CompSci 001 8.1 Today’s topics Parsing Java Programming Notes from Tammy Bailey Reading Great Ideas, Chapter 3 & 4.

Slides:



Advertisements
Similar presentations
Types and Arithmetic Operators
Advertisements

 2005 Pearson Education, Inc. All rights reserved Introduction.
1 Chapter 2 Introduction to Java Applications Introduction Java application programming Display ____________________ Obtain information from the.
Primitive Data Types There are a number of common objects we encounter and are treated specially by almost any programming language These are called basic.
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.
Bellevue University CIS 205: Introduction to Programming Using C++ Lecture 3: Primitive Data Types.
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.
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie June 27, 2005.
Primitive Types Java supports two kinds of types of values – objects, and – values of primitive data types variables store – either references to objects.
Hello, world! Dissect HelloWorld.java Compile it Run it.
String Escape Sequences
© The McGraw-Hill Companies, 2006 Chapter 1 The first step.
 2003 Prentice Hall, Inc. All rights reserved. 1 Introduction to C++ Programming Outline Introduction to C++ Programming A Simple Program: Printing a.
Introduction to Python
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.
Chapter 2 Basic Elements of Java. Chapter Objectives Become familiar with the basic components of a Java program, including methods, special symbols,
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 Programming, Second Edition Chapter One Creating Your First Java Program.
 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.
 Pearson Education, Inc. All rights reserved Introduction to Java Applications.
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition.
Copyright 2008 by Pearson Education 1 Building Java Programs Chapter 2 Lecture 2-1: Expressions and Variables reading:
Introduction to Java Java Translation Program Structure
CompSci Today’s topics Parsing Java Programming Reading Great Ideas, Chapter 3 & 4.
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.
COMP Primitive and Class Types Yi Hong May 14, 2015.
Outline Character Strings Variables and Assignment Primitive Data Types Expressions Data Conversion Interactive Programs Graphics Applets Drawing Shapes.
 2008 Pearson Education, Inc. All rights reserved JavaScript: Introduction to Scripting.
Programming in Java (COP 2250) Lecture 4 Chengyong Yang Fall, 2005.
Copyright 2010 by Pearson Education 1 Building Java Programs Chapter 2 Lecture 2-1: Expressions and Variables reading:
Introduction to Python Dr. José M. Reyes Álamo. 2 Three Rules of Programming Rule 1: Think before you program Rule 2: A program is a human-readable set.
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.
CSM-Java Programming-I Spring,2005 Fundamental Data Types Lesson - 2.
1 Building Java Programs Chapter 2 Lecture 2-1: Expressions and Variables reading:
CHAPTER 2 PROBLEM SOLVING USING C++ 1 C++ Programming PEG200/Saidatul Rahah.
Today’s topics Java Input More Syntax Upcoming Decision Trees More formal treatment of grammers Reading Great Ideas, Chapter 2.
CS 106 Introduction to Computer Science I 09 / 10 / 2007 Instructor: Michael Eckmann.
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.
CS0007: Introduction to Computer Programming Primitive Data Types and Arithmetic Operations.
© 2004 Pearson Addison-Wesley. All rights reserved August 27, 2007 Primitive Data Types ComS 207: Programming I (in Java) Iowa State University, FALL 2007.
HelloWorld.java import java.awt.*; public class HelloWorld extends
Chapter 7: Expressions and Assignment Statements
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
Type Conversion, Constants, and the String Object
Java Programming: From Problem Analysis to Program Design, 4e
Building Java Programs Chapter 2
Introduction to C++ Programming
Chapter 2: Basic Elements of Java
Building Java Programs
Building Java Programs Chapter 2
Building Java Programs
Primitive Types and Expressions
Building Java Programs Chapter 2
Review of Java Fundamentals
Presentation transcript:

CompSci Today’s topics Parsing Java Programming Notes from Tammy Bailey Reading Great Ideas, Chapter 3 & 4

CompSci Java programs l Java programs are created as text files using a text editor (like emacs) Save to disk with.java file extension HelloWorld.java l 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 l Java must first translate the program into bytecodes before it can be run

