Variables, Types, Operations on Numbers

Slides:



Advertisements
Similar presentations
Types, Variables and Operators Computer Engineering Department Java Course Asst. Prof. Dr. Ahmet Sayar Kocaeli University - Fall 2013.
Advertisements

Variables Pepper. Variable A variable –box –holds a certain type of value –value inside the box can change Example –A = 2B+1 –Slope = change in y / change.
Introduction to Computers and Programming Lecture 4: Mathematical Operators New York University.
Review… Yong Choi BPA CSUB. Access Modifier public class HelloWorldApp –More detailes of Java key (reserved) wordJava key (reserved) word –The keyword,
Computer Science A 2: 6/2. Course plan Introduction to programming Basic concepts of typical programming languages. Tools: compiler, editor, integrated.
Fundamental Programming Structures in Java: Comments, Data Types, Variables, Assignments, Operators.
Copyright 2008 by Pearson Education 1 Building Java Programs Chapter 2 Lecture 2-1: Expressions and Variables reading:
1 The First Step Learning objectives write Java programs that display text on the screen. distinguish between the eight built-in scalar types of Java;
Boolean Expressions and Conditionals (If Statements) CSE 1310 – Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington.
1 Number Types  Every value in Java is either: 1.a reference to an object or 2.one of the eight primitive types  eight primitive types: a.four integer.
Java Methods. Topics  Declaring fields vs. local variables  Primitive data types  Strings  Compound Assignment  Conversions from one value to another.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 2 Basic Elements of Java.
First Programs CSE 1310 – Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington 1.
1 Java Basics: Data Types, Variables, and Loops “ If debugging is the process of removing software bugs, then programming must be the process of putting.
Copyright 2008 by Pearson Education 1 Building Java Programs Chapter 2 Lecture 2-1: Expressions and Variables reading:
CMP-MX21: Lecture 4 Selections Steve Hordley. Overview 1. The if-else selection in JAVA 2. More useful JAVA operators 4. Other selection constructs in.
School of Computer Science & Information Technology G6DICP - Lecture 4 Variables, data types & decision making.
Copyright 2010 by Pearson Education 1 Building Java Programs Chapter 2 Lecture 2-1: Expressions and Variables reading:
1 More data types Character and String –Non-numeric variables –Examples: char orange; String something; –orange and something are variable names –Note.
Formatted Output (printf) CSE 1310 – Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington 1.
CSM-Java Programming-I Spring,2005 Fundamental Data Types Lesson - 2.
1 Building Java Programs Chapter 2 Lecture 2-1: Expressions and Variables reading:
Variables, Types, Operations on Numbers CSE 1310 – Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington 1.
Copyright 2010 by Pearson Education 1 Building Java Programs Chapter 2 Lecture 2-1: Expressions and Variables reading:
Java Programming: Guided Learning with Early Objects Chapter 1 Basic Elements of Java.
CompSci 230 S Programming Techniques
Boolean Expressions and Conditionals (If Statements)
Formatted Output (printf)
Exceptions and User Input Validation
Building Java Programs
Introduction to Computer Science / Procedural – 67130
Multiple variables can be created in one declaration
Primitive Data, Variables, Loops (Maybe)
Java Programming: From Problem Analysis to Program Design, 4e
First Programs CSE 1310 – Introduction to Computers and Programming
Static Variables ICS 111: Introduction to Computer Science I
IDENTIFIERS CSC 111.
Basic Notions Review what is a variable? value? address? memory location? what is an identifier? variable name? keyword? what is legal identifier? what.
Chapter 2: Basic Elements of Java
Building Java Programs
Variables Numbers can be stored and retrieved while a program is running if they are given a home. The way that integers and decimal numbers are stored.
Building Java Programs
Building Java Programs
Variables, Types, Operations on Numbers
Building Java Programs Chapter 2
Building Java Programs
Building Java Programs
elementary programming
Building Java Programs
Building Java Programs
Building Java Programs
Building Java Programs
Building Java Programs
Building Java Programs
Building Java Programs
Building Java Programs
Introduction to Primitives
Fundamental OOP Programming Structures in Java: Comments, Data Types, Variables, Assignments, Operators.
Introduction to Primitives
Building Java Programs
In this class, we will cover:
Building Java Programs
Building Java Programs Chapter 2
Building Java Programs
Just Enough Java 17-May-19.
First Programs CSE 1310 – Introduction to Computers and Programming
Data Types Every variable has a given data type. The most common data types are: String - Text made up of numbers, letters and characters. Integer - Whole.
Building Java Programs
Building Java Programs
Building Java Programs
Presentation transcript:

