What did we talk about last time? Examples switch statements

Similar documents
What did we talk about last time? Math methods boolean operations char operations

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

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

Full file at

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

Define a method vs. calling a method. Chapter Goals. Contents 1/21/13

CMSC131. Introduction to your Introduction to Java. Why Java?

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

12/22/11. Java How to Program, 9/e. Help you get started with Eclipse and NetBeans integrated development environments.

Chapter 1. Introduction to Computers and Programming. M hiwa ahmad aziz

Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal

COSC 123 Computer Creativity. Introduction to Java. Dr. Ramon Lawrence University of British Columbia Okanagan

Wentworth Institute of Technology. Engineering & Technology WIT COMP1000. Java Basics

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

Chapter. Let's explore some other fundamental programming concepts

Getting started with Java

Basics of Java Programming

Review Chapters 1 to 4. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

CONTENTS: Compilation Data and Expressions COMP 202. More on Chapter 2

ECE 122 Engineering Problem Solving with Java

The type of all data used in a C (or C++) program must be specified

Important Java terminology

Lecture 2. COMP1406/1006 (the Java course) Fall M. Jason Hinek Carleton University

Introduction to Software Development (ISD) David Weston and Igor Razgon

2/9/2012. Chapter Four: Fundamental Data Types. Chapter Goals

4. Java Project Design, Input Methods

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

Chapter 2: Data and Expressions

double float char In a method: final typename variablename = expression ;

Programming with Java

Lecture Set 2: Starting Java

Università degli Studi di Bologna Facoltà di Ingegneria. Principles, Models, and Applications for Distributed Systems M

The type of all data used in a C++ program must be specified

Review for Test 1 (Chapter 1-5)

Lecture Set 2: Starting Java

CS 106 Introduction to Computer Science I

Hello World. n Variables store information. n You can think of them like boxes. n They hold values. n The value of a variable is its current contents

Lesson 02 Data Types and Statements. MIT 11053, Fundamentals of Programming By: S. Sabraz Nawaz Senior Lecturer in MIT Department of MIT FMC, SEUSL

