Java Language Syntax for Experienced Programmers · PDF fileJava Language Syntax for...

25
1 1 Java Language Syntax for Experienced Programmers COMP440 Penn State Harrisburg January 16, 2007 © Julia M. Lobur 2 Java History Began as “Oak” by James Gosling at Sun Microsystems 1991. Java 1.0 released 1995. Key ideas Write once, run anywhere Use C++ syntax and object orientation Make language safer than C++ Many built-in classes helpful to programmer Java 1.02: 250 classes Java 1.1: 500 classes Java 2 1.2 - 1.4: 2300 classes Java 5 1.5: 3500 classes

Transcript of Java Language Syntax for Experienced Programmers · PDF fileJava Language Syntax for...

Page 1: Java Language Syntax for Experienced Programmers · PDF fileJava Language Syntax for Experienced Programmers ... – Write once, run anywhere – Use C++ syntax and object ... •

1

1

Java Language Syntax for Experienced Programmers

COMP440Penn State Harrisburg

January 16, 2007

© Julia M. Lobur

2

Java History• Began as “Oak” by James Gosling at Sun

Microsystems 1991. Java 1.0 released 1995.• Key ideas

– Write once, run anywhere– Use C++ syntax and object orientation– Make language safer than C++

• Many built-in classes helpful to programmer– Java 1.02: 250 classes– Java 1.1: 500 classes– Java 2 1.2 - 1.4: 2300 classes– Java 5 1.5: 3500 classes

Page 2: Java Language Syntax for Experienced Programmers · PDF fileJava Language Syntax for Experienced Programmers ... – Write once, run anywhere – Use C++ syntax and object ... •

2

3

Java Execution Environment• Write once run anywhere achieved by Java

virtual machine (JVM).– Java compiler output is a bytecode class file. – Bytecode is input to the JVM, which runs it.

• A JVM must be installed on a system in order for your program to run.

• JVMs exist for Linux, Unix, Windows 9x, 2000, XP, embedded and mobile platforms (PDAs, cell phones, etc.)

See Essentials of Computer Organization and Architecture 2/e Pp 439 - 445

4

Object Orientation

Java is a pure OO language, which means:– Everything is an object.

• Think of an object as a fancy variable• “An object has state, behavior, and identity.”

(Grady Booch)– A program consists of collaborating objects.

• They collaborate only by exchanging messages

Page 3: Java Language Syntax for Experienced Programmers · PDF fileJava Language Syntax for Experienced Programmers ... – Write once, run anywhere – Use C++ syntax and object ... •

3

5

Object Orientation

Java is a pure OO language, which means:– Each object has its own memory made up of

other objects.• You create a new kind of object by organizing

existing objects.– Every object has a type.

• Each object is an instance of a class, in which “class” is synonymous with “type.”

– All objects of a particular type can receive the same messages.

6

Object Orientation• Messages are exchanged between objects

through their interfaces• Whenever a message is received through an

interface, a suitable method is invoked.• The method provides a service, and may return

a value in another message.• The initiating object doesn’t care how the

service is provided.– This is one aspect of encapsulation or information

hiding.

Page 4: Java Language Syntax for Experienced Programmers · PDF fileJava Language Syntax for Experienced Programmers ... – Write once, run anywhere – Use C++ syntax and object ... •

4

7

Object Orientation

Your author’s class notation:

8

Object Orientation

Your author’s class notation differs from real UML:

Page 5: Java Language Syntax for Experienced Programmers · PDF fileJava Language Syntax for Experienced Programmers ... – Write once, run anywhere – Use C++ syntax and object ... •

5

9

Object Orientation

One of the key principles of OO is the idea of inheritance. You must master it.

A base class is also known as a superclassor parent class.

A derived class is also known as a subclass or child class.

10

Object Orientation

An example:

Circle, Square, and Triangle extend the base class Shape.

This is an “IS-A”relation-ship.

Page 6: Java Language Syntax for Experienced Programmers · PDF fileJava Language Syntax for Experienced Programmers ... – Write once, run anywhere – Use C++ syntax and object ... •

6

11

Object Orientation

Aggregationprovides the “HAS-A”relationship.

12

• An object is an instance of a class.– Think of a class as a highly complex data type,

and an object is a “variable” of that type.• Objects are created using the new operator.

– When we do this, a special constructormethod is invoked. Every class has a default constructor, and you can write your own.

• Objects are destroyed when there are no longer any references to them.– Java does this for you.

Object Orientation