Variables, Types, Operations on Numbers CSE 1310 – Introduction to Computers and Programming University of Texas at Arlington Updated 8/28/18

Summary Variable declaration, initialization, and use. Types: Possible syntax errors Syntax – rules for code that can compile. Types: Define what are legal values for a variable. Both variables and values have types. A variable can only have one type throughout the program. Common errors: Initialize a variable with a value of another type Use data of a ‘wrong’ type for an operator(e.g. "catapult" - "cat" ) Wrong type: operator – is not defined for strings Use data of a ‘wrong’ type as function argument Function takes arguments of a different type. ++/--, +=/-= (not recommended in exams) Type conversion: Casting: (int) Casting and: Math.round(), Math.floor() or Math.ceil() Constant variables: "final int days_per_week = 7; "

Declaring a Variable At any point, you can create a variable, by doing a variable declaration. There are two ways to declare a variable: type variable_name; // declare only: name and type type variable_name = initial_value; // declare and initialize For example: int x; //declaration only int number_of_fingers = 5; //declare and initialize double radius = 20.231;

Declaration/Initialization before Use A variable must be declared before we try to use it. The code below illustrates a common mistake. Variable age is not declared anywhere. Java will refuse to run this code, complaining that it "cannot find symbol age". See:https://www.google.com/search?q=image+with+room+full+of+filing+cabinets&tbm=isch&source=iu&ictx=1&fir=TZieO3kjdSjeqM%253A%252CRTpejPPfbeeEjM%252C_&usg=AFrqEzeFfY82boLRiw_ZSe8EOvAGpQ66Xw&sa=X&ved=2ahUKEwjI0J2-7o_dAhUCUK0KHUI0BZ4Q9QEwDnoECAYQIA#imgrc=TZieO3kjdSjeqM: public class example1 // incorrect code { public static void main(String[] args) age = 5; System.out.println(age); }

Declaration/Initialization before Use A variable must be declared and initialized before we try to use it. The code below illustrates a common mistake. Variable age is declared but not initialized. Java will refuse to run this code, complaining that "variable age might not have been initialized". public class example1 // incorrect code { public static void main(String[] args) int age; System.out.println(age); }

Declaration/Initialization before Use Solution 2: declare the variable in one line, and then set the value of the variable in another line. See code below: The first red line declares a variable called age2. The second red line sets the value of age2 to 5. Solution1: provide an initial value for the variable at the same line where you declare the variable. See code below The red line declares and initializes a variable called age1. // correct code version 1 int age = 5; System.out.println(age); // correct code version 2 int age; age = 5; System.out.println(age);

Using Variables What is wrong with this code? public class hello1 // incorrect code { public static void main(String[] args) radius = 20.231; area = Math.PI * Math.pow(radius, 2); System.out.println(area); } What is wrong with this code?

Using Variables What is wrong with this code? public class hello1 // incorrect code { public static void main(String[] args) radius = 20.231; area = Math.PI * Math.pow(radius, 2); System.out.println(area); } What is wrong with this code? Variables "radius" and "area" are not declared.

Using Variables Corrected version. public class hello1 // correct code { public static void main(String[] args) double radius = 20.231; double area = Math.PI * Math.pow(radius, 2); System.out.println(area); } Corrected version.

Using Variables - Practice public class hello1 // incorrect code { public static void main(String[] args) double area = Math.PI * Math.pow(radius, 2); double radius = 20.231; System.out.println(area); } What is wrong with this code?

Using Variables What is wrong with this code? public class hello1 // incorrect code { public static void main(String[] args) double area = Math.PI * Math.pow(radius, 2); double radius = 20.231; System.out.println(area); } What is wrong with this code? Variable "radius" is used before it has been declared.

Using Variables Corrected version. public class hello1 // correct code { public static void main(String[] args) double radius = 20.231; double area = Math.PI * Math.pow(radius, 2); System.out.println(area); } Corrected version.

