Expressions and Data Types CSC 121 Spring 2017 Howard Rosenthal

Similar documents
Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

CS5000: Foundations of Programming. Mingon Kang, PhD Computer Science, Kennesaw State University

Program Fundamentals

CSC 1214: Object-Oriented Programming

BIT Java Programming. Sem 1 Session 2011/12. Chapter 2 JAVA. basic

Expressions, Data Types, Formatted Printing, Scanning CSC 123 Fall 2018 Howard Rosenthal

Full file at

3. Java - Language Constructs I

JAVA Programming Fundamentals

COMP 202 Java in one week

Basics of Java Programming

CMPT 125: Lecture 3 Data and Expressions

DEPARTMENT OF MATHS, MJ COLLEGE

Features of C. Portable Procedural / Modular Structured Language Statically typed Middle level language

12/22/11. Java How to Program, 9/e. Help you get started with Eclipse and NetBeans integrated development environments.

5/3/2006. Today! HelloWorld in BlueJ. HelloWorld in BlueJ, Cont. HelloWorld in BlueJ, Cont. HelloWorld in BlueJ, Cont. HelloWorld in BlueJ, Cont.

Objects and Types. COMS W1007 Introduction to Computer Science. Christopher Conway 29 May 2003

A Java program contains at least one class definition.

2 rd class Department of Programming. OOP with Java Programming

Java Notes. 10th ICSE. Saravanan Ganesh

Programming Lecture 3

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

Objectives. Chapter 2: Basic Elements of C++ Introduction. Objectives (cont d.) A C++ Program (cont d.) A C++ Program

Chapter 2: Basic Elements of C++

Chapter 2: Basic Elements of C++ Objectives. Objectives (cont d.) A C++ Program. Introduction

Language Fundamentals Summary

Computer Components. Software{ User Programs. Operating System. Hardware

LESSON 1. A C program is constructed as a sequence of characters. Among the characters that can be used in a program are:

UNIT- 3 Introduction to C++

Accelerating Information Technology Innovation

Chapter 3: Operators, Expressions and Type Conversion

Getting started with Java

Computer Components. Software{ User Programs. Operating System. Hardware

cis20.1 design and implementation of software applications I fall 2007 lecture # I.2 topics: introduction to java, part 1

Lecture 2: Variables and Operators. AITI Nigeria Summer 2012 University of Lagos.

Last Time. University of British Columbia CPSC 111, Intro to Computation Alan J. Hu. Readings

4 Programming Fundamentals. Introduction to Programming 1 1

CSCI 2010 Principles of Computer Science. Data and Expressions 08/09/2013 CSCI

Le L c e t c ur u e e 2 To T p o i p c i s c t o o b e b e co c v o e v r e ed e Variables Operators

Fundamental of Programming (C)

A variable is a name that represents a value. For

Java Identifiers. Java Language Essentials. Java Keywords. Java Applications have Class. Slide Set 2: Java Essentials. Copyright 2012 R.M.

An overview of Java, Data types and variables

BASIC ELEMENTS OF A COMPUTER PROGRAM

Visual C# Instructor s Manual Table of Contents

Java Programming Fundamentals. Visit for more.

Data and Variables. Data Types Expressions. String Concatenation Variables Declaration Assignment Shorthand operators. Operators Precedence

Declaration and Memory

Values and Variables 1 / 30

A complex expression to evaluate we need to reduce it to a series of simple expressions. E.g * 7 =>2+ 35 => 37. E.g.

CSc 10200! Introduction to Computing. Lecture 2-3 Edgardo Molina Fall 2013 City College of New York

Introduction to C# Applications

Object oriented programming. Instructor: Masoud Asghari Web page: Ch: 3

Chapter 2. Elementary Programming

SECTION II: LANGUAGE BASICS

Fundamentals of Programming

ECE 122 Engineering Problem Solving with Java

Operators. Java operators are classified into three categories:

Lecture 2. COMP1406/1006 (the Java course) Fall M. Jason Hinek Carleton University

Data and Expressions. Outline. Data and Expressions 12/18/2010. Let's explore some other fundamental programming concepts. Chapter 2 focuses on:

CHAPTER 2 Java Fundamentals

Character Set. The character set of C represents alphabet, digit or any symbol used to represent information. Digits 0, 1, 2, 3, 9

The Java Language Rules And Tools 3

Programming with Java

Tools : The Java Compiler. The Java Interpreter. The Java Debugger

Course Outline. Introduction to java

The Arithmetic Operators. Unary Operators. Relational Operators. Examples of use of ++ and

C: How to Program. Week /Mar/05

The Arithmetic Operators

CS113: Lecture 3. Topics: Variables. Data types. Arithmetic and Bitwise Operators. Order of Evaluation

Chapter 2 Elementary Programming

JAVA OPERATORS GENERAL

CONTENTS: Compilation Data and Expressions COMP 202. More on Chapter 2

Entry Point of Execution: the main Method. Elementary Programming. Learning Outcomes. Development Process

Lecture Notes. System.out.println( Circle radius: + radius + area: + area); radius radius area area value

Chapter 2: Data and Expressions

For the course, we will be using JCreator as the IDE (Integrated Development Environment).

Lecture Set 2: Starting Java

C OVERVIEW BASIC C PROGRAM STRUCTURE. C Overview. Basic C Program Structure

Chapter 2: Using Data

Objectives. In this chapter, you will:

Object-Oriented Programming

DM550 / DM857 Introduction to Programming. Peter Schneider-Kamp

Lecture Set 2: Starting Java

Welcome to CSE 142! Whitaker Brand. University of Washington, Winter 2018

CS102: Variables and Expressions

Chapter 2: Data and Expressions

Chapter 2: Data and Expressions

ANSI C Programming Simple Programs

Tester vs. Controller. Elementary Programming. Learning Outcomes. Compile Time vs. Run Time

UNIT - I. Introduction to C Programming. BY A. Vijay Bharath

C OVERVIEW. C Overview. Goals speed portability allow access to features of the architecture speed

Programming in C++ 5. Integral data types

Outline. Parts 1 to 3 introduce and sketch out the ideas of OOP. Part 5 deals with these ideas in closer detail.

3. Java - Language Constructs I

Welcome to CSE 142! Zorah Fung University of Washington, Spring Building Java Programs Chapter 1 Lecture 1: Introduction; Basic Java Programs

Elementary Programming

Introduction To Java. Chapter 1. Origins of the Java Language. Origins of the Java Language. Objects and Methods. Origins of the Java Language

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

Transcription:

Expressions and Data Types CSC 121 Spring 2017 Howard Rosenthal

Lesson Goals Understand the basic constructs of a Java Program Understand how to use basic identifiers Understand simple Java data types and the operations on those types Understand how to write and evaluate expressions Understand the concept of casting 2

Key Terms and Defini/ons public class Hello { public static void main ( String[] args ) { System.out.println("Hello World!"); } } Above is a source program (source file) for a Java program. The purpose of this program is to type the characters Hello World! on the monitor. The file must be named Hello.java to match the name of the class. The upper and lower case characters of the file name are important. On all computers, upper and lower case inside the program are important. Java is very case sensitive The first line class Hello says that this source program defines a class called Hello. A class is a section of a program. Small programs often consist of just one class. Most programs use multiple classes to create objects Some classes are are imported while other are created by the programmer Every class is contained within a set of braces 3

Key Terms and Defini/ons (2) When the program is compiled, the compiler will make a file of bytecodes called Hello.class. - This is the file that the JVM uses. If the file is named hello.java with a small h it will compile but hello.class won t exist if the code declares the class with a capital H It will create a class Hello.class that will work but keep it simple and follow the capitalization exactly Methods are built out of statements. The statements in a method are placed between braces { and } as in this example. A method is a section of a class that performs a specific task All programs start executing from the main method Each method is contained within a set of braces Braces For every left brace { there is a right brace } that matches. Usually there will be sets of matching braces inside other sets of matching braces. The first brace in a class (a left brace) will match the last brace in that class (a right brace). A brace can match just one other brace. Use indenting to show how the braces match (and thereby show the logic of the program). Look at the example. Increase the indenting by three spaces for statements inside a left and right brace. If another pair of braces is nested within those braces, increase the indenting for the statements they contain by another three spaces. Line up the braces vertically. With Notepad++ the indent levels for both braces and parentheses are color coded After a left brace an indent will be created for you automatically Make sure that you step back to align your left and right braces You can also indent when necessary by using the tab key 4

Key Terms and Defini/ons (3) Most classes contain many more lines than this one. Everything that makes up a class is placed between the first brace { and its matching last brace }. The name of the class (and therefore the name of the file) is up to you. By convention the first letter of a class is typically upper case. If the class has a compound name each word in the name starts with a uppercase letter i.e. NumberAdder A source file always end with.java in lower case. Therefore the file name is ClassName.java In programming, the name for something like a class, a method or a variable is called an identifier. An identifier consists of alphabetical characters and digits, plus the two characters '_' and '$' - underscore and dollar sign The first character must be alphabetical, the remaining characters can be mixed alphabetic characters and digits or _ or $. No spaces are allowed inside the name. An expression is a sequence of symbols (identifiers, operators, constants, etc.) that denote a value 3*(2*x+y)-6*z 5

Key Terms and Defini/ons (4) A reserved word is a word like class that has a special meaning to the system. For example, class means that a definition of a class immediately follows. You must use reserved words only for their intended purpose. (For example, you can't use the word class for any other purpose than defining a class.) Page 25 0f the text lists reserved words A statement in a programming language is a command for the computer to do something. It is like a sentence of the language. A statement in Java is always followed by a semicolon. A group of statements within a set of braces is called a block We will learn that each block level defines a scope for the variables defined within that scope The part "Hello World!" is called a String. A String is a sequence of characters within double quotes. This program writes a String to the monitor and then stops. 6

Reserved Keywords In Java The table below lists all the words that are reserved Java. Words in red are those that we will be using this semester Notice that all the reserved words are lower case abstract assert boolean break byte case catch char class const* continue default double do else enum extends false final finally float for goto* if implements import instanceof int interface long native new null package private protected public return short static strictfp super switch synchronized this throw throws transient true try void volatile while *Even though goto and const are no longer used in the Java programming language, they still cannot be used. 7

Comments A single line comment begins with // This // can come at the beginning of the line or after a statement on the line : System.out.println("On a withered branch" ); // Write first line of the poem Multiline comments begin/* and end */ /* Program 1 Write out three lines of a poem. The poem describes a single moment in time, using 17 syllables. */ It is a good idea to fully comment your program This includes describing the logic, and defining your variables Using descriptive variable names makes this much easier 8

Data Types and Operators A data type is a set of values together with an associated set of operators for manipulating those values. Who can think of some basic data types in the numerical world? The logical world? When an identifier is used as a variable it always has a defined data type The meaning of the 0 s and 1 s in the computer depends on the data type being represented We will begin by defining the eight primitive data types byte, short, int, long, float, double, char and boolean all lower case 9

Data Types and Operators (2) All data in Java falls into one of two categories: primitive data types, and reference data types which refer to objects that are created from classes. There are only eight primitive data types - byte, short, int, long, float, double, char, and boolean. Reference data types are memory addresses that refer to objects Java has many different classes, and you can invent as many others as you need. Much more will be said about objects in future chapters (since Java is a object oriented programming language). The following is all you need to know, for now: A primitive data value uses a small, fixed number of bytes. There are only eight primitive data types. A programmer cannot create new primitive data types. 10

Some Notes on Objects An object is a big block of data. An object may use many bytes of memory. An object usually consists of many internal pieces. The data type of an object is called its class. Many classes are already defined in Java. A programmer can invent new classes to meet the particular needs of a program. We create classes and access the methods of those classes Some classes have static methods that are accessed without creating new objects We will see the differences as we move ahead 11

Primi/ve Numeric Data Types (1) Numbers are so important in Java that 6 of the 8 primitive data types are numeric types. There are both integer and floating point primitive types. There are 4 integer data types byte a single byte used for small integers short two bytes int 4 bytes all integers are assumed to be of type int long 8 bytes use for very large number 12

Primi/ve Numeric Data Types (2) There are two data types that are used for floating point numbers float - 4 bytes double - 8 bytes this is the default for all floating constants and is used in almost all cases for floating point arithmetic Floating point numbers, unlike integers, are not always precise. If you compare floating point numbers you can get errors or unexpected results when executing due to the way that they are represented in the computer Due to this lack of perfect precision we usually prefer to use double over float for real numbers that aren t integers, since the precision is greater, although still not perfect. As we will see shortly, there are casting issues when you mix numbers, especially with floating point numbers Java has advanced methods using objects to calculate numbers even more precisely This class called BigDecimal is used for very precise monetary and scientific calculations In the tables, E means "ten to the power of". So 3.5E38 means 3.5 x 10 38 13

Primi/ve Numeric Data Types (3) There is a fundamental difference between the the representations of integers and floating point numbers in the computer. Integer types have no fractional part; floating point types have a fractional part. On paper, integers have no decimal point, and floating point types do. But in main memory, there are no decimal points: even floating point values are represented with bit patterns. 14

Primi/ve Numeric Data Types (4) Each primitive type uses a fixed number of bytes. This means that if you are using a particular data type then the same number of bytes will be used no matter what value is represented. For example, all values represented using the short data type use 2 bytes (16 bits). The value zero (as a short) uses 2 bytes and the value thirty thousand uses 2 bytes. All values represented using the long data type use 8 bytes (64 bits). The value zero (as a long) uses 8 bytes, the value thirty thousand uses 8 bytes, and the value eight trillion uses 8 bytes. Values that are large in magnitude (negative or positive) need more bits to be represented. This is similar to writing out numbers on paper: large numbers need more digits. If a value needs more bits than a particular data type uses, then it cannot be represented using that data type. 15

Summary of PrimiJve Numeric Data Types Integer Primitive Data Types Type Size Range byte 1 byte (8 bits) -128 to +127 short 2 bytes (16 bits) -32,768 to +32,767 int long 4 bytes (32 bits) 8 bytes (64 bits) -2 billion to +2 billion (approximately) -9E18 to +9E18 (approximately) Remember: Integer data types reserve the leftmost bit to indicate positive (0) or negative (1) in two s complement format Floating Point Primitive Data Types Type Size Range float 4 bytes (32 bits) -3.4E38 to +3.4E38 double 8 bytes (64 bits) -1.7E308 to 1.7E308 In the tables, E means "ten to the power of". So 3.5E38 means 3.5 x 10 38 16

Numeric Operators (1) Operator Meaning Precedence - unary minus highest + unary plus highest * multiplication middle / division middle % remainder /modulus middle + addition low - subtraction low Precedence of operators can take the place of parentheses, but just as in algebra, you should use parentheses for clarity. Where there are no parentheses and equal precedence evaluation is from left to right 17

Numeric Operators (2) All of these operators can be used on floating point numbers and on integer numbers. The % operator is rarely used on floating point. (we won t be using it, but the remainder concept would be similar) When mixing floating point numbers and integer numbers, floating point takes precedence this is called casting An integer operation is always done with 32 bits or more. If one or both operand is 64 bits (data type long) then the operation is done with 64 bits. Otherwise the operation is done with 32 bits, even if both operands are of a lesser data type than 32 bits. For example, with 16 bit short variables, the arithmetic is done using 32 bits: 18

Integer ArithmeJc In integer arithmetic you always truncate 7/2 = 3 11/4 = 2 The modulus operator gives you the remainder 7%4 = 3 9%2 =? Any ideas on where the % can be helpful? Note: In Java the sign of the result of a%b is always the sign of a (the dividend). 19

CasJng Java is a highly type sensitive language When evaluating any expression with operands of different types Java first promotes or casts the operand of the smaller data type By smaller we mean the range byte is smaller than short which is smaller than int which is smaller than long which is smaller than float which is smaller than double boolean expressions are never cast char automatically casts up to int, not to short You can only cast downwards explicitly, otherwise you may create an error Example : int a =10; short b =5; a = b; This is casting upwards it is implicit and automatic b = (short)(a); This is casting downwards must be explicit 20

Mixing Numeric Data Types (1) If both operands are integers, then the operation is an integer operation. If any operand is double, then the operation is double. 7.1+7.4 = 14.5 7.0+7.4 = 14.4 7+7.4 = 14.4 (15/2) +7.4 =? (15%2) + 7.4 =? The numbers are casted upwards This becomes more important in the next chapter when we learn about typing variables Note: Unless otherwise declared all decimals are assumed to be of type double 21

Mixing Numeric Data Types (2) Remember that without parentheses you follow the hierarchy Mixed integer/decimal addition is cast to decimal when the mixing occurs (10.0+5) = 15.0 10/4*(18.0) = 36.0 (5/9) *(212.0-32.0) = 0.0 Note: Integers can be of type byte, short, int, long, but default to int However you can directly assign an int to a short or byte variable (if it fits with the range) short b =5; works Floating point numbers can be of type double or float, but default to double Example: float z; z = 2.0+3.0; this creates an error Why? Java doesn t allow the double to cast down because of precision issues z = (float)(2.0+3.0); - This is correct we explicitly cast down. 22

Type boolean Type boolean identifiers can have only one of two values true or false. (1 or 0) A boolean value takes up a single byte. There are three operators && - means and both operands must be true for the value of the expression to be true - means or one of the operands must be true for the value of the expression to be true! - means not p q p&&q (and) p q (or)!p (not) true true true true false true false false true false false true false true true false false false false true 23

Type boolean Short CircuiJng There are also boolean operators & and What s the difference? When you use && or the compiler is more efficient, it can shortcircuit when necessary This means that once it determines if a statement is true or false it stops evaluating i.e.: (true false) false it is evaluated true after the first is evaluated (true && false) && true same idea, but evaluates as false after first && So when is there a problem: If you try to assign a logical value (allowed) this might not take place if there is short circuiting: (true false) (a= true) a doesn t get assigned the value true (a= true) is allowed as the expression evaluates as true (true false) (a= true) a does get assigned the value true Don t use these types of assignment statements inside of boolean statements it will inevitably lead to errors 24

Switches and Boolean Logic A A A X Y B To get from A to B both X and Y must be closed X&&Y X A B Y To get from A to B either X or Y must be closed X Y 25

RelaJonal Operators Operator Description Example (with A=2, B=5 == Checks if the value of two operands are equal or not, if yes then condition becomes true. (A == B) is not true.!= > Checks if the value of two operands are equal or not, if values are not equal then condition becomes true. Checks if the value of left operand is greater than the value of right operand, if yes then condition becomes true. (A!= B) is true. (A > B) is not true. < Checks if the value of left operand is less than the value of right operand, if yes then condition becomes true. (A < B) is true. >= <= Checks if the value of left operand is greater than or equal to the value of right operand, if yes then condition becomes true. Checks if the value of left operand is less than or equal to the value of right operand, if yes then condition becomes true. (A >= B) is not true. (A <= B) is true. The result of applying a relational operator is a true or false value 26

The hierarchy is very similar to what you know from algebra When there is an equivalent hierarchy level and no parentheses you evaluate from left to right When in doubt use parentheses Operator Hierarchy Priority Operators Operation Associativity [ ] array index 1 () method call left. member access ++ pre- or postfix increment -- pre- or postfix decrement + - unary plus, minus 2 ~ bitwise NOT right! boolean (logical) NOT (type) type cast new object creation 3 * / % multiplication, division, remainder left + - addition, subtraction 4 left + String concatenation << signed bit shift left 5 >> signed bit shift right left >>> unsigned bit shift right < <= less than, less than or equal to 6 > >= greater than, greater than or equal to left instanceof reference test == equal to 7 left!= not equal to & bitwise AND 8 left & boolean (logical) AND ^ bitwise XOR 9 left ^ boolean (logical) XOR bitwise OR 10 left boolean (logical) OR 11 && boolean (logical) AND left 12 boolean (logical) OR left 13? : conditional right = assignment *= /= += -= %= 14 right <<= >>= combinated assignment >>>= &= ^= = 27

Some Extra Examples 5>4 true 4>5 false (5>4) (4>5) -? (5>4) && (4>5) -? 28

Evaluate as true or false true false && 3 < 4!(5==7) Another Example (true (false && (3 < 4)))!(5==7) putting in the parentheses correctly always helps (true (false && true))!false (true false) true true true true 29

Type char Type char is the set of all characters found on the standard keyboard, and thousands of other characters as well. char is a primitive data type Type char is denoted using single quotes A, 5 Java uses Unicode 2 byte representations that increases the number of characters that can be represented from 255 to 65536 unique characters in actuality only 15 bits are used for two byte Unicode. Note: Keyboard letters in ASCII Code and Unicode have the same value i.e. A = 65 ie 01000001 in ASCII or 0000000001000001 in Unicode You can add and subtract type char they are actually treated like integers when adding i.e. A +1 = 66 0r 0000000001000010 - char would automatically cast up to int You could cast back down to char by saying (char)(66) which yields B They are added as type int 4bytes to accommodate all Unicode characters The most common characters and their Unicode values are found in Appendix B You can also compare type char values they compare based on their ASCII value ( A < B ) would evaluate as true 30

String String is a class in Java with lots of different methods that allows you to manipulate them An individual String is an object, not a basic data type. A String is a sequence of characters enclosed in double quotes Java provides a String class and we can create String objects Why does String have a capital S while primitive data types have lower case first letters String is the name of a class Strings can be concatenated I am + a man would evaluate as I am a man Strings and values Everything depends on the order The sum of two numbers is + (5*2) prints as The sum of two numbers is 10 Why? You always work from inside the parentheses outwards However ( The sum of two numbers is 5 ) + 2 prints as The sum of two numbers is 52 In Chapter 9 we do a lot more with String objects 31

Cas/ng With Strings and Characters A + B = 131 (integer) A + B = AB (String) A + B = AB (String) + A + B = AB (String) A gets cast to String A + B + = 131 (String) 3 + 4 + = 7 (String) + 3 + 4 = 34 (String) Key is that without parentheses we are reading left to right 32

PrinJng and Special Characters The System.out class is predefined and is included with the basic java.lang and therefore is always available for use. It is called the standard output object, and prints to the terminal We will learn how to print to other File objects later in this term We will be using two basic static methods from this class System.out.println( abc ) // prints the String and a character return System.out.print ( abc ) // prints a String without a character return Escape sequences inside the String can be used to control printing Escape Sequence Character \n newline \t tab \b backspace \f form feed \r return \" " (double quote) \' ' (single quote) \\ \ (back slash) \udddd character from the Unicode character set (DDDD is four hex digits) used when the character isn t available during input 33

PrinJng Example public class PrintAPoem { public static void main (String[] args) { System.out.println ( He wrote his code ); System.out.print( \the indented well\n ); System.out.println( \ttill he was done ); System.out.print( \nthe Author\n ); } } He wrote his code He indented well Till he was done The Author System.out.println(concatenated String) prints and goes to the next line System.out.print(concatenated String) prints and stays on the same line 34

PrinJng Example ConcatenaJon in Print Statements When you write expressions in a System.out.println() statement the expression may or may not be calculated first, depending on if and where you put the parentheses The rules are exactly the same as used when concatenating String(s) Ultimately the println method will output a single String public class PrintingNumbers //Class name { public static void main ( String[] args ) { System.out.println("The sum of 5 + 6 is " + (5+6)); System.out.println("The sum of 5 + 6 is " + 5+6); System.out.println("The sum of " +5 +" + " +6 + " is " +(5 + 6)); } } 35

Programming Exercise - Class (1) Modify the following program so that it s output is: Welcome To Java Programming public class Welcome1 { public static void main (String [] args) { System.out.println( Welcome To Java Programming ); } } 36

Programming Exercise - Class (2) Exercise 6. Triangle1Stars Write a program that prints the triangle: * ** *** **** ***** ****** Use this framework: public class Pname //Class name { public static void main ( String[] args ) //main method header } { } Code goes here //Body Compile with javac Pname.java Execute with java Pname once you compile successfully 37

Programming Exercise - Lab (1) Exercise 7. Triangle1StarsInits Write a program that prints the triangle: * ** *H* **G* ***R* ****** 38

Programming Exercise - Lab (2) Exercise 2. Uptime The uptime command of the UNIX operating system displays the number of days, hours and minutes since the operating system was started. For example the UNIX command uptime might return the string Up 53 days 12:39. Write a program that converts the 53 days, 12 hours and 39 minutes to the number of seconds that have elapsed since the operating since was last started. 39