CompSci Java Details l Java tutorial 1. Do “Your First Cup of Java” and create your First Applet 2. Go to “Learning the Java Language” and read “Language Basics” l Variable: an item of data named by an identifier l Operators à Arithmetic à Relational and conditional à Assignment à Other l Expression: a series of variables, operators, and method calls that evaluates to a single value

CompSci Bytecodes l 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.javajavacHelloWorld.class source program Java compiler Java bytecodes

CompSci Java Virtual Machine (JVM) l Bytecode (class) file will contain exactly the same bytecodes no matter what computer system is used l Bytecode file is executed by a Java bytecode interpreter à processor specific executable program l Each type of computer system has its own Java interpreter that can run on that system l Any computer system can execute Java bytecode programs if it has a Java interpreter l Computers with Java interpreters are called Java Virtual Machines à a “computer” with a Java processor that can run Java bytecodes

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

CompSci Data types l Computer memory stores arbitrary bit patterns l Meaning of a bit pattern depends on its use l 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 l Example: What does the following pattern of 16 bits represent? l No way to know without more information If data type is short (a Java type) it represents 103

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

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

CompSci Java primitive data types Primitive TypeDescriptionRange byte 8-bit integer-128 to 127 short 16-bit integer to int 32-bit integer to long 64-bit integer-2 63 to float 32-bit floating point to double 64-bit floating point to char Unicode character boolean Boolean variable false and true

CompSci Basic operators OperatorJavaDescription 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

CompSci Variable declaration Declaration type ; l Declaration + initialization: type = ; l 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)

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

CompSci Operator precedence l Evaluate a + b * c à multiplication first? a + (b * c) à addition first? ( a + b) * c l 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) 1. ( ) 2. * / % =

CompSci When in doubt, use parentheses l a + b * c = a + (b * c) à because * has higher priority than + l To perform the + operation first we need to use parentheses à (a + b) * c l 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

CompSci Examples l Java adheres to traditional order of operations * and / have higher priority than + and – int x = * 6;(x = 33) int y = (3 + 5) * 6;(y = 48) l Parentheses are free, use them liberally int z = ((3 + 5) * (6));(z = 48) l 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 * * 6;(y = 24) int z = 3 * (4 + 2) * 6;(z = 108)

CompSci Syntax and semantics Addition, subtraction: + and –, int and double int x = 21+4; (x = 25) double y = ;(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)

CompSci Automatic type conversion l 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 l Cannot convert to a lower type l 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? a) 5 b) 0.0 c) 9.0 d) 5.0 e) 9

CompSci More expressions int g = ; What is the value of g? a. 0 b. 12 c. 14 d e. error int x = 8 * (7 – 6 + 5) % (4 + 3 / 2) – 1; What is the value of x? a. -1 b. 0 c. 2 d. 3 e. none of the above int n = 1 – 2 * 3 – (4 + 5); What is the value of n?

CompSci Syntax errors l 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++ }

CompSci Logic errors l The computer will do precisely what you say even though it may not be what you want l 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++; }

CompSci Java objects l 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 l 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 l In Java, we define an object’s attributes using variables and its functionality using methods

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

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

CompSci 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; l Testing for equality: first.equals(“Tammy”); /* returns true */ first.equals(“Amy”); /* returns false */

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

CompSci Java TextField class The TextField class allows the editing and display of a single line of text TextField t = new TextField(); l 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

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

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

CompSci Action listeners l 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

CompSci Example l 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);

CompSci Think about it Puzzle: Toggling Frogs à You have 100 light switches, numbered 1-100, and 100 frogs, also numbered à Whenever a frog jumps on a light switch, it toggles a light between on and off. All lights are initially off. frog #1 jumps on every light switch (ie turning them all on). frog #2 jumps on every 2nd light switch, toggling some of them back off.... frog #k jumps on every kth light switch.  After 100 frogs, which lights are on? Game: Don’t be last à You and a friend have a stack of 10 coins. à On each person's turn, they remove either 1 or 2 coins from the stack. à The person who removes the last coin wins. à What is a winning strategy? Should you go first or second?