Using Variables - Practice public class hello1 // incorrect code { public static void main(String[] args) double radius = 20.231; double area = Math.PI * Math.pow(Radius, 2); System.out.println(area); } What is wrong with this code?

Using Variables What is wrong with this code? public class hello1 // incorrect code { public static void main(String[] args) double radius = 20.231; double area = Math.PI * Math.pow(Radius, 2); System.out.println(area); } What is wrong with this code? Variable "radius" is misspelled in the line where the area is computed.

Using Variables Corrected version. public class hello1 // correct code { public static void main(String[] args) double radius = 20.231; double area = Math.PI * Math.pow(radius, 2); System.out.println(area); } Corrected version.

Using Variables - Practice public class example1 // incorrect code { public static void main(String[] args) int x = 5; int x = 3 * 5; System.out.println(x); } What is wrong with this code?

Using Variables What is wrong with this code? public class example1 // incorrect code { public static void main(String[] args) int x = 5; int x = 3 * 5; System.out.println(x); } What is wrong with this code? Variable x is being declared twice.

Using Variables Corrected version. public class example1 // correct code { public static void main(String[] args) int x = 5; x = 3 * 5; System.out.println(x); } Corrected version.

Types The type of a variable defines what are legal values for that variable. Java will never allow you to set a variable to a value incompatible with the type of the variable. Both variables and values have a type.

The Five Basic Types In this course we will use numbers and text (and boolean values). They will be represented by five basic types. int double boolean String char

The Five Basic Types int double boolean String char legal values? integers, like 0, 57, -1896… double legal values? real numbers, like 3.0, 5.2, -0.23… illegal: 5,300 (comma). Use: 5300. boolean legal values? only two: true and false. String legal values? text, like "hello", "a cat jumped on the table", … NOTE: text for strings must be enclosed in double quotes. char legal values? singe characters, like 'c', '3', 'A', '#', … NOTE: text for strings must be enclosed in single quotes.

Types Are NOT Interchangeable Not pay attention to types makes programming very hard and confusing. The following four values are NOT interchangeable: 2 2.0 "2" '2' Why?

Types Are NOT Interchangeable Not pay attention to types makes programming very hard and confusing. The following four values are NOT interchangeable: 2 this is an int 2.0 this is a double "2" this is a string '2' this is a character Why? Because they are different types.

Types Are NOT Interchangeable For example: Incorrect Correct String a1 = 2.5; String a1 = "2.5"; double a2 = "2.5"; double a2 = 2.5; int num = '5'; int num = 5; char c1 = 5; char c1 = '5'; String str = '5'; String str = "5"; int my_int = 2.0; int my_int = 2; boolean v = "true"; boolean v = true; String v = true; String v = "true";