Page 7: Java Language Syntax for Experienced Programmers · PDF fileJava Language Syntax for Experienced Programmers ... – Write once, run anywhere – Use C++ syntax and object ... •

7

13

• A class is a named collection of fields,(data members) and methods (member functions).– Think of a class as a highly complex data type,

and an object is a “variable” of that type.• Unless you specify otherwise, each object

instance contains its own copy of all fields and methods.– The static keyword prevents this from

happening.

Class Composition

14

A class definition looks like this:

Class AClassName {

dataType var1;

dataType var2;

ReturnType methodName(type1 varX, type1 varY) {

/* Method body */

}

}

Class Composition

Page 8: Java Language Syntax for Experienced Programmers · PDF fileJava Language Syntax for Experienced Programmers ... – Write once, run anywhere – Use C++ syntax and object ... •

8

15

An example:Class MyFirstClass {

int var1;float var2 = 14.75;int addThese(int varX, int varY) {

return(varX + varY);} // addThese

} // MyFirstClass

MyFirstClass mfc = new MyFirstClass();float f = mfc.var2;int i = mfc.addThese(3, 9);

Class Composition

16

Primitive types:Java Data Types

Page 9: Java Language Syntax for Experienced Programmers · PDF fileJava Language Syntax for Experienced Programmers ... – Write once, run anywhere – Use C++ syntax and object ... •

9

17

• Each primitive type (except void) has a corresponding wrapper class.– Wrapper classes are used when you need to treat

a primitive type like an object.• Strings are another special case. They are

not primitive data types, but they do not require the new operator when creating a string reference.

Java Data Types

18

• If you do not want multiple copies of data and methods, you can declare a “class level”instance using the static keyword.

• The namespace of a Java program is the library (called a package) that it is in.

• To allow use of objects that are outside the current package, the import keyword is used.

Class Composition

import java.util.ArrayList;static float f;

Page 10: Java Language Syntax for Experienced Programmers · PDF fileJava Language Syntax for Experienced Programmers ... – Write once, run anywhere – Use C++ syntax and object ... •

10

19

• Dozens of packages (class libraries) are built into Java.

• The default class library is java.lang. You do not have to import this library.– It contains the wrapper classes and System, among

others.• You’ll need to import java.util into just about

every class you write.– The Java documentation tells you what you need to

know. Or visit: http://java.sun.com/j2se/1.5.0/docs/api/

Class Composition

20

• A runnable Java program consists of a class and one--only one-- main() method.

• The name of the source file must be the same as the name of the class.

• The class and main method must have public access.

• The main() method always must allow for a argument list string, even if you don’t need it.

Program Composition

public static void main(String args[]) {// code here

}

Page 11: Java Language Syntax for Experienced Programmers · PDF fileJava Language Syntax for Experienced Programmers ... – Write once, run anywhere – Use C++ syntax and object ... •

11

21

An Example Program//:HelloDate.java

