Download presentation
Presentation is loading. Please wait.
Published byAnabel Randall Modified over 8 years ago
1
Lecture 3: More Java Basics Michael Hsu CSULA
2
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
3
Topics to Cover Variables/constants Data Type Type Casting Operators
4
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 * 3.14159; // Display results System.out.println("The area for the circle of radius " + radius + " is " + area); } no value radius allocate memory for radius animation
5
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 * 3.14159; // 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
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 * 3.14159; // 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
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 * 3.14159; // Display results System.out.println("The area for the circle of radius " + radius + " is " + area); } 20 radius memory 1256.636 area compute area and assign it to variable area animation
8
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 * 3.14159; // Display results System.out.println("The area for the circle of radius " + radius + " is " + area); } 20 radius memory 1256.636 area print a message to the console animation
9
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
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. https://docs.oracle.com/javase/tutorial/java/nutsandbolts/_keywords.html https://docs.oracle.com/javase/tutorial/java/nutsandbolts/_keywords.html An identifier cannot be true, false, or null. An identifier can be of any length.
11
11 Concept of Variables // Compute the first area radius = 1.0; area = radius * radius * 3.14159; System.out.println("The area is “ + area + " for radius "+radius); // Compute the second area radius = 2.0; area = radius * radius * 3.14159; System.out.println("The area is “ + area + " for radius "+radius);
12
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
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
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
15 Constants final datatype CONSTANTNAME = VALUE; final double PI = 3.14159; final int SIZE = 3;
16
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
17
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
18
Base 10 to Base 2 (Binary) conversion Source: http://www.wikihow.com/images/4/43/Convert-from-Decimal-to-Binary-Step-14-Version-2.jpg
19
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
20
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
21
Numerical Data Types
22
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
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 http://introcs.cs.princeton.edu/java/91float/ http://introcs.cs.princeton.edu/java/91float/
24
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
25
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.
26
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.
27
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
28
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
29
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
30
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
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
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
33 Augmented Assignment Operators
34
34 Increment and Decrement Operators
35
35 Increment and Decrement Operators, cont.
36
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
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--;
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.