The ++ and -- Operators public class example1 { public static void main(String[] args) { double x = 5.5; x++; // same effect as x = x+1 System.out.println(x); int y = 4; y--; // same effect as y = y-1 System.out.println(y); } Output 6.5 3 The ++ operator increments the value of a variable by 1. Syntax: variable_name++; The -- operator decrements the value of a variable by 1. Syntax: variable_name--;

The += and -= operators public class example1 { public static void main(String[] args) { double x = 5.5; x += 3.2; // same as x = x+3.2; int y = 20; y -= 5; // same as y = y-5; System.out.println(x); System.out.println(y); } Output 8.7 15 The += operator adds some value to a variable. Syntax: variable_name += value; The -= operator subtracts some value from a variable. Syntax: variable_name -= value; Whether you use += and -= or not is entirely up to you. Do NOT use these in an exam (miss a symbol => wrong answer)

Converting Doubles to Ints public class example1 { public static void main(String[] args) { double price = 18.53; int dollars = price; System.out.printf("Rounded price: %d dollars", dollars); } The above code gives an error: Java does not allow assigning a double value to an int variable. There are several ways to get around that.

Converting Doubles to Ints public class example1 { public static void main(String[] args) { double price = 18.53; int dollars = (int) price; System.out.printf("Rounded price: %d dollars", dollars); } First approach: casting. Putting (int) in front of the double value asks Java to convert that value to an integer. Casting simply removes the decimal part. (int) 18.53 evaluates to 18. (int) -18.53 evaluates to -18.

Converting Doubles to Ints public class example1 { public static void main(String[] args) { double price = 18.53; int dollars = (int) Math.round(price); System.out.printf("Rounded price: %d dollars", dollars); } Second approach: rounding. Math.round(number) rounds number to the closest integer. We still need to put (int), to convert the result of Math.round into an integer. (int) Math.round(18.53) evaluates to 19. (int) Math.round(-18.53) evaluates to -19.

Converting Doubles to Ints public class example1 { public static void main(String[] args) { double price = 18.53; int dollars = (int) Math.floor(price); System.out.printf("Rounded price: %d dollars", dollars); } Third approach: rounding down (taking the floor). Math.floor(number) rounds number down to an integer. We still need to put (int), to convert the result of Math.floor into an integer. (int) Math.floor(18.53) evaluates to 18. (int) Math.floor(-18.53) evaluates to -19.

Converting Doubles to Ints public class example1 { public static void main(String[] args) { double price = 18.53; int dollars = (int) Math.ceil(price); System.out.printf("Rounded price: %d dollars", dollars); } Fourth approach: rounding up (taking the ceiling). Math.ceil(number) rounds number up to an integer. We still need to put (int), to convert the result of Math.ceil into an integer. (int) Math.ceil(18.53) evaluates to 19. (int) Math.ceil(-18.53) evaluates to -18.

Constants Some variables should never change value. Examples: public class example1 { public static void main(String[] args) { int weeks = 12; final int days_per_week = 7; int days = weeks * days_per_week; System.out.printf("%d weeks = %d days\n", weeks, days); } Some variables should never change value. Examples: Number of days in a week. Constants from math and physics such as pi and e. Other data specific to your application (e.g. minimum number of staff at a desk during a work day)

Constant Variables public class example1 { public static void main(String[] args) { int weeks = 12; final int days_per_week = 7; int days = weeks * days_per_week; System.out.printf("%d weeks = %d days\n", weeks, days); } To tell Java that a variable is a constant, use the keyword final when you declare the variable. Syntax: final type variable_name = value;

Constant Variables public class example1 { public static void main(String[] args) { int weeks = 12; final int days_per_week = 7; int days = weeks * days_per_week; System.out.printf("%d weeks = %d days\n", weeks, days); } If we remove the final keyword in the program above, it runs just as well. (Try it.) However using final is the better practice, because: The code is easier to read and understand (it is clear that days_per_week will not change throughout the program). The compiler will check and report errors such as modifying days_per_week.

Example Where final Is Useful public class example1 { public static void main(String[] args) { int days_per_week = 7; int weeks = 12; days_per_week++; int days = weeks * days_per_week; System.out.printf("%d weeks = %d days\n", weeks, days); } What do you think will happen with this code?

Example Where final Is Useful public class example1 { public static void main(String[] args) { int days_per_week = 7; int weeks = 12; days_per_week++; int days = weeks * days_per_week; System.out.printf("%d weeks = %d days\n", weeks, days); } What do you think will happen with this code? Java will run it, and it will give the wrong answer (12 weeks have 96 days). The days_per_week++ should not have happened, probably the programmer put it there by accident. However, Java cannot possibly know that it was a mistake.

Example Where final Is Useful public class example1 { public static void main(String[] args) { final int days_per_week = 7; int weeks = 12; days_per_week++; int days = weeks * days_per_week; System.out.printf("%d weeks = %d days\n", weeks, days); } What do you think will happen with this code?

Example Where final Is Useful public class example1 { public static void main(String[] args) { final int days_per_week = 7; int weeks = 12; days_per_week++; int days = weeks * days_per_week; System.out.printf("%d weeks = %d days\n", weeks, days); } What do you think will happen with this code? Java will refuse to run it, will give an error: A constant variable is not allowed to change. By declaring a variable as final, you tell Java that if you ever try to change it, you are probably making a mistake and it should not let you.

Multiple Ways to Add/Subtract 1 If we want to add 1 to x, in how many ways can we do it? If we want to subtract 1 from x, in how many ways can we do it?

Multiple Ways to Add/Subtract 1 If we want to add 1 to x, in how many ways can we do it? x++; x += 1; x = x+1; If we want to subtract 1 from x, in how many ways can we do it? x--; x -= 1; x = x-1;