import java.util.*;/** Displays a string and today's date.* @author Bruce Eckel* @version 4.0

*/public class HelloDate {

/** Sole entry point to class & app* @param args array of string* @throws exceptions: None thrown

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

System.out.println("Hello, it's: ");System.out.println(new Date());

}} ///:~

22

To Write and Compile Programs

• If you are not using a computer in one of our labs, you’ll need to download and install the Java 5 SDK from java.sun.com on your computer.

• Find a decent text editor, such as EditPadLite. Must be able to save plain text!

• Create a DOS.bat file to set path to include the Java binary directory and the directory where you will store your Java code. (See next slide.)

• Download Eckel’s code from www.mindview.netand unzip it one directory below your source directory.

Page 12: Java Language Syntax for Experienced Programmers · PDF fileJava Language Syntax for Experienced Programmers ... – Write once, run anywhere – Use C++ syntax and object ... •

12

23

To Write and Compile Programs

• Sample DOS bat file. (Created using EditPadLite).

set PATH=%PATH%; C:\PROGRA~1\Java\jdk1.5.0_10\bin

set CLASSPATH=C:\Java_Source\comp440\Eckel; C:\Java_Source;.

cd C:\Java_Source\comp440

Note: Line breaks should not be in your bat file! Each command should be on a single line.

24

To Write and Compile Programs

• After your PATH and CLASSPATH system variables are set, you can compile and run the Java program

C:\Java_Source\comp440>javac HelloDate.java[If you don’t get an error message, your program compiled okay.]

C:\Java_Source\comp440 >java HelloDate

The last line invokes the Java virtual machine, which in turn executes the bytecode stored in HelloDate.class.

Page 13: Java Language Syntax for Experienced Programmers · PDF fileJava Language Syntax for Experienced Programmers ... – Write once, run anywhere – Use C++ syntax and object ... •

13

25

• The set of unary and binary operators is the same in Java as it is in the other languages you have studied.

• We will discuss only the more interesting ones.

• A comprehensive set of arithmetic operation examples can be found in your text on pages 123 - 132.

Operators

26

• As in C/C++, Java has a shortcut assignment operator.

• Also like C/C++, Java has pre-increment/ decrement and post-increment/decrement operations.

Operators

a *= b; // Multiply a by b.

a++; // Evaluate and then increment a.++a; // Increment a and then evaluate.

See demo program on Page 102.

Page 14: Java Language Syntax for Experienced Programmers · PDF fileJava Language Syntax for Experienced Programmers ... – Write once, run anywhere – Use C++ syntax and object ... •

14

27

• Assignment and logical equality are indicated by two different operators.

• Logical operators and connectives are ==, !=, &&, ||.

Operators

a = b; // Set a = b.if (a==b)

if (a=b) // Throws an error unless // a and b are boolean!

28

• The equality operator for objects tells us whether two objects are identical, not whether their contents are the same.

• Use the equals()method for wrapper classes!.

Operators

Integer a = new Integer(3);Integer b = new Integer(3);

if (a == b)// Evaluates false!

if a.equals(b)// Evaluates true.

Page 15: Java Language Syntax for Experienced Programmers · PDF fileJava Language Syntax for Experienced Programmers ... – Write once, run anywhere – Use C++ syntax and object ... •

15

29

• Conditional statements.”short circuit.”• In the code fragment below, the evaluation stops

as soon as a condition that would make the statement false is encountered.

• So if a != b, the other two comparisons never happen.

Operators

if ((a == b) && (d >= g) && (b < c))

30

• Ternary if-else

• If boolean-expression is true, then stmt1executes, otherwise, stmt2 executes.

• Not recommended: It’s all the same to the compiler and this is hard to read and understand.

Operators

boolean-expression ? stmt1 : stmt2

Page 16: Java Language Syntax for Experienced Programmers · PDF fileJava Language Syntax for Experienced Programmers ... – Write once, run anywhere – Use C++ syntax and object ... •

16

31

• String concatenation uses the “+” operator.

Operators

String hello = new String(“Hello”);String world = new String(“world.”); String hw1, hw2;hw1 = hello + “ “ + world;hw2 = hello + “ world.”;if (hw1 == hw2)

System.out.println(“Same world.”);else

System.out.println(“Different world.”);

32

• Java has 16 levels of precedence.• An easy mnemonic:

– Ulcer Unary + - ++ --– Addicts Arithmetic and Shift * / % + - << >>– Really Relational < <= > >= == !=– Like Logical and bitwise && || & |– C Conditional (ternary) cond ? x : y– A Lot Assignment = *= +=, etc.

• When in doubt-- or for clarity-- use parens! The compiler doesn’t care if you have too many. Too few, and you breed bugs!

Operators

Page 17: Java Language Syntax for Experienced Programmers · PDF fileJava Language Syntax for Experienced Programmers ... – Write once, run anywhere – Use C++ syntax and object ... •

17

33

• Certain characters indicate particular numeric types as follows:– d or D: double 0.7D– l or L: long 14L– x or X hex 0x04B3– leading zero for octal: 075– e or E for exponential: 0.0314E2

• true and false are boolean literals, unlike C/C++ where any nonzero is “true”

Literals and Promotion

Note: Use of lowercase L is not recommended.

34

• Arrays consist of a set of identical element types that are accessed through a numerical index.– The array index begins at zero.

• Declaration syntax

• Example

Arrays

<type> <name> = new <type>[size];

int aList[] = new int[32];

We will study these in much detail later.

Page 18: Java Language Syntax for Experienced Programmers · PDF fileJava Language Syntax for Experienced Programmers ... – Write once, run anywhere – Use C++ syntax and object ... •

18

35

• Java automatically promotes an rvalue to the type of an lvalue if the lvalue is wider.

• If you are going from a wider type to a narrower one, you need to type cast.

• You assume responsibility for truncation or overflow.

Literals and Promotion

int iNum = 25;long lNum = iNum;

long lNum = 25;int iNum = (int) lNum;byte bNum = (byte) 32;

36

• An identifier is a name that is given to a variable (field), method or class. Rules are:– No length limit– Consist of letters, numbers, $, _ (underscore)– Cannot begin with a number, avoid initial $ or _– Case sensitive– Cannot be reserved word (next slide)

• Conventions– Class names have initial capital– Constants all caps (separate words with _)– All other identifiers start with lowercase, camel case all

subsequent words.

Java Identifiers

Page 19: Java Language Syntax for Experienced Programmers · PDF fileJava Language Syntax for Experienced Programmers ... – Write once, run anywhere – Use C++ syntax and object ... •

19

37

Reserved Words

This is the entire list of Java keywords:

abstractassertbooleanbreakbytecasecatchcharclassconst

continuedefaultdodoubleelseenumextendsfinalfinallyfloat

forifgotoimplementsimportinstanceofintinterfacelongnative

newpackageprivateprotectedpublicreturnshortstaticstrictfpsuper

switchsynchronizedthisthrowthrowstransienttryvoidvolatilewhile

goto and const are not used.

38

Controlling Execution

• if statements

if (<boolean expression>) {// statements executed if true

}else {

// statements executed if false}

Page 20: Java Language Syntax for Experienced Programmers · PDF fileJava Language Syntax for Experienced Programmers ... – Write once, run anywhere – Use C++ syntax and object ... •

20

39

Controlling Execution

• if statement example

otPay = 0;if (hours > 40) {

regularPay = wageRate * 40;otPay = (hoursWorked - 40) * wageRate * 1.5;

}elseregularPay = wageRate * hoursWorked;

grossPay = regularPay + otPay;

40

Controlling Execution

• switch statementswitch (integer value) {

case intVal1 : statement(s);[break;]

case intVal2 : statement(s);[break;]

case intValn : statement(s);[break;]

[default: statement(s);]}

Page 21: Java Language Syntax for Experienced Programmers · PDF fileJava Language Syntax for Experienced Programmers ... – Write once, run anywhere – Use C++ syntax and object ... •

21

41

Controlling Execution

• switch statement example

switch (partNo) {case 32 : case 789 : isRoofingNail = true;

break;case 193 : isCotterPin = true;

break;default : isRoofingNail = false;

isCotterPin = false;}

42

Controlling Execution

• while statements

while (<condition>) {// Statement(s) }

do {// Statement(s)

}while (<condition>);

What’s the difference?

Page 22: Java Language Syntax for Experienced Programmers · PDF fileJava Language Syntax for Experienced Programmers ... – Write once, run anywhere – Use C++ syntax and object ... •

22

43

Controlling Execution

• for loops

• You can have any number of expressions in all parts separated by commas.

for ([<initialization(s)>] ; [<boolean expression(s)>] ;

[<step statement(s)>)] {// Statement(s)

}

44

Controlling Execution

• for loop examples

char letters[] = new char[26];char aChar = 65;

for (int i = 0 ; i < 26 ; i++, aChar++) letters[i] = aChar;

for ( ; ; ) // do something;

Page 23: Java Language Syntax for Experienced Programmers · PDF fileJava Language Syntax for Experienced Programmers ... – Write once, run anywhere – Use C++ syntax and object ... •

23

45

Controlling Execution

• foreach loop syntax

char letters[] = new char[26];char aChar = 65;for (int i = 0 ; i < 26 ; i++, aChar++)

letters[i] = aChar;

for (char ch : letters) System.out.print(ch + " ");

Note: You must traverse the array in order andyou cannot modify any of its members.

46

Controlling Execution

• break andcontinue

• Can be labeled or unlabeled

• Intended particularly to control execution in nested loops (for, while, etc.)

label1:outer-iteration {

inner-iteration {// …break; // (1)//…continue; // (2)// …continue label1; // (3)// …break label1; // (4)

}}

Page 24: Java Language Syntax for Experienced Programmers · PDF fileJava Language Syntax for Experienced Programmers ... – Write once, run anywhere – Use C++ syntax and object ... •

24

47

Controlling Execution

• Unlabeled continue goes to top of loop in which it is located.

• Labeled continue goes to the label and reenters the loop directly following the label.

• break exits the loop in which it is located.• Labeled break exits the loop directly

following the label. • return immediately exits the method in

which it is located (even main()).

48

Summary

• A Java program consists of classes from which objects are instantiated.

• Classes consist of methods and data.• Java syntax is much like C++ only safer.• Java 5 has over 3500 classes as part of base

language.• New operation is the foreach iterator.• Be sure that you path and classpath are set to

point to your Java installation and source code folder, respectively.

Page 25: Java Language Syntax for Experienced Programmers · PDF fileJava Language Syntax for Experienced Programmers ... – Write once, run anywhere – Use C++ syntax and object ... •

25

49