HelloWorld.java import java.awt.*; public class HelloWorld extends

Slides:



Advertisements
Similar presentations
Types and Arithmetic Operators
Advertisements

Data Types in Java Data is the information that a program has to work with. Data is of different types. The type of a piece of data tells Java what can.
1 Chapter 4 Language Fundamentals. 2 Identifiers Program parts such as packages, classes, and class members have names, which are formally known as identifiers.
Aalborg Media Lab 21-Jun-15 Software Design Lecture 2 “ Data and Expressions”
Program Elements We can now examine the core elements of programming (as implemented in Java) We focuse on: data types variable declaration and use, constants.
ECE122 L3: Expression Evaluation February 6, 2007 ECE 122 Engineering Problem Solving with Java Lecture 3 Expression Evaluation and Program Interaction.
Hello, world! Dissect HelloWorld.java Compile it Run it.
Java Primitives The Smallest Building Blocks of the Language (corresponds with Chapter 2)
Chapter 2: Basic Elements of Java J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Second Edition.
DEPARTMENT OF COMPUTER SCIENCE & TECHNOLOGY FACULTY OF SCIENCE & TECHNOLOGY UNIVERSITY OF UWA WELLASSA 1 CST 221 OBJECT ORIENTED PROGRAMMING(OOP) ( 2 CREDITS.
Lecture 2 Object Oriented Programming Basics of Java Language MBY.
Introduction to Java Applications Part II. In this chapter you will learn:  Different data types( Primitive data types).  How to declare variables?
CS 11 java track: lecture 1 Administrivia need a CS cluster account cgi-bin/sysadmin/account_request.cgi need to know UNIX
Introduction to Computer Systems and the Java Programming Language.
 JAVA Compilation and Interpretation  JAVA Platform Independence  Building First JAVA Program  Escapes Sequences  Display text with printf  Data.
1 INTRODUCTION TO PROBLEM SOLVING AND PROGRAMMING.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 2 Basic Elements of Java.
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition.
1 Chapter 3 Syntax, Errors, and Debugging Fundamentals of Java: AP Computer Science Essentials, 4th Edition Lambert / Osborne.
Chapter 3 Syntax, Errors, and Debugging Fundamentals of Java.
CompSci Today’s topics Parsing Java Programming Notes from Tammy Bailey Reading Great Ideas, Chapter 3 & 4.
Programming in Java (COP 2250) Lecture 4 Chengyong Yang Fall, 2005.
VISUAL C++ PROGRAMMING: CONCEPTS AND PROJECTS Chapter 2A Reading, Processing and Displaying Data (Concepts)
Operator precedence.  Evaluate a + b * c –multiplication first? a + (b * c) –addition first? ( a + b) * c  Java solves this problem by assigning priorities.
Today’s topics Java Input More Syntax Upcoming Decision Trees More formal treatment of grammers Reading Great Ideas, Chapter 2.
Java Programming: From Problem Analysis to Program Design, Second Edition 1 Lecture 1 Objectives  Become familiar with the basic components of a Java.
Java Programming. Objects  Java is an object-oriented programming language –use objects to define both the data type and the operations that can be applied.
© 2004 Pearson Addison-Wesley. All rights reserved August 27, 2007 Primitive Data Types ComS 207: Programming I (in Java) Iowa State University, FALL 2007.
Chapter 4 Assignment Statement
Chapter 7: Expressions and Assignment Statements
Lecture 3 Java Operators.
Chapter 3 Syntax, Errors, and Debugging
BASIC ELEMENTS OF A COMPUTER PROGRAM
Building Java Programs
Yanal Alahmad Java Workshop Yanal Alahmad
Java Primer 1: Types, Classes and Operators
Primitive Data Types August 28, 2006 ComS 207: Programming I (in Java)
Chapter 7: Expressions and Assignment Statements
Multiple variables can be created in one declaration
Assignment and Arithmetic expressions
Primitive Data, Variables, Loops (Maybe)
Variables, Expressions, and IO
Chapter 3 Assignment Statement
Type Conversion, Constants, and the String Object
Java Programming: From Problem Analysis to Program Design, 4e
IDENTIFIERS CSC 111.
Building Java Programs Chapter 2
Starting JavaProgramming
Introduction to C++ Programming
Chapter 2: Basic Elements of Java
Programming Funamental slides
Building Java Programs
Fundamentals 2.
Building Java Programs
Building Java Programs Chapter 2
elementary programming
Building Java Programs
Chapter 2 Programming Basics.
Building Java Programs
Building Java Programs
Building Java Programs
Building Java Programs
Building Java Programs
Building Java Programs
Introduction to Primitives
Building Java Programs
Primitive Types and Expressions
Building Java Programs Chapter 2
Building Java Programs
Building Java Programs
Presentation transcript:

HelloWorld.java 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 Java programs are created as text files using a text editor (like emacs) Save to disk with .java file extension HelloWorld.java The file contains characters (stored as bytes) file can be printed, displayed on monitor, or edited file cannot be directly executed (run) by the computer system Java must first translate the program into bytecodes before it can be run

Bytecodes Java bytecode machine instruction for the Java processor Java compiler javac translates the source program into bytecodes Bytecode file has same name as the source program with a .class file extension: HelloWorld.class HelloWorld.java javac HelloWorld.class Java compiler source program Java bytecodes

Java Virtual Machine (JVM) Bytecode (class) file will contain exactly the same bytecodes no matter what computer system is used Bytecode file is executed by a Java bytecode interpreter processor specific executable program Each type of computer system has its own Java interpreter that can run on that system Any computer system can execute Java bytecode 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

Java applets An applet is a Java bytecode program that runs on a Web browser Most newer Web browsers have Java interpreters Web pages on the Internet contain instructions that send Java bytecodes to your computer Web browser runs the Java applet with its built-in interpreter

Data types Computer memory stores arbitrary bit patterns Meaning of a bit pattern depends on its use Pattern used for a particular string of bits is a data type values are any kind of data a computer can process all values are represented using some data type 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

Java data types Primitive types of data that are so fundamental ways to represent them are built into Java Object built-in or user-defined

byte short int long float double char boolean Primitive data types All primitive values belong to one of eight primitive types byte short int long float double char boolean Primitive data types use a fixed number of bytes four of these types designate different sizes of bounded integers: byte, short, int, long A programmer can not create new primitive data types Any data type you invent will be a type of object Most commonly used types in practice: int, boolean, and double

Java primitive data types Primitive Type Description Range byte 8-bit integer -128 to 127 short 16-bit integer -32768 to 32767 int 32-bit integer -2147483648 to 2147483647 long 64-bit integer -263 to 263-1 float 32-bit floating point 10-46 to 1038 double 64-bit floating point 10-324 to 10308 char Unicode character boolean Boolean variable false and true

Basic operators Operator Java Description Assignment = assigns rhs to lhs Arithmetic +,-,*,/,% addition, subtraction, multiplication, division, remainder Unary -,++,-- negative, auto increment, auto decrement Equality ==, != equals to, not equals to Relational <,<=,>,>= less than, less than or equals to, greater than, greater than or equals to Logical &&,||,! AND, OR, NOT

type <variable-name> = <value>; Variable declaration Declaration type <variable-name>; Declaration + initialization: type <variable-name> = <value>; Variable names any combination of letters, numbers, and the underscore character may not start with number may not be reserved word e.g. int, return, if, for, while may not be same as a subroutine name case-sensitive (num and Num are different)

Examples int x, y, z; int sum = 0; float f; double pi = 3.14; char first = ‘T’, middle = ‘L’, last = ‘B’; char first = ‘T’; char middle = ‘L’; char last = ‘B’;

Operator precedence Evaluate a + b * c multiplication first? a + (b * c) addition first? (a + b) * c Java solves this problem by assigning priorities to operators (operator precedence) operators with high priority are evaluated before operators with low priority operators with equal priority are evaluated left to right Operator priority (highest to lowest) ( ) * / % + - =

When in doubt, use parentheses a + b * c = a + (b * c) because * has higher priority than + To perform the + operation first we need to use parentheses (a + b) * c If in any doubt use extra parentheses to ensure the correct order of evaluation parentheses are free! cause no extra work for the computer only make it easier for you to work out what is happening

Examples Java adheres to traditional order of operations * and / have higher priority than + and – int x = 3 + 5 * 6; (x = 33) int y = (3 + 5) * 6; (y = 48) Parentheses are free, use them liberally int z = ((3 + 5) * (6)); (z = 48) Equal priority operations are evaluated left-to-right in the absence of parentheses int w = 3 * 4 / 2 * 6; (w = 36) int x = 3 * 4 / (2 * 6); (x = 1) int y = 3 * 4 + 2 * 6; (y = 24) int z = 3 * (4 + 2) * 6; (z = 108)

Syntax and semantics Addition, subtraction: + and –, int and double int x = 21+4; (x = 25) double y = 14.1-2; (y = 12.1) Multiplication: *, int and double int x = 21*4; (x = 84) double y = 14.1*2.5; (y = 35.25) Division: /, different for int and double int x = 21/4; (x = 5) double y = 21/4; (y = 5.0) double y = 21/4.0; (y = 5.25) Modulus: %, only for int int x = 21%4; (x = 1)

Automatic type conversion Mixed type expressions are converted to higher compatible types If all operands are of type int then result is type int If any operand is of type double then result is of type double Cannot convert to a lower type Conversion may result in loss of precision Example: Convert Fahrenheit to Celsius double F=41.0; double C=(F-32.0)*(5/9); Question: What is the value of C? 5 0.0 9.0 5.0 9

More expressions int g = 12 + 2.5; int n = 1 – 2 * 3 – (4 + 5); What is the value of g? 12 14 14.5 error int n = 1 – 2 * 3 – (4 + 5); What is the value of n? -4 -2 2 4 none of the above int x = 8 * (7 – 6 + 5) % (4 + 3 / 2) – 1; What is the value of x? -1 2 3 none of the above

Syntax errors The following Java subroutine computes the inclusive sum between two integers. Find all the syntax errors. int sumBetween( x, y ) { int z = x; Int sum = 1; while( z <= y ){ sum = sum*z; z++ }

Logic errors The computer will do precisely what you say even though it may not be what you want What is wrong with this code? int sumBetween( int x, int y ) { int z = x; int sum = 1; while( z <= y ) sum = sum*z; z++; }

Java objects Java is an object-oriented programming language use objects to define both the data type and the operations that can be applied to the data Objects have attributes and functionality attributes describe the state of the object the functionality of an object is the set of actions the object can perform In Java, we define an object’s attributes using variables and its functionality using methods

Real-world objects Suppose we want to describe a car in terms of its attributes and functionality Attributes: int year; int mileage; String make; String model; boolean manual_transmission; Methods: void brake() int getMileage() boolean needsGas() void shift(int gear)

Java classes Java objects are created using classes Encapsulation combining elements to create a new entity A class encapsulates the variables and methods that define an object Instantiation the act of creating an object objects are called class instances Java provides many predefined classes You can also define your own classes

Java String class The String class represents character strings String first = “Tammy”; String last = “Bailey”; Strings can be concatenated (added together) using the concatenation operator + String fullname = first + “ ” + last; Testing for equality: first.equals(“Tammy”); /* returns true */ first.equals(“Amy”); /* returns false */

Instantiation Creating an object is called instantiation the new operator is used with class name Example: Create a TextField object TextField t = new TextField(); Can create multiple instances of the same class TextField t1 = new TextField(); TextField t2 = new TextField(); Exception the new operator is not required when creating a String

Java TextField class The TextField class allows the editing and display of a single line of text TextField t = new TextField(); Methods setText(String s) set the text of the field to the string s String getText() get the text of the field and assign it to a variable of type string

Invoking an object’s methods Once we create a text field, we can perform actions on it using its methods The variables and methods of an object are accessed using the dot operator TextField t = new TextField(); t.setText(“Hello”); Syntax object.verb(data); Perform verb on object using data

Interactive objects User interaction determines the behavior of the program Program receives user input through mouse and keyboard and performs associated method or action Text fields edit and display single line of text Buttons can specify action to occur when button is clicked

Action listeners If we want a button to know when it is clicked, we have to enable it to “listen” for user input Use the button method addActionListener Button b = new Button(“click!”); b.addActionListener(this); If we don’t invoke the addActionListener method on a button, nothing will happen when the button is clicked

Example We would like our applet to do the following: get text from text field t1 and display it in text field t2 when button b is clicked TextField t1 = new TextField(); TextField t2 = new TextField(); Button b = new Button(“copy text”); b.addActionListener(this);

Actions We specify actions to occur when a button is clicked in the actionPerformed method public void actionPerformed(ActionEvent event) { Object cause = event.getSource(); if(cause == b) t2.setText(t1.getText()); }

Numeric input Suppose we want an applet that allows the user to enter two integers and display the minimum a text field contains a character string If we want to perform numeric operations on the input from a text field, we have to convert the string to a numeric data type numbers are primitive data types, not objects Can convert using Java type wrappers

Type wrappers Convert primitive types into objects Primitive Type Wrapper Type byte Byte short Short int Integer long Long float Float double Double char Character boolean Boolean

String conversion Convert String str to byte b byte b = Byte.parseByte(str); Convert String str to short s short s = Short.parseShort(str); Convert String str to int i int i = Integer.parseInt(str); Convert String str to long l long l = Long.parseLong(str); Convert String str to float f float f = Float.parseFloat(str); Convert String str to double d double d = Double.parseDouble(str);

Action performed for integer input public void actionPerformed(ActionEvent event) { Object cause = event.getSource(); int x = Integer.parseInt(t1.getText()); int y = Integer.parseInt(t2.getText()); if(cause == b) int min = minimum(x,y); t3.setText(“The minimum is: ” + min); }