HelloWorld.

import java.awt.*; public class HelloWorld extends java.applet.Applet { TextField t; public void init() { t = new TextField(50); t.setText(“Hello World!"); add(t); } }

Java programs Bytecodes

• Java programs are created as text files using a text • editor (like emacs) – machine instruction for the Java processor • Save to disk with .java file extension • javac translates the source program into HelloWorld.java bytecodes • The file contains characters (stored as bytes) • Bytecode file has same name as the source program – file can be printed, displayed on monitor, or edited with a .class file extension: – file cannot be directly executed (run) by the computer HelloWorld.class system • Java must first translate the program into bytecodes before it can be run HelloWorld.java javac HelloWorld.class Java source program Java bytecodes compiler

Java Virtual Machine (JVM) Java applets

• Bytecode (class) file will contain exactly the same • An applet is a Java bytecode program that runs on a bytecodes no matter what computer system is used Web browser • Bytecode file is executed by a Java bytecode interpreter • Most newer Web browsers have Java interpreters – processor specific executable program • Web pages on the Internet contain instructions that send • Each type of computer system has its own Java Java bytecodes to your computer interpreter that can run on that system • Web browser runs the Java applet with its built-in • Any computer system can execute Java bytecode interpreter programs if it has a Java interpreter • Computers with Java interpreters are called Java Virtual Machines – a “computer” with a Java processor that can run Java bytecodes

1 Data types Java data types

• Computer memory stores arbitrary bit patterns • Primitive • Meaning of a bit pattern depends on its use – types of data that are so fundamental ways to • Pattern used for a particular string of bits is a data type represent them are built into Java – values are any kind of data a computer can process • Object – all values are represented using some data type – built-in or user-defined • Example: What does the following pattern of 16 bits represent? 0000000001100111 • No way to know without more information • If data type is short (a Java type) it represents 103

Primitive data types Java primitive data types

• All primitive values belong to one of eight primitive types Primitive Type Description Range byte short int long float byte 8-bit integer -128 to 127 double char boolean short 16-bit integer -32768 to 32767 • Primitive data types use a fixed number of bytes -2147483648 to int 32-bit integer – four of these types designate different sizes of 2147483647 bounded integers: byte, short, int, long long 64-bit integer -263 to 263-1 • A programmer can not create new primitive data types float 32-bit floating point 10-46 to 1038 • Any data type you invent will be a type of object double 64-bit floating point 10-324 to 10308 • Most commonly used types in practice: int, boolean, and double char Unicode character boolean Boolean variable false and true

Basic operators Variable declaration

Operator Java Description • Declaration Assignment = assigns rhs to lhs type ; • Declaration + initialization: addition, subtraction, Arithmetic +,-,*,/,% multiplication, division, type = ; remainder • Variable names negative, auto increment, auto Unary -,++,-- – any combination of letters, numbers, and the decrement underscore character Equality ==, != equals to, not equals to – may not start with number

less than, less than or equals – may not be reserved word Relational <,<=,>,>= to, greater than, greater than or • e.g. int, return, if, for, while equals to – may not be same as a subroutine name Logical &&,||,! AND, OR, NOT – case-sensitive (num and Num are different)

2 Examples Operator precedence

• int x, y, z; • Evaluate a + b * c • int sum = 0; – multiplication first? a + (b * c) • float f; – addition first? (a + b) * c • double pi = 3.14; • Java solves this problem by assigning priorities to • char first = ‘T’, operators (operator precedence) middle = ‘L’, Operator priority last = ‘B’; – operators with high priority are evaluated before (highest to lowest) • char first = ‘T’; operators with low priority char middle = ‘L’; 1. ( ) char last = ‘B’; – operators with equal priority are evaluated left to right 2. * / % 3. + - 4. =

When in doubt, use parentheses Examples

• a + b * c = a + (b * c) • Java adheres to traditional order of operations – because * has higher priority than + • * and / have higher priority than + and – • To perform the + operation first we need to use int x = 3 + 5 * 6; (x = 33) parentheses int y = (3 + 5) * 6; (y = 48) – (a + b) * c • Parentheses are free, use them liberally • If in any doubt use extra parentheses to ensure the int z = ((3 + 5) * (6)); (z = 48) correct order of evaluation • Equal priority operations are evaluated left-to-right in the – parentheses are free! absence of parentheses – cause no extra work for the computer int w = 3 * 4 / 2 * 6; (w = 36) – only make it easier for you to work out what is int x = 3 * 4 / (2 * 6); (x = 1) happening int y = 3 * 4 + 2 * 6; (y = 24) int z = 3 * (4 + 2) * 6; (z = 108)

Syntax and semantics Automatic type conversion

• Addition, subtraction: + and –, int and double • Mixed type expressions Example: int x = 21+4; (x = 25) are converted to higher Convert Fahrenheit to Celsius double y = 14.1-2; (y = 12.1) compatible types • If all operands are of type • Multiplication: *, int and double double F=41.0; int then result is type int int x = 21*4; (x = 84) double C=(F-32.0)*(5/9); • If any operand is of type double y = 14.1*2.5; (y = 35.25) double then result is of Question: What is the value of C? • Division: /, different for int and double type double a) 5 int x = 21/4; (x = 5) • Cannot convert to a lower b) 0.0 double y = 21/4; (y = 5.0) type c) 9.0 double y = 21/4.0; (y = 5.25) • Conversion may result in d) 5.0 • Modulus: %, only for int loss of precision e) 9 int x = 21%4; (x = 1)

