Lecture 3: More Java Basics Michael Hsu CSULA. Recall From Lecture Two  Write a basic program in Java  The process of writing, compiling, and running.

Slides:



Advertisements
Similar presentations
L2:CSC © Dr. Basheer M. Nasef Lecture #2 By Dr. Basheer M. Nasef.
Advertisements

Chapter 2 Elementary Programming
Introduction to Computing Concepts Note Set 7. Overview Variables Data Types Basic Arithmetic Expressions ▫ Arithmetic.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 2 1 Chapter 2 Primitive.
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.
Chapter 2 Primitive Data Types and Operations F Introduce Programming with an Example F Identifiers, Variables, and Constants F Primitive Data Types –byte,
Primitive Data Types and Operations. Introducing Programming with an Example public class ComputeArea { /** Main method */ public static void main(String[]
Aalborg Media Lab 21-Jun-15 Software Design Lecture 2 “ Data and Expressions”
Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 2 Primitive Data.
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.
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie June 27, 2005.
Fundamental Programming Structures in Java: Comments, Data Types, Variables, Assignments, Operators.
1 Chapter 2: Elementary Programming Shahriar Hossain.
CSci 142 Data and Expressions. 2  Topics  Strings  Primitive data types  Using variables and constants  Expressions and operator precedence  Data.
Introduction to Java Programming, 4E Y. Daniel Liang.
String Escape Sequences
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 2 Elementary Programming.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 1 Chapter 2 Elementary Programming.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 1 Chapter 2 Elementary Programming.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 1 Chapter 2 Elementary Programming.
Java Building Elements Lecture 2 Instructors: Fu-Chiung Cheng ( 鄭福炯 ) Associate Professor Computer Science & Engineering Tatung University
Java Primitives The Smallest Building Blocks of the Language (corresponds with Chapter 2)
Chapter 2 Elementary Programming 1. Introducing Programming with an Example Listing 2.1 Computing the Area of a Circle This program computes the area.
Primitive Data Types and Operations Identifiers, Variables, and Constants Primitive Data Types Byte, short, int, long, float, double, char, boolean Casting.
Chapter 2 Primitive Data Types and Operations F Introduce Programming with an Example  The MyInput class F Identifiers, Variables, and Constants F Primitive.
1 Chapter 2 Primitive Data Types and Operations F Introduce Programming with an Example  The MyInput class F Identifiers, Variables, and Constants F Primitive.
Chapter 2: Basic Elements of Java J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Second Edition.
VARIABLES Introduction to Computer Science 1- COMP 1005, 1405 Instructor : Behnam Hajian
1 Do you have a CS account? Primitive types –“ building blocks ” for more complicated types Java is strongly typed –All variables in a Java program must.
Introduction to Java Applications Part II. In this chapter you will learn:  Different data types( Primitive data types).  How to declare variables?
Chapter 2 Elementary Programming
Java Programming: From Problem Analysis to Program Design, 4e Chapter 2 Basic Elements of Java.
Using Data Within a Program Chapter 2.  Classes  Methods  Statements  Modifiers  Identifiers.
College Board A.P. Computer Science A Topics Program Design - Read and understand a problem's description, purpose, and goals. Procedural Constructs.
PHY-102 SAPVariables and OperatorsSlide 1 Variables and Operators In this section we will learn how about variables in Java and basic operations one can.
Data Types and Statements MIT 12043: Fundamentals of Programming Lesson 02 S. Sabraz Nawaz Fundamentals of Programming by
A Simple Java Program //This program prints Welcome to Java! public class Welcome { public static void main(String[] args) { public static void main(String[]
Programming in Java (COP 2250) Lecture 4 Chengyong Yang Fall, 2005.
Operators and Expressions. 2 String Concatenation  The plus operator (+) is also used for arithmetic addition  The function that the + operator performs.
Variables and Constants Objectives F To understand Identifiers, Variables, and Constants.
Tokens in C  Keywords  These are reserved words of the C language. For example int, float, if, else, for, while etc.  Identifiers  An Identifier is.
Java Programming: From Problem Analysis to Program Design, Second Edition 1 Lecture 1 Objectives  Become familiar with the basic components of a Java.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Elementary Programming.
1 1 Chapter 2 Elementary Programming. 2 2 Motivations In the preceding chapter, you learned how to create, compile, and run a Java program. Starting from.
CSE 110: Programming Language I Matin Saad Abdullah UB 1222.
CS 201 Lecture 2: Elementary Programming Tarik Booker CS 201 California State University, Los Angeles.
Primitive Data Types and Operations F Introduce Programming with an Example F Identifiers, Variables, and Constants F Primitive Data Types –byte, short,
1.  Algorithm: 1. Read in the radius 2. Compute the area using the following formula: area = radius x radius x PI 3. Display the area 2.
© 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 2 Elementary Programming
Topic 2 Elementary Programming
Unit 2 Elementary Programming
Elementary Programming
Lecture 3: Operators, Expressions and Type Conversion
Primitive Data Types August 28, 2006 ComS 207: Programming I (in Java)
Multiple variables can be created in one declaration
Java Programming: From Problem Analysis to Program Design, 4e
Chapter 2 Elementary Programming
IDENTIFIERS CSC 111.
مساق: خوارزميات ومبادئ البرمجة الفصل الدراسي الثاني 2016/2015
Numerical Data Types.
Chapter 2: Java Fundamentals
Chapter 2 Elementary Programming
Expressions and Assignment
elementary programming
Fundamental OOP Programming Structures in Java: Comments, Data Types, Variables, Assignments, Operators.
In this class, we will cover:
Chapter 2 Primitive Data Types and Operations
Chapter 2: Beginning to Program
Presentation transcript:

Lecture 3: More Java Basics Michael Hsu CSULA

Recall From Lecture Two  Write a basic program in Java  The process of writing, compiling, and running a Java program  Write a String literal to standard output  System.out.println(“……”);  Naming conventions

Topics to Cover  Variables/constants  Data Type  Type Casting  Operators

4 Trace a Program Execution public class ComputeArea { /** Main method */ public static void main(String[] args) { double radius; double area; // Assign a radius radius = 20; // Compute area area = radius * radius * ; // Display results System.out.println("The area for the circle of radius " + radius + " is " + area); } no value radius allocate memory for radius animation

5 Trace a Program Execution public class ComputeArea { /** Main method */ public static void main(String[] args) { double radius; double area; // Assign a radius radius = 20; // Compute area area = radius * radius * ; // Display results System.out.println("The area for the circle of radius " + radius + " is " + area); } no value radius memory no value area allocate memory for area animation

6 Trace a Program Execution public class ComputeArea { /** Main method */ public static void main(String[] args) { double radius; double area; // Assign a radius radius = 20; // Compute area area = radius * radius * ; // Display results System.out.println("The area for the circle of radius " + radius + " is " + area); } 20 radius no value area assign 20 to radius animation

7 Trace a Program Execution public class ComputeArea { /** Main method */ public static void main(String[] args) { double radius; double area; // Assign a radius radius = 20; // Compute area area = radius * radius * ; // Display results System.out.println("The area for the circle of radius " + radius + " is " + area); } 20 radius memory area compute area and assign it to variable area animation

8 Trace a Program Execution public class ComputeArea { /** Main method */ public static void main(String[] args) { double radius; double area; // Assign a radius radius = 20; // Compute area area = radius * radius * ; // Display results System.out.println("The area for the circle of radius " + radius + " is " + area); } 20 radius memory area print a message to the console animation

Variables and Constants  One of the basic building blocks of a program  Similar to variables and constants in math  Recall from lecture two:  Computer has memory addresses to store and retrieve data  Variables/constants, in the general sense, allocate memory for specific data you’re using in a program  Example:  double radius = 0;  Allocates space to store a double, names it radius (think memory address), then stores the value 0 at the memory address  We call the name of the variable an identifier

10 Identifiers  An identifier is a sequence of characters that consist of letters, digits, underscores (_), and dollar signs ($).  Names of variables, methods, classes, etc.  The name of a class is an identifier  An identifier must start with a letter, an underscore (_), or a dollar sign ($). It cannot start with a digit.  An identifier cannot be a reserved word.   An identifier cannot be true, false, or null.  An identifier can be of any length.

11 Concept of Variables // Compute the first area radius = 1.0; area = radius * radius * ; System.out.println("The area is “ + area + " for radius "+radius); // Compute the second area radius = 2.0; area = radius * radius * ; System.out.println("The area is “ + area + " for radius "+radius);

12 Declaring Variables int x; // Declare x to be an // integer variable; double radius; // Declare radius to // be a double variable; char a; // Declare a to be a // character variable; In Java, you must declare variables before you use them

13 Assignment and Comparison Statements Note: a SINGLE equal sign is assignment in Java. To compare variables, use == x = 1; // Assign 1 to x; radius = 1.0; // Assign 1.0 to radius; a = 'A'; // Assign 'A' to a; 1 == 1// Is one equal to one?

14 Declaring and Initializing in One Step  int x = 1;  double d = 1.4;  For now, you have to initialize all your variable before you access them, as they are so called “local variables” (local to the main method).

15 Constants final datatype CONSTANTNAME = VALUE; final double PI = ; final int SIZE = 3;

Naming Convention For Variables/Constants  For variables, use lowerCamelCase  First word starts with lower case, the rest upper case  Choose meaningful, descriptive names, usually nouns.  Capitalize all letters in constants, and use underscores to connect words. For example, the constant PI and MAX_VALUE  More examples of constant:  HEIGHT_OF_MICHAEL  ABOGADRO_CONSTANT  Again, if you don’t pick reasonable names/follow naming conventions, I will take off points

Before We Talk About Data Types:  Recall from lecture 2, data is stores as zeroes and ones on the computer  In binary  Bit  Unit of information  It is either 0 or 1 (on or off, true or false)  Logic gates/transistors  Bits make up binary numbers, represented with base 2

Base 10 to Base 2 (Binary) conversion Source:

Bytes  1 Byte = 8 Bit (8 digits in binary)  1 Kilobyte = 1,024 Bytes  1 Megabyte = 1,048,576 Bytes  1 Gigabyte = 1,073,741,824 Bytes  1 Terabyte = 1,099,511,627,776 Bytes  Note: powers of 2

Data Types  Recall from previous slides, when we declare variables/constants, we specify why type it is  A String literal also has a data type: it is of type String  Different data types take up different amount of space

Numerical Data Types

Numerical Data Types Cont.  Be careful on what numeric type you use to store data  Different types take up different amounts of memory  You will most likely not use byte or short for this course  Remember that each numeric type has a set range of possible values  For now, use int for integer values, use double for decimal values

23 Floating Point Types  Include the types float and double  Uses scientific Notation in binary to store data  IEEE 754  These types store values with limited precision, essentially rounding to the closest value they can hold  More Info 

Floating Point Types Rounding Errors  Floating point arithmetic is not exact, as some numbers require infinite amount of digits to be represented (like 1/10) in binary.  Example:  FloatingPointComparison.java  Lesson of the day:  Do not rely on floating point types for accurate calculations  What if we’re calculating money? Use BigDecimal  Do not do test for equality between floating point nubmers

More Data Types  boolean  Either true or false  Comparisons evaluate to boolean values  100 > 2 true  2 == 2 true  char  Single character  Set literal value using single quotes:  char exampleChar = ‘B’  You can also use ASCII values:  char exampleChar = 66  Since the variable is of chart datatype, java knows that you are using the ASCII value to refer to the character ‘B’  As a result, ‘b’ is different from ‘B’ since they have different ASCII values.

Primitive Data Types  Predefined by the language  basic types that build up other types  In later classes, you will use primitives to create your own data types  Only the values are copied when you reassign primitive type variables to each other  More on this later  Includes all the numeric data types mentioned in previous slides, plus boolean and char.

Strings  A sequence of zero or more characters  You already used them in the System.out.println statements  Set values using double quotes  The ‘S’ is capitalized  It is NOT a primitive type, but a class  Will be covered later  String helloWorld = “Hello, World”;  “” null String/empty String

Math Operations  Most of them are just like how you do it in math  int x = 1; // declared an integer variable x, sets x to be 1  x = x + 1; // adds 1 to x  x = x * 2; // multiplies x by 2  X = 2/3 //integer division  x = 100.0/9.2; //Floating point division  Integer division: when all variables in the calculation are numeric non- floating point types, the decimal portion is dropped.  Example: 1/2 == 0, 20/6 == 3, 14/200 == 0

The Modulo operator  %  Performs integer division, and returns the remainder.  x = 7 % 3  Divide 7 by 3, find the remainder, then assign value of the remainder to x  In this case x is 1  Very useful  Calculate divisibility:  If a % b == 0, then a is evenly divisible by b

How to Get Floating Point Results from Calculations?  One or more of the operands must be of floating point type  When performing a binary* operation involving two operands of different types, Java automatically converts the operand based on the following rules: 1. If one of the operands is double, the other is converted into double. 2. Otherwise, if one of the operands is float, the other is converted into float. 3. Otherwise, if one of the operands is long, the other is converted into long. 4. Otherwise, both operands are converted into int.  * In this case binary means “involving two operands,” not “ in base 2”

31 Type Casting  Converting between data types Implicit casting double d = 3; (type widening) Explicit casting int i = (int)3.0; (type narrowing) int i = (int)3.9; (Fraction part is truncated) char i = (char) 65; (ASCII code to char) What is wrong?int x = 5 / 2.0;

32 Casting in an Augmented Expression In Java, an augmented expression of the form x1 op= x2 is implemented as x1 = (T)(x1 op x2), where T is the type for x1. Therefore, the following code is correct. int sum = 0; sum += 4.5; // sum becomes 4 after this statement sum += 4.5 is equivalent to sum = (int)(sum + 4.5).

33 Augmented Assignment Operators

34 Increment and Decrement Operators

35 Increment and Decrement Operators, cont.

36 Increment and Decrement Operators, cont. Using increment and decrement operators makes expressions short, but it also makes them complex and difficult to read. Avoid using these operators in expressions that modify multiple variables, or the same variable for multiple times such as this: int k = ++i + i.

37 Assignment Expressions and Assignment Statements Prior to Java 2, all the expressions can be used as statements. Since Java 2, only the following types of expressions can be statements: variable op= expression; // Where op is +, -, *, /, or % ++variable; variable++; --variable; variable--;