John Hurley Cal State LA CS 201 Lecture 3:. 2 Reserved Words Reserved words or keywords are words that have a specific meaning to the compiler and cannot.

Slides:



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

10-Jun-15 Just Enough Java. Variables A variable is a “box” that holds data Every variable has a name Examples: name, age, address, isMarried Variables.
10-Jun-15 Introduction to Primitives. 2 Overview Today we will discuss: The eight primitive types, especially int and double Declaring the types of variables.
Primitive Data Types and Operations. Introducing Programming with an Example public class ComputeArea { /** Main method */ public static void main(String[]
Bellevue University CIS 205: Introduction to Programming Using C++ Lecture 3: Primitive Data Types.
Introduction to Computers and Programming Lecture 4: Mathematical Operators New York University.
COMPSCI 125 Spring 2005 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 3: Numeric Data *Variables *Numeric data.
Chapter 3 Numerical Data. Topics Variables Numeric data types Assignment Expressions.
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie June 27, 2005.
Copyright 2008 by Pearson Education 1 Building Java Programs Chapter 2 Lecture 2-1: Expressions and Variables reading:
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.
Java Primitives The Smallest Building Blocks of the Language (corresponds with Chapter 2)
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.
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
C++ Programming: Basic Elements of C++.
Using Data Within a Program Chapter 2.  Classes  Methods  Statements  Modifiers  Identifiers.
Copyright 2008 by Pearson Education 1 Building Java Programs Chapter 2 Lecture 2-1: Expressions and Variables reading:
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.
A Simple Java Program //This program prints Welcome to Java! public class Welcome { public static void main(String[] args) { public static void main(String[]
Copyright 2010 by Pearson Education 1 Building Java Programs Chapter 2 Lecture 2-1: Expressions and Variables reading:
1 Week 5 l Primitive Data types l Assignment l Expressions l Documentation & Style Primitive Types, Assignments, and Expressions.
1 Building Java Programs Chapter 2 Lecture 2-1: Expressions and Variables reading:
Topic 4 Expressions and variables Based on slides bu Marty Stepp and Stuart Reges from "Once a person has understood.
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.
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.
John Hurley Spring 2011 Cal State LA CS 201 Lecture 5:
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.
Copyright 2010 by Pearson Education 1 Building Java Programs Chapter 2 Lecture 2-1: Expressions and Variables reading:
John Hurley Cal State LA
Unit 2 Elementary Programming
Lecture 3: Operators, Expressions and Type Conversion
Building Java Programs
Lecture 2: Operations and Data Types
Multiple variables can be created in one declaration
Primitive Data, Variables, Loops (Maybe)
Building Java Programs Chapter 2
مساق: خوارزميات ومبادئ البرمجة الفصل الدراسي الثاني 2016/2015
Building Java Programs
Building Java Programs
Building Java Programs
Building Java Programs Chapter 2
Expressions and Assignment
Building Java Programs
Building Java Programs
Building Java Programs
Building Java Programs
Building Java Programs
Building Java Programs
Building Java Programs
Building Java Programs
Building Java Programs
Building Java Programs
Primitive Types and Expressions
Building Java Programs
Unit 3: Variables in Java
Building Java Programs Chapter 2
Building Java Programs
Chapter 2 Primitive Data Types and Operations
Building Java Programs
Building Java Programs
Building Java Programs
Chapter 2: Beginning to Program
Presentation transcript:

John Hurley Cal State LA CS 201 Lecture 3:

2 Reserved Words Reserved words or keywords are words that have a specific meaning to the compiler and cannot be used for other purposes in the program. For example, when the compiler sees the word class, it understands that the word after class is the name for the class. Some other reserved words include public, private, static, and void. Their use will be introduced later. Don’t use them as names for variables or classes.

3 Assignments x = 1 is an assignment that sets x to the value 1 To the computer, this means “go find the memory you set aside to keep track of x and replace the value there with 1” x == 1 is a test that is true if x is equal to 1, otherwise false. Usually used in a expression like if(x == 1) System.out.println(“x is equal to 1!”);

4 More Fun With Data Types boolean Value that is either true or false inequalities and tests in loop statements evaluate to boolean values 1 < 2 is true, so 2 < 1 is false 2 == 2 is true int i = 2; System.out.println(i + " < " "?" + (i < 5)); prints “true”

5 More Fun With Data Types public class BooleanDemo{ public static void main(String[] args){ for(int i = 0; i < 10; i++){ System.out.println(i + " < " "? " + (i < 5)); System.out.println(i + " == " "? " + (i == 5)); System.out.println(i + " > " "? " + (i > 5) + "\n"); } System.out.println(" (1 == 1) == (2 == 1)? " + ((1 == 1) == (2 == 1))); System.out.println(" (1 < 2) == (2 < 3)? " + ((1 < 2) == (2 < 3))); } }

6 More Fun With Data Types char One character Set value using single quotes: char myChar = ‘A’; ‘A’ is not the same as ‘a’

7 More Fun With Data Types String Sequence of zero or more characters. Note the capital S String is a class; we will learn what that means later. Set values using double quotes: String myString = “Get your own String, This one is mine.” “” is called a null String or empty String.

8 More Fun With Data Types public class CharStringDemo{ public static void main(String[] args){ char myChar = 'a'; String myString = "John Hurley"; System.out.println(myChar); System.out.println(myString); }

9 Math Operations Java's math operations are easy to understand x = 1; // sets x to 1 x = x + 1; // adds 1 to x x = x * y; // multiplies x by y x = 100.0/9.2; // x should be a floating point // type, not an integer x = y + 100;

10 Math Operations: Modulo Modulo may be unfamiliar. It performs integer division and yields the remainder. The modulo operator is the symbol % x = y % 3; means "divide y by 3, ignore the quotient, and assign the remainder as the new value of x." y should be an integer. Modulo has many uses. The simplest one is that it tells us whether an integer is evenly divisible by another integer. If, for example a % b == 0, then a is evenly divisible by b. 9 % 3 is 0 10 % 3 is 1

11 Math Operations and Data Type What will the output from this code be? public class Mathematician{ public static void main(String[] args){ int total = 5; int divisor = 4; int result = total / divisor; System.out.println( total + "/" +divisor + " = " + result); }

12 Math Operations and Data Type What about this one? public class Mathematician{ public static void main(String[] args){ int total = 5; int divisor = 3; int result = total / divisor; System.out.println( total + "/" +divisor + " = " + result); }

13 Math Operations and Data Type This one still doesn’t work! public class Mathematician{ public static void main(String[] args){ int total = 5; int divisor = 4; double result = total / divisor; System.out.println( total + "/" +divisor + " = " + result); }

14 Math Operations and Data Type To get a floating point result from division, you must make at least one of the operands a floating point type: public class Mathematician{ public static void main(String[] args){ int total = 5; double divisor = 4; double result = total / divisor; System.out.println( total + "/" +divisor + " = " + result); }

15 Conversion Rules 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”

16 Casting Casting converts data types You should rarely have to do this at this point For primitive types, the syntax looks like this: int x = (int) 5.1; Casting a floating point type to an integer truncates, doesn’t round! int x = (int) 1.6; sets x to 1, not 2!

17 Casting Casting the value back to the original type does not restore lost data, so if you need the original value, go back to the original variable public class Caster{ public static void main(String[] args){ double x = 1.6; int y = (int) x; System.out.println(x); System.out.println(y); System.out.println((double) y); System.out.println(x); } outputs:

18 Constants Imagine you are writing aprogram which can calculate the circumference of a circle: 2 π r the area of a circle: π r 2 the volume of a cylinder: π r 2 h You could type in a value of pi each time you will use it double radius = 5.1; double height = 3; … double circumference = 2 * 3.14 * radius; … double area = 3.14 * radius * radius; … double volume = 3.14 * radius * radius * height;

19 Constants Better idea: define a constant and set its value once Less risk of errors or inconsistencies Clearer code; it’s easier to recognize the constant name than the value Easier to change precision Used 3.14 before for simplicity, but results were not accurate enough. Now you want to use

20 Constants Use all caps for constant names Use final keyword final double PI = ; … code omitted… double circumference = 2 * PI * radius;

Just as in arithmetic and algebra, you can combine simple operations into complex calculations of any length public class Converter{ public static void main(String[] args){ double celsius; double fahrenheit = 212; celsius = (fahrenheit -32) * 5.0/9; System.out.println(fahrenheit + " degrees F = " + celsius + " degrees C"); } Combining Operations

22 Operator Precedence

23 Operator Associativity Binary operators are those that take two operands. Example: a - b All binary operators except assignment operators are left-associative. a – b + c – d is equivalent to ((a – b) + c) – d Assignment operators are right-associative. Therefore, the expression a = b += c = 5 is equivalent to a = (b += (c = 5)) x = 1 X = 10 * b;

24 Formatting Output Use the printf statement. System.out.printf(format, items); Where format is a string that may consist of substrings and format specifiers. A format specifier specifies how an item should be displayed. An item may be a numeric value, character, boolean value, or a string. Each specifier begins with a percent sign.

25 Frequently-Used Specifiers Specifier OutputExample %b a boolean value true or false %c a character 'a' %d a decimal integer 200 %f a floating-point number %e a number in standard scientific notation e+01 %s a string "Java is cool"

Printf public class PrintfDemo{ public static void main(String[] args){ int intVar = 1; double doubleVar = ; double moonRadius = ; // in meters char charVar = 'a'; String stringVar = "Hi, Mom"; boolean boolVar = true; System.out.printf("\nintVar: %d; \ndoubleVar: %f; \ndoubleVar to 4 places: %7.4f; \nmoonRadius: %e; \ncharVar: %c; \nstringVar: %s", intVar, doubleVar, doubleVar, moonRadius, charVar, stringVar); } // end main() } // end class

27 Naming Conventions Choose meaningful and descriptive names. Variables and method names: Use lowercase. If the name consists of several words, concatenate all in one, use lowercase for the first word, and capitalize the first letter of each subsequent word in the name. For example, the variables radius and area, and the method computeArea.

28 Naming Conventions, cont. Class names: Capitalize the first letter of each word in the name. For example, the class name ComputeArea. Constants: Capitalize all letters in constants. Use underscores to connect words or just run words together. For example, the constant PI and MAX_VALUE or MAXVALUE

Programming is frustrating, but you will not experience anything that every other programmer who ever lived has not also experienced. You will never get anything right on the first try, and rarely on the tenth. This is the real origin of the term “hacking” The problem is not that you are not smart enough, it is that programming requires closer attention to detail than is normal for a human being. Rough guess: you will spend 5% of your time writing the frist draft of your code and 95% of your time figuring out why it doesn’t work and fixing it Debugging = the process of finding and correcting defects in a piece of software (definition adapted from Wikipedia) Professional software development organizations spend more time testing than programming, and programming itself consists mostly of debugging. What to Expect

Programmers’ proverb: “A computer is like an idiot with a perfect memory who never gets tired” it will do exactly what you say, but it is very hard for you to figure out how to say what you want it does not understand your intentions or any kind of subtext. It will do neither more nor less than what you tell it to do you will never be able to think out your programs well enough to account for all possibilities Assume everything that goes wrong is your fault. At this stage in your programming career, problems will almost always be caused by your failure to think things out. You will be tempted to blame hardware failures, problems with Java, or bugs in Windows/OSX/Linux; you’ll almost always be wrong. What to Expect