3 More expressions Syntax errors

int g = 12 + 2.5; int n = 1 – 2 * 3 – (4 + 5); • The following Java subroutine computes the inclusive What is the value of g? What is the value of n? sum between two integers. Find all the syntax errors. a. 0 a. -4 b. 12 b. -2 c. 14 c. 2 int sumBetween( x, y ) d. 14.5 d. 4 { e. error e. none of the above int z = x; Int sum = 1; int x = 8 * (7 – 6 + 5) % (4 + 3 / 2) – 1; What is the value of x? while( z <= y ){ a. -1 sum = sum*z; b. 0 z++ c. 2 d. 3 } e. none of the above }

Logic errors Java objects

• The computer will do precisely what you say even • Java is an object-oriented programming language though it may not be what you want – use objects to define both the data type and the • What is wrong with this code? operations that can be applied to the data • Objects have attributes and functionality int sumBetween( int x, int y ) – attributes describe the state of the object { – the functionality of an object is the set of actions the int z = x; object can perform int sum = 1; • In Java, we define an object’s attributes using variables while( z <= y ) and its functionality using methods sum = sum*z; z++; }

Real-world objects Java classes

• Suppose we want to describe a car in terms of its • Java objects are created using classes attributes and functionality • Encapsulation • Attributes: – combining elements to create a new entity – int year; int mileage; • A class encapsulates the variables and methods that – String make; String model; define an object – boolean manual_transmission; • Instantiation • Methods: – the act of creating an object – void brake() – int getMileage() – objects are called class instances – boolean needsGas() • Java provides many predefined classes – void shift(int gear) • You can also define your own classes

4 Java String class Instantiation

• The String class represents character strings • Creating an object is called instantiation String first = “Tammy”; – the new operator is used with class name String last = “Bailey”; • Example: Create a TextField object TextField t = new TextField(); • Strings can be concatenated (added together) using the concatenation operator + • Can create multiple instances of the same class String fullname = first + “ ” + last; TextField t1 = new TextField(); TextField t2 = new TextField(); • Testing for equality: • Exception first.equals(“Tammy”); /* returns true */ – the new operator is not required when creating a first.equals(“Amy”); /* returns false */ String

Java TextField class Invoking an object’s methods

• The TextField class allows the editing and display of a • Once we create a text field, we can perform actions on it single line of text using its methods TextField t = new TextField(); • The variables and methods of an object are accessed using the dot operator • Methods TextField t = new TextField(); – setText(String s) t.setText(“Hello”); • set the text of the field to the string s • Syntax – String getText() – object.verb(data); • get the text of the field and assign it to a variable of – Perform verb on object using data type string

Interactive objects Action listeners

• User interaction determines the behavior of the program • If we want a button to know when it is clicked, we have • Program receives user input through mouse and to enable it to “listen” for user input keyboard and performs associated method or action • Use the button method addActionListener • Text fields – edit and display single line of text Button b = new Button(“click!”); • Buttons b.addActionListener(this); – can specify action to occur when button is clicked • If we don’t invoke the addActionListener method on a button, nothing will happen when the button is clicked

5 Example Actions

• We would like our applet to do the following: • We specify actions to occur when a button is clicked in – get text from text field t1 and display it in text field t2 the actionPerformed method when button b is clicked public void actionPerformed(ActionEvent event) TextField t1 = new TextField(); { TextField t2 = new TextField(); Object cause = event.getSource(); Button b = new Button(“copy text”); if(cause == b) b.addActionListener(this); { t2.setText(t1.getText()); } }

Numeric input Type wrappers

• Suppose we want an applet that allows the user to enter • Convert primitive types into objects two integers and display the minimum Primitive Type Wrapper Type – a text field contains a character string byte Byte – If we want to perform numeric operations on the input from a text field, we have to convert the string to a short Short numeric data type int Integer – numbers are primitive data types, not objects long Long float Float • Can convert using Java type wrappers double Double char Character boolean Boolean

String conversion Action performed for integer input

• Convert to String str byte b public void actionPerformed(ActionEvent event) byte b = Byte.parseByte(str); { • Convert to String str short s Object cause = event.getSource(); short s = Short.parseShort(str); int x = Integer.parseInt(t1.getText()); • Convert to String str int i int y = Integer.parseInt(t2.getText()); int i = Integer.parseInt(str); • Convert String str to long l if(cause == b) long l = Long.parseLong(str); { • Convert String str to float f int min = minimum(x,y); float f = Float.parseFloat(str); t3.setText(“The minimum is: ” + min); • Convert String str to double d } double d = Double.parseDouble(str); }

6