Computer Components. Software{ User Programs. Operating System. Hardware

CS 302: Introduction to Programming

First Java Program - Output to the Screen

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

A Java program contains at least one class definition.

Lesson 02 Data Types and Statements. MIT 12043, Fundamentals of Programming By: S. Sabraz Nawaz Senior Lecturer in MIT Department of MIT FMC, SEUSL

Program Elements -- Introduction

Methods CSC 121 Fall 2016 Howard Rosenthal

Chapter 4 Fundamental Data Types. Big Java by Cay Horstmann Copyright 2009 by John Wiley & Sons. All rights reserved.

Methods CSC 121 Spring 2017 Howard Rosenthal

Chapter 2: Data and Expressions

MODULE 02: BASIC COMPUTATION IN JAVA

More Things We Can Do With It! Overview. Circle Calculations. πr 2. π = More operators and expression types More statements

AP Computer Science A

AP Computer Science Unit 1. Programs

int: integers, no fractional part double: floating-point numbers (double precision) 1, -4, 0 0.5, , 4.3E24, 1E-14

2: Basics of Java Programming

Full file at

1001ICT Introduction To Programming Lecture Notes

COMP-202 Unit 2: Java Basics. CONTENTS: Using Expressions and Variables Types Strings

Zheng-Liang Lu Java Programming 45 / 79

Mobile Computing Professor Pushpendra Singh Indraprastha Institute of Information Technology Delhi Java Basics Lecture 02

COMP-202: Foundations of Programming. Lecture 2: Variables, and Data Types Sandeep Manjanna, Summer 2015

Computational Expression

Section 2: Introduction to Java. Historical note

Chapter 4 Fundamental Data Types. Big Java by Cay Horstmann Copyright 2009 by John Wiley & Sons. All rights reserved.

Primitive Data, Variables, and Expressions; Simple Conditional Execution

Introduction to Java & Fundamental Data Types

Computer Components. Software{ User Programs. Operating System. Hardware

Primitive Data Types: Intro

School of Computer Science CPS109 Course Notes 5 Alexander Ferworn Updated Fall 15

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

CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 10: OCT. 6TH INSTRUCTOR: JIAYIN WANG

COMP-202 Unit 2: Java Basics. CONTENTS: Using Expressions and Variables Types Strings Methods

Expressions and Data Types CSC 121 Spring 2017 Howard Rosenthal

Chapter 2 Using Data. Instructor s Manual Table of Contents. At a Glance. Overview. Objectives. Teaching Tips. Quick Quizzes. Class Discussion Topics

Pace University. Fundamental Concepts of CS121 1

Lecture 6. Assignments. Summary - Variables. Summary Program Parts 1/29/18. Reading: 3.1, 3.2, 3.3, 3.4

CSE 142 Su 04 Computer Programming 1 - Java. Objects

COMP Computer Basics. Yi Hong May 13, 2015

Basic Computation. Chapter 2

Program Fundamentals

Week 2: Data and Output

Exam 1 Prep. Dr. Demetrios Glinos University of Central Florida. COP3330 Object Oriented Programming

DATA TYPES AND EXPRESSIONS

COMP 202 Java in one week

FUNDAMENTAL DATA TYPES

CS112 Lecture: Primitive Types, Operators, Strings

Chapter 2: Data and Expressions

COMP 202 Java in one week

CS 152: Data Structures with Java Hello World with the IntelliJ IDE

COMP-202: Foundations of Programming

Key Concept: all programs can be broken down to a combination of one of the six instructions Assignment Statements can create variables to represent

Introduction to Computer Science Unit 2. Notes

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

Lecture 6. Assignments. Java Scanner. User Input 1/29/18. Reading: 2.12, 2.13, 3.1, 3.2, 3.3, 3.4

Visual C# Instructor s Manual Table of Contents

Intro to Programming. Unit 7. What is Programming? What is Programming? Intro to Programming

CS 11 java track: lecture 1

Introduction to Java Applications

Java Classes: Math, Integer A C S L E C T U R E 8

Variables and data types

Transcription:

Week 4 - Friday

What did we talk about last time? Examples switch statements

History of computers Hardware Software development Basic Java syntax Output with System.out.print()

Mechanical Calculation Devices (2400BC onward) Aid to human calculation No stored program Mechanical Computers (1725 onward) Punch card programming Serious limitations Early Electronic Computers (1941 onward) General purpose, stored program computers Electronic, using vacuum tubes Microprocessors (1970's onward) Succeeded transistors Now billions of computations per second at a nanometer scale

Cache Actually on the CPU Fast and expensive RAM Primary memory for a desktop computer Pretty fast and relatively expensive Flash Drive Faster than hard drives Seen on USB drives but SSDs are becoming common too Hard Drive Secondary memory for a desktop computer Slow and cheap Optical Drive Secondary memory that can usually only be written once Very slow and very cheap

Storage for all the data and instructions on your computer Modern computers store everything as binary digits (bits) which have a value of 0 or 1. 1 byte = 8 bits 1 kilobyte (kb) = 2 10 bytes 1 megabyte (mb) = 2 20 bytes 1 gigabyte (gb) = 2 30 bytes 1 terabyte (tb) = 2 40 bytes

Monitor Common visual output device Speakers Common audio output device Mouse Common input device Keyboard Common input device

Source Code Machine Code Hardware Computer! Solve a problem; 010101010 010100101 001110010 Execute

Java Source Code Java Bytecode Machine Code Hardware class A { Problem p; p.solve(); } 101110101 101011010 110010011 JVM 010101010 010100101 001110010

Often goes through phases similar to the following: 1. Understand the problem 2. Plan a solution to the problem 3. Implement the solution in a programming language 4. Test the solution 5. Maintain the solution and do bug fixes Factor of 10 rule!

The absolute smallest program possible, with a print statement public class Hello { public static void main(string[] args) { System.out.println("Hello, world!"); } }

For example, instead of one print statement, we can have several: System.out.println("Hello, world!"); System.out.println("Hello, galaxy!"); System.out.println("Goodbye, world!"); Each statement is an instruction to the computer They are printed in order, one by one

Java is a case sensitive language Class is not the same as class System.out.println("Word!"); prints correctly system.out.println("word!"); does not compile

Java generally ignores whitespace (tabs, newlines, and spaces) System.out.println("Hello, world!"); is the same as: println( System.out. "Hello, world!"); You should use whitespace effectively to make your code readable

There are two kinds of comments (actually 3) Single line comments use // System.out.println("Hi!"); // this is a comment Multi-line comments start with a /* and end with a */ System.out.println("Hi!"); /* this is a multi-line comment */

Binary representation Basic data types Using Scanner for input

The binary number system is base 2 This means that its digits are: 0 and 1 Base 2 means that you need 2 digits to represent two, namely 1 and 0 Each place in the number as you move left corresponds to an increase by a factor of 2 instead of 10

Sixty fours 256 s Sixteens Fours 1024 s 11111100001 Ones 512 s Twos 128 s Eights Thirty twos

We're focusing on five basic types of data in Java These are: int double boolean char String For whole numbers For rational numbers For true or false values For single characters For words String is a little different from the rest, since you can call methods on it (and for other reasons)

Type Kind of values Sample Literals int double boolean char Integers Floating-point Numbers Boolean values Single characters -5 0 900031 3.14-0.6 6.02e23 true false 'A' 'Z' '&' String Sequences of characters "If you dis Dr. Dre" "10 Sesquipedalians"

The int type is used to store integers (positive and negative whole numbers and zero) Examples: 54-893992 0 Inside the computer, an int takes up 4 bytes of space, which is 32 bits (1's and 0's)

You will use the int type very often Sometimes, however, you need to represent numbers with a fractional part The double type is well suited to this purpose Declaration of a double variable is just like an int variable: double x;

Numbers are great But, sometimes you only need to keep track of whether or not something is true or false This is what the boolean type is for Hopefully you have more appreciation for booleans now Declaration of a boolean variable is like so: boolean value;

Sometimes you need to deal with characters This is what the char type is for The char type only allows you to store a single character like '$' or 'q' Declaration of a char variable is like so: char c;

The String type is different from the other types in several ways The important thing for you to focus on now is that it can hold a large number of chars, not just a single value A String literal is what we used in the Hello, World program String word;

There are three parts to using Scanner for input 1. Include the appropriate import statement so that your program knows what a Scanner object is 2. Create a specific Scanner object with a name you choose 3. Use the object you create to read in data

Lots of people have written all kinds of useful Java code By importing that code, we can use it to help solve our problems To import code, you type import and then the name of the package or class To import Scanner, type the following at the top of your program (before the class!) import java.util.scanner;

Once you have imported the Scanner class, you have to create a Scanner object To do so, declare a reference of type Scanner, and use the new keyword to create a new Scanner with System.in as a parameter like so: Scanner in = new Scanner(System.in); You can call it whatever you want, I chose to call it in Doesn't make any sense? For now, that's okay.

Now that you've got a Scanner object, you can use it to read some data It has a method that will read in the next piece of data that user types in, but you have to know if that data is going to be an int, a double, or a String Let's say the user is going to input her age (an int) and you want to store it in an int variable called years We'll use the nextint() method to do so: int years; years = in.nextint();

Scanner has a lot of methods (ways to accomplish some tasks) For now, we're only interested in three These allow us to read the next int, the next double, and the next String, respectively: Scanner in = new Scanner(System.in); int number = in.nextint(); double radius = in.nextdouble(); String word = in.next();

Numerical operations Advanced math operations boolean operations char operations String operations Wrapper classes

+ adds - subtracts * multiplies / divides (integer division for int type and fractional parts for double type) % finds the remainder

Order of operations holds like in math int a = 31; int b = 16; int c = 1; int d = 2; a = (((b + c) * d) a / b) / d; You can use parentheses to clarify or change the precedence Now a is 16

You cannot directly store a double value into an int variable int a = 2.6; // fails! However, you can cast the double value to convert it into an int int a = (int)2.6;// succeeds! (a = 2) Casting tells the compiler that you want the loss of precision to happen You can always store an int into a double

The sin() method allows you to find the sine of an angle (in radians) This method is inside the Math class The answer that it gives back is of type double To use it, you might type the following: double value = Math.sin( 2.4 );

In Java, the conversion of a double into an int does not use rounding As in the case of integer division, the fractional part is dropped For positive numbers, that's like using floor For negative numbers, that's like using ceiling The right way to do rounding is to call Math.round() double x = 2.6; int a = (int)math.round(x); // rounds

Return type Name Job double sin( double theta ) Find the sine of angle theta double cos( double theta ) Find the cosine of angle theta double tan( double theta ) Find the tangent of angle theta double exp( double a ) Raise e to the power of a (e a ) double log( double a ) Find the natural log of a double pow( double a, double b ) Raise a to the power of b (a b ) long round( double a ) Round a to the nearest integer double random() Create a random number in [0, 1) double sqrt( double a ) Find the square root of a double todegrees( double radians ) Convert radians to degrees double toradians( double degrees ) Convert degrees to radians

! NOT Flips value of operand from true to false or vice versa && AND true if both operands are true OR true if either operand is true ^ XOR true if operands are different

In some circumstances, Java doesn't check the whole expression: (true (some complicated expression)) Ignores everything after and gives back true (false && (some complicated expression)) Ignores everything after && and gives back false

char values can be treated like an int int number; number = 'a'; // number contains 97 It can be more useful to get the offset from a starting point char letter = 'r'; int number; number = letter 'a' + 1; //number is 18

Remember that we use single quotes to designate a char literal: 'z' What if you want to use the apostrophe character ( ' )? apostrophe: '\'' What if you want to use characters that can't be printed, like tab or newline? tab: newline: '\t' '\n' The backslash is a message that a special command called an escape sequence is coming These can be used in String literals as well: "\t\t\t\nthey said, \"Wow!\""

The only operator that we will use directly with Strings is the + (concatenation) operator This operator creates a new String that is the concatenation of the two source Strings Concatenation can be used to insert the values of other types into Strings as well String word; word = "tick" + "tock"; // word is "ticktock"

equals() Tests two Strings to see if they are the same compareto() Returns a negative number if the first String comes earlier in the alphabet, a positive number if the first String comes later in the alphabet, and 0 if they are the same length() Returns the length of the String charat() Returns the character at a particular index inside the String substring() Returns a new String made up of the characters that start at the first index and go up to but do not include the second index

Each primitive data type in Java has a wrapper class Integer Allows String representations of integer values to be converted into ints Double Allows String representations of floating point values to be converted into doubles Character Provides methods to test if a char value is a digit, is a letter, is lower case, is upper case Provides methods to change a char value to upper case or lower case

Making choices with if statements Basics Having if bodies with more than one line Using else blocks Nesting if statements Using switch statements

The if part Any boolean expression if( condition ) statement; Any single executable statement

if( condition ) statement1; else statement2; Two different outcomes

if( condition ) { statement1; A whole bunch of statements statement2; statementn; }

if( condition1 ) { } statement1; if( condition2 ) { if( condition3 ) statement2; }

The most common condition you will find in an if is a comparison between two primitive types In Java, that comparison can be: ==!= < <= > >= equals does not equal less than less than or equal to greater than greater than or equal to

switch( data ) { case value1: statements 1; case value2: statements 2; case valuen: statements n; default: default statements; }

int data = 3; switch( data ) { case 3: System.out.println("Three"); case 4: System.out.println("Four"); break; case 5: System.out.println("Five"); } The default is optional too Both "Three" and "Four" are printed The break is optional

1. The data that you are performing your switch on must be either an int, a char, or a String 2. The value for each case must be a literal 3. Execution will jump to the case that matches 4. If no case matches, it will go to default 5. If there is no default, it will skip the whole switch block 6. Execution will continue until it hits a break

Exam 1

Study for Exam 1 Keep working on Project 1, due tonight by 11:59! Never look at another student's code