A Java program contains at least one class definition.

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

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal

Full file at

Chapter 3: Operators, Expressions and Type Conversion

JAVA Programming Fundamentals

JAVA OPERATORS GENERAL

Declaration and Memory

Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following groups:

Computer System and programming in C

Operators and Expressions

CMPT 125: Lecture 3 Data and Expressions

These are reserved words of the C language. For example int, float, if, else, for, while etc.

Program Fundamentals

C Language Part 1 Digital Computer Concept and Practice Copyright 2012 by Jaejin Lee

BASIC COMPUTATION. public static void main(string [] args) Fundamentals of Computer Science I

Topic Notes: Bits and Bytes and Numbers

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

Basics of Java Programming

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

More Programming Constructs -- Introduction

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

The Arithmetic Operators

Review: Exam 1. Your First C++ Program. Declaration Statements. Tells the compiler. Examples of declaration statements

CS102: Variables and Expressions

Zheng-Liang Lu Java Programming 45 / 79

Will introduce various operators supported by C language Identify supported operations Present some of terms characterizing operators

Types and Expressions. Chapter 3

Expressions and Data Types CSC 121 Spring 2017 Howard Rosenthal

Computer Science 324 Computer Architecture Mount Holyoke College Fall Topic Notes: Bits and Bytes and Numbers

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

COMP2121: Microprocessors and Interfacing. Number Systems

Chapter 2 Elementary Programming

Topic Notes: Bits and Bytes and Numbers

Inf2C - Computer Systems Lecture 2 Data Representation

Basic operators, Arithmetic, Relational, Bitwise, Logical, Assignment, Conditional operators. JAVA Standard Edition

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

Information Science 1

ECE 122 Engineering Problem Solving with Java

COMP2611: Computer Organization. Data Representation

Variables and literals

GO - OPERATORS. This tutorial will explain the arithmetic, relational, logical, bitwise, assignment and other operators one by one.

Java Programming Fundamentals. Visit for more.

3. Java - Language Constructs I

SOFTWARE DEVELOPMENT 1. Operators 2018W A. Ferscha (Institute of Pervasive Computing, JKU Linz)

Expressions and Casting

Programming in C++ 5. Integral data types

Language Basics. /* The NUMBER GAME - User tries to guess a number between 1 and 10 */ /* Generate a random number between 1 and 10 */

Fundamentals of Programming

Getting started with Java

UNIT- 3 Introduction to C++

Fundamental of Programming (C)

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

SECTION II: LANGUAGE BASICS

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

A variable is a name for a location in memory A variable must be declared

4 Programming Fundamentals. Introduction to Programming 1 1

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

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

COMP Primitive and Class Types. Yi Hong May 14, 2015

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

Reserved Words and Identifiers

Slide 1 CS 170 Java Programming 1 Expressions Duration: 00:00:41 Advance mode: Auto

Visual C# Instructor s Manual Table of Contents

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

CEN 414 Java Programming

Expressions and Casting. Data Manipulation. Simple Program 11/5/2013

Chapter 2: Basic Elements of C++

Operators. Java operators are classified into three categories:

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

DEPARTMENT OF MATHS, MJ COLLEGE

Work relative to other classes

Unit 3. Operators. School of Science and Technology INTRODUCTION

Chapter 2 Working with Data Types and Operators

Primitive Data Types: Intro

2 nd Week Lecture Notes

CSE 1001 Fundamentals of Software Development 1. Identifiers, Variables, and Data Types Dr. H. Crawford Fall 2018

Sir Muhammad Naveed. Arslan Ahmed Shaad ( ) Muhammad Bilal ( )

Lecture 3. More About C

More about Binary 9/6/2016

CS61B Lecture #14: Integers. Last modified: Wed Sep 27 15:44: CS61B: Lecture #14 1

COSC 243. Data Representation 3. Lecture 3 - Data Representation 3 1. COSC 243 (Computer Architecture)

CHAPTER 3 Expressions, Functions, Output

Chapter 4. Operations on Data

Operators in java Operator operands.

DaMPL. Language Reference Manual. Henrique Grando

Fundamental Data Types. CSE 130: Introduction to Programming in C Stony Brook University

Lexical Considerations

CS 31: Introduction to Computer Systems. 03: Binary Arithmetic January 29

Information Science 1

CS 115 Data Types and Arithmetic; Testing. Taken from notes by Dr. Neil Moore

Numerical computing. How computers store real numbers and the problems that result

Operators. Java Primer Operators-1 Scott MacKenzie = 2. (b) (a)

Programming Lecture 3

Numerical Data. CS 180 Sunil Prabhakar Department of Computer Science Purdue University

Floating-Point Data Representation and Manipulation 198:231 Introduction to Computer Organization Lecture 3

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

MODULE 02: BASIC COMPUTATION IN JAVA

Programming for Engineers Introduction to C

CIS133J. Working with Numbers in Java

Transcription:

Java Programs Identifiers Objects and Types COMS W1007 Introduction to Computer Science Christopher Conway 29 May 2003 A Java program contains at least one class definition. public class Hello { public static void main(string[] args) { System.out.println("Hello, world!") ; This code defines a class named Hello. The definition of Hello must be in a file Hello.java. The method main is the code that runs when you call java Hello. When we give an element in a program a name, we call that name an identifier. In the previous example, Hello was an identifier. In Java, identifiers: Always start with a letter. Can include letters, digits, underscore ( ) and the dollar sign symbol ($). Must be different from any Java reserved words (or keywords). Keywords that we ve seen so far include: public, static, class and void. Case Sensitivity Whitespace Comments Identifiers and keywords in Java are case sensitive. In other words, capitalization matters. Keywords are always in lowercase. The following identifers are all different: foobar Foobar FooBar FOOBAR Even so, it would probably be a bad idea to use more than one of them in the same program. We use the word whitespace to describe blanks, tabs and newline characters. The Java compiler ignores whitespace except when it is used to separate words. E.g.: y=m*x+b;total=total+y; Is the same as: y = m*x + b ; total = total + y ; But which is easier to read? To make our code understandable to those who come after us, we comment sections whose purpose is not immediately obvious. // this comment ends at a newline /* this comment goes until it is explicitly ended with a: */ The Java compiler treats comments as if they were whitespace it ignores them unless they separate words. I.e., foo/*hi, mom!*/bar becomes foo bar, not foobar. Variables Types Booleans A variable is a location in memory where data is stored. Every variable is associated with an identifier. We can assign a value to a variable using the assignment operator =. x = 12 ; The assignment operator means take the value on the right-hand side and store it in the memory location on the left-hand side. The values a variable can take on and the operations that can be performed on it are determined by its type. Java has five categories of types: Booleans Characters Integers Floating-point numbers References to objects Boolean variables can only take on the values true or false. They are often used to test for conditions in a program. boolean t = true ; boolean f = false ;

Characters Integers Integers Types Character variables can store one character. A character value is a character surrounded by single quotes: char q = Q ; Some special characters are: \n newline \t tab \ single quote \" double quote \\ backslash The integers are the infinite set: Z = {..., 1, 0, 1,.... Obviously, we can t represent all of the integers in one variable. We have to choose an n-bit encoding that can represent 2 n integers. The Java integer types represent both positive and negative integers. An n-bit integer x can represent the range: 2 n 1 x < 2 n 1 The Java integer types are: E.g.: byte short int long byte b = 127 ; short s = -32768 ; int i = 2 ; 8 bits 16 bits 32 bits 64 bits Integer Literals Integer Conversions Integer Conversions: 2 An integer value, or literal, can be written in decimal, hex or octal (base-8): A hex literal starts with 0x, e.g.: 0x1F (= 31 10 ) An octal literal starts with just 0, e.g.: 072 (= 58 10 ) A decimal literal is just a regular number that doesn t start with 0, e.g.: 123 Integer literals are by default of type int. A long literal ends with L. If an int literal is small enough to fit into a byte or a short, it will be automatically converted. The same is true for long literals and int, byte and short. byte b = 0x7F ; /* 7 bits, OK */ short s = 0x7FFF ; /* 15 bits, OK */ int i = 0x12345678L /* 29 bits, OK */ byte b2 = 0xFF ; /* Error: 255 > 127 */ int i2 = 0x123456789ABCDEFL /* Error: way too big, 57 bits */ If a literal is too big for its target variable, you must explicitly convert it using a type cast. The number is converted by truncating the extra bits, which is probably not what you want. /* 0x100 = 256 */ byte b = (byte) 0x100 ; /* b now equals 0! */ An int literal can always be assigned to a long variable its value will be the same as if it was assigned to an int variable. Floating-Point Numbers Floating-Point Types Floating-Point Literals Floating-point numbers are used to represent the reals (R), i.e., numbers that may have fractional parts. The floating-point representation uses a form of scientific notation: 0.123 = 1.23 10 1 1.23 = 1.23 10 0 12.3 = 1.23 10 1 123.0 = 1.23 10 2 A floating-point variable uses some of its bits to store the exponent and some of them to store the fractional part (or significand). Thus, floating-point numbers are constrained by both magnitude and precision. The Java floating-point types are: float double 32 bits 64 bits Floating-point literals are decimal numbers with an optional decimal point. 123.4 0.99 55..2 You may also include an exponent n, which multiplies the literal by 10 n : 1.234e2 9.9e-1 55e0.02e1 A floating-point literal is by default of type double. A float literal ends with F.

Floating-Point Conversions The only automatic conversion between floating-point types is the assignment of a float value to a double. double d = 1.23F ; /* OK */ float f = 5.99 ; /* Error: cannot assign double to float */ When an integer literal is assigned to a floating-point type, it is automatically promoted to floating-point, even if that means a loss of precision. float f = 2 ; /* OK, f = 2.0 */ float f2 = 1234512345L ; /* OK, but f2 = 1234512384 */ Objects You may have heard that Java is an object-oriented programming language. What does that mean? An object is a collection of data and operations that manipulate that data. public class Circle { int x ; int y ; double radius ; Object-Oriented Programming In object-oriented programming (or OOP), we try to define all of our data as objects, and we define the program as interaction between those objects. public class HappyFace { Circle head ; SemiCircle smile ; void draw() { head.draw() ; smile.draw() ; Object-Oriented Programming: 2 OOP encourages us to think of objects as modules reusable components. If we have Circle, we can use it to make HappyFace. If we have HappyFace, we can use it to make StickMan. public class StickMan { HappyFace head ; Line body ; Line arm1, arm2 ; Line leg1, leg2 ; Defining Object Types An object is usually a noun, a thing. To define an object, we first need to define what kind of a thing it is. In Java, we use the keyword class: public class Car { String make ; int model_year ; Color color ; int max_occupants ; Defining Object Types: 2 Now that we ve defined a class, we can create instances of the class (i.e., objects). In order to create an instance, we need to tell Java how to initialize the object. We do this using a constructor. public class Car { public Car(String mk, int yr, Color c, int max) { make = mk ; model_year = yr ; color = c ; max_occupants = max ; Defining Objects Now we can use the keyword new to invoke the constructor and create an instance of the class. We can create any kind of a car we need by changing the parameters to the constructor. Car suv = new Car("Ford Explorer", 1999, Color.BLUE, 5) ; Car mini = new Car("Cooper Mini", 2002, Color.RED, 4) ; The Type of an Object An object s type is its class. A Car variable can only take the value of a Car object, or an object that is compatible with Car. (We ll talk about what it means for an object to be compatible next week.) Car suv = new Car("Ford Explorer", 1999, Color.BLUE, 5) ; Car c = suv ; /* OK: suv is a Car */ StickMan s = suv ; /* Error: suv is not a StickMan */ References We said earlier that one of the categories of Java types is references to objects. What is a reference? We said that a variable is a location in memory. When we declare an integer variable x and assign it a value 123, the location in memory set aside for x contains the binary representation of 123. x n + 1 n n 1 true 123 6.02e23

References: 2 A variable of an object type is a reference variable. When we declare a Car variable suv, the location in memory set aside for suv contains a reference to the location of the data members of suv. suv n + 1 n n 1 6.02e23 ref X "Ford Explorer" 1999 Color.BLUE 5 Reference Assignment Assignment means copy the value on the right-hand side into the memory location on the left-hand side. If you assign one variable to another, the value is copied and that is that. int x = 0 ; int y = x ; /* x and y both equal 0 */ x = 2 ; /* x now equals 2, y still equals 0 */ Reference Assignment: 2 When you assign the value of one reference variable to another, it s the reference that s copied, not the object. This can lead to surprising results. Point p = new Point(0,0) ; Point q = p ; /* p and q now refer to the same object */ p.x = 2 ; /* p.x now equals 2 q.x now equals 2, as well */ Reference Assignment: 2 When you copy the reference value, you still have only one copy of the object data. You just have two references to it. p q 0xFFFFFFFF ref ref false x: 2 y: 0 This may seem confusing at first, but there s a simple reason for it: copying data is slow. We avoid it when we can. Strings String is a class that has special support in Java. A string literal is surrounded by double quotes. String hamlet = "To be or not to be" ; String is a reference type, but you don t have to use the new operator to create an instance. You can assign a string literal to a String variable directly, as above. Strings: 2 Character and string values may seem confusingly similar. A char value is a single character, surrounded by single quotes: char c1 = C ; char c2 = \n ; A String value is a sequence of characters surrounded by double quotes. A String may be empty. String s1 = "C" ; String s2 = "" ; String s3 = "LastName\tFirstName\tGrade\n" ; /* Words separated by tabs, closed with a newline. */ Arithmetic Java provides five basic arithmetic operators: + addition - subtraction * multiplication / division % remainder There are also unary + and - operators. The operators can be applied to any of the integer or floating-point types. Operator Precedence Multiplication, division and remainder have higher precedence than addition and subtraction. All higher-precedence operators are evaluated before any lower-precedence operators. Operators at the same precedence are evaluated left-to-right. Parentheses can be used to override operator precedence. x+y*z = x+(y*z) a*b+c%d = (a*b)+(c%d) Assignment is the lowest-precedence operator of all. Unary + and - are higher-precedence than multiplication. Integer Arithmetic Integer division is grade-school division: fractional results round toward zero. 9/2 = 4-9/2 = -4 Integer division and remainder obey the rule: (x/y)*y + x%y = x 9%2 = 1-9%2 = -1

Overflow and Underflow If the result of an operation is greater than the maximum value (overflow) or less than the minimum value (underflow) of its type, the result wraps around. Integer.MAX VALUE + 1 = Integer.MIN VALUE Integer.MIN VALUE - 1 = Integer.MAX VALUE All arithmetic is performed with int and long values. byte and short values are automatically promoted. Typecasting The result of an integer arithmetic operation is always an int or long. This means you have to cast back to a smaller type when you assign a result. byte b = 1 ; byte b2 = b + 1 ; /* Error: can t assign int to byte */ byte b3 = (byte)( b + 1 ) ; /* OK: b3 now equals 2 */ byte b4 = (byte)( Byte.MAX_VALUE + 1 ) ; /* OK: b4 now equals Byte.MIN_VALUE */ Floating-point Arithmetic Floating-point arithmetic works pretty much how you would expect, except you have to be careful about precision. float f = 1.0e8F, g = 1.0e-8F ; float x = f + g ; /* x now equals 1.0e8 */ float y = (f - f) + g ; /* y now equals 1.0e-8 */ float z = f - (f + g) ; /* z now equals 0 */ Special Floating-point Values Floating-point arithmetic has several special values that behave in interesting ways. +Inf -Inf Infinity +0.0 Zero Negative Infinity -0.0 Negative Zero NaN Not a Number Special Floating-point Values: 2 Here s how to get and what you get from, these special values: 1/0.0 = Inf 1/-0.0 = -Inf 1/Inf = 0.0 1/-Inf = -0.0 Inf/Inf = NaN 1+Inf = Inf 1%Inf = 1 Inf*0.0 = NaN 1-Inf = -Inf Inf%1 = NaN Increment and Decrement Adding or subtracting one from a number is a common operation. Java provides a short-hand in the increment (++) and decrement (--) operators. Increment and decrement can be used as prefix or postfix operators. In prefix form, increment means add one to this variable and use the incremented value in this expression. In postfix form, increment means add one to this variable, and use the previous value in this expression. Aside: C also has increment and decrement. The developers of C++ wanted to indicate it was an incremental improvement on C. Increment and Decrement: Examples int i = 0, j ; i++ ; /* i = 1 */ i-- ; /* i = 0 */ j = i++ ; /* i=1, j=0 */ j = ++i ; /* i=2, j=2 */ j = --i ; /* i=1, j=1 */ j = i-- ; /* i=0, j=1 */ Increment and Decrement: Precedence Increment and decrement are higher-precedence than any operator we ve seen so far. Postfix is higher-precedence than prefix. Highest Lowest = ++, -- (postfix) ++, -- (prefix), +, - (unary) *, /, % +, - Comparison Operators Java provides the following operators for comparing numbers: > Greater than < Less than >= Greater than or equal to <= Less than or equal to == Equal to!= Not equal to == and!= can be applied to boolean values, but >, <, >= and <= cannot. The result of a comparison operation is a boolean value.

Reference Comparison == and!= can be applied to reference variables. They test whether the references are equal, not the data members. Point x = new Point(0,0) ; Point y = new Point(0,0) ; Point z = x ; boolean b = x==y ; /* false, x and y are references to different objects */ boolean b2 = x==z ; /* true, x and z are references to the same object */ The instanceof Operator Occasionally we want to investigate the type of an object. The instanceof operator tells us if a reference variable is an instance of a class. Point x = new Point(0,0) ; boolean a = x instanceof Point ; /* true, x is a Point */ boolean b = x instanceof Car ; /* false, x is not a Car */ Comparison Operators: Precedence The relational operators have higher precedence than the equality operators. All of the comparison operators have lower precedence than the arithmetic operators. Highest Lowest = ++, -- (postfix) ++, -- (prefix), +, - (unary) *, /, % +, - <, >, <=, >=, instanceof ==,!= Logical Operators Java provides the following logical operators: & AND OR ˆ XOR! NOT && short-circuit AND short-circuit OR The operands of a logical operator are boolean values and the result is also a boolean. AND AND is true if and only if both of its operands are true. a b a&b false false false false true false true false false true true true OR OR is true if one of its operands are true. a b a b false false false false true true true false true true true true XOR XOR is true if and only if exactly one of its operands is true. a b aˆb false false false false true true true false true true true false NOT NOT inverts its operand. a!a false true true false Short-circuit AND and OR The logical AND and OR operators ( & and ) always evaluate both of their operands. In some cases, this can be wasteful. If the first operand of AND is false, then AND must be false. Short-circuit AND ( && ) doesn t evaluate the second operand if the first is false. If the first operand of OR is true, then OR must be true. Short-circuit OR ( ) doesn t evaluate the second operand if the first is true.

Short-circuit Operators: Example boolean a = true, b = false ; int i = 0, j = 1, k = 2 ; boolean c = a (i=j) < k ; /* c = true, i = 0 */ boolean d = a && (i=j) < k ; /* d = true, i = 1 */ boolean e = a && (i=k) < j ; /* e = false, i = 2 */ Logical Operators: Precedence AND has higher precedence than OR. The short-circuit operators have lower precedence than their ordinary equivalents. All of the logical operators have lower precedence than arithmetic and comparison. Highest Arithmetic, etc. <, >, <=, >=, instanceof ==,!= & ˆ Lowest = && Bitwise Operators Java provides the following operators for manipulating bit patterns: & Bitwise AND Bitwise OR ˆ Bitwise XOR << Shift left >> Shift right signed >>> Shift right unsigned &, and ˆ are overloaded operators. They are logical operators when applied to boolean values, and bitwise operators when applied to integers. Bitwise AND Bitwise AND applies the AND operation to every pair of bits in the operands. A 0 is treated as false and a 1 is treated as true. Bitwise OR Bitwise OR applies the OR operation to every pair of bits in the operands. Bitwise XOR Bitwise XOR applies the XOR operation to every pair of bits in the operands. 0xF6 & 0x93 = 1111 0110 AND 1001 0011 = 1001 0010 0xF6 0x93 = 1111 0110 OR 1001 0011 = 1111 0111 0xF6 ˆ 0x93 = 1111 0110 XOR 1001 0011 = 0110 0101 Shift left The shift left operator shifts the bits in its first operand as indicated by its second operand. 0xF6 << 2 = 1111 0110 << 2 11 0110 00 Shift right signed The way integers are represented in Java, the highest-order bit is the sign of the number. If we shift right the same way we shift left (bringing in zeroes), the sign might changed. The shift right signed operator brings in bits that match the sign. 1111 0110 >> 2 0xF6 >> 2 = 11 1111 01 Shift right unsigned The shift right unsigned operator ignores the sign bit and brings in zeroes. 1111 0110 >>> 2 0xF6 >>> 2 = 00 1111 01

Using Bitwise Operators Bitwise AND is good for turning bits off: int i = 0xC7 & 0xFE ; /* i = 0xC6 */ Bitwise OR is good for turning bits on: int i = 0xC7 0x08 ; /* i = 0xCF */ Bitwise XOR is good for flipping bits: int i = 0xC7 0x09 ; /* i = 0xCE */ Bitwise Operators: Precedence The precedence of bitwise AND, OR and XOR match their logical equivalents. The precendence of the shift operators is between the arithmetic and comparison operators. Highest Lowest Unary operators *, /, % +, - <<, >>, >>> <, >, <=, >=, instanceof ==,!= Logical operators, assignment String Concatenation The + is also overloaded. When applied to two strings, it concatenates them. I.e., it appends the second to the first. String a = "Flower" ; String b = "Power" ; String c = a + b ; /* c = "FlowerPower" */ String Concatenation: 2 All of the basic types are automatically converted to String under the concatenation operator. int i = 2 ; double x = 5.2 ; String s = "i = " + i + " and x = " + x ; /* s = "i = 2 and x = 5.2" */ Assignment Operators All of the binary operators have corresponding compound assignment operators. += %= &= -= >>= ˆ= *= <<= = /= >>>= x op= y is equivalent to x = x op y. All of the compound assignment operators have the same precedence as assignment.