1 CS 177 Week 3 Recitation Slides Basic Math Operations, Booleans, and Character Operations.

Slides:



Advertisements
Similar presentations
Types, Variables and Operators Computer Engineering Department Java Course Asst. Prof. Dr. Ahmet Sayar Kocaeli University - Fall 2013.
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.
©2004 Brooks/Cole Chapter 2 Variables, Values and Operations.
Primitive Data Types and Operations. Introducing Programming with an Example public class ComputeArea { /** Main method */ public static void main(String[]
1 Fundamental Data types Overview l Primitive Data Types l Variable declaration l Arithmetical Operations l Expressions l Assignment statement l Increment.
Datalogi A 3: 26/9. Java Concepts chapter 4 Fundamental Data Types int (long and short) double (and float) boolean char String.
Numerical Data Recitation – 01/30/2009
Lab session 3 and 4 Topics to be covered Escape sequences Escape sequences Variables /identifiers Variables /identifiers Constants Constants assignment.
Computer Science A 2: 6/2. Course plan Introduction to programming Basic concepts of typical programming languages. Tools: compiler, editor, integrated.
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.
Java Primitives The Smallest Building Blocks of the Language (corresponds with Chapter 2)
Week 3 - Wednesday.  What did we talk about last time?  Math methods  Lab 2.
Chapter 2: Basic Elements of Java J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Second Edition.
Java Methods. Topics  Declaring fields vs. local variables  Primitive data types  Strings  Compound Assignment  Conversions from one value to another.
The string data type String. String (in general) A string is a sequence of characters enclosed between the double quotes "..." Example: Each character.
Chapter 2 Basic Elements of Java. Chapter Objectives Become familiar with the basic components of a Java program, including methods, special symbols,
Java Keywords  Reserved Words Part of the Java language Examples: public, static, void  Pre-defined Java Identifiers Defined in Java Libraries Examples:
Week 2 - Friday.  What did we talk about last time?  Using Scanner to get input  Basic math operations.
CIS 260: App Dev I. 2 Programs and Programming n Program  A sequence of steps designed to accomplish a task n Program design  A detailed _____ for implementing.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 2 Basic Elements of Java.
Types CS 21a: Introduction to Computing I Department of Information Systems and Computer Science Ateneo de Manila University (Chapter 4, Horstmann text)
Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. int: integers, no fractional part: 1, -4, 0 double : floating-point.
Programming for Beginners Martin Nelson Elizabeth FitzGerald Lecture 2: Variables & Data Types.
CS177 Week2: Recitation Primitive data types and Strings with code examples.
Characters and Strings. Characters  New primitive char  char letter; letter = ‘a’; char letter2 = ‘C’;  Because computers can only represent numbers,
FUNDAMENTALS 2 CHAPTER 2. OPERATORS  Operators are special symbols used for:  mathematical functions  assignment statements  logical comparisons 
Week 15 - Monday.  What did we talk about last time?  File I/O.
A Simple Java Program //This program prints Welcome to Java! public class Welcome { public static void main(String[] args) { public static void main(String[]
Coding Bat: Ends in ly Given a string of even length, return a string made of the middle two chars, so the string "string" yields "ri". The string.
School of Computer Science & Information Technology G6DICP - Lecture 4 Variables, data types & decision making.
VISUAL C++ PROGRAMMING: CONCEPTS AND PROJECTS Chapter 2A Reading, Processing and Displaying Data (Concepts)
1 More data types Character and String –Non-numeric variables –Examples: char orange; String something; –orange and something are variable names –Note.
“Great leaders are never satisfied with current levels of performance. They are restlessly driven by possibilities and potential achievements.” – Donna.
1.2 Built-in Types of Data Introduction to Programming in Java: An Interdisciplinary Approach · Robert Sedgewick and Kevin Wayne · Copyright © 2008 · December.
CSCI 51 Introduction to Computer Science Joshua Stough February 3, 2009.
CSM-Java Programming-I Spring,2005 Fundamental Data Types Lesson - 2.
CS 106 Introduction to Computer Science I 09 / 10 / 2007 Instructor: Michael Eckmann.
C OMMON M ISTAKES CSC Java Program Structure  String Methods.
A data type in a programming language is a set of data with values having predefined characteristics.data The language usually specifies:  the range.
Java Programming: From Problem Analysis to Program Design, Second Edition 1 Lecture 1 Objectives  Become familiar with the basic components of a Java.
Programming Principles Operators and Expressions.
Chapter 2: Data and Expressions. Variable Declaration In Java when you declare a variable, you must also declare the type of information it will hold.
1 Lecture # 2. * Introducing Programming with an Example * Identifiers, Variables, and Constants * Primitive Data Types * Byte, short, int, long, float,
Georgia Institute of Technology Introduction to Java, and DrJava part 1 Dr Usman Saeed Assistant Professor Faculty of Computing and Information Technology.
CS0007: Introduction to Computer Programming Primitive Data Types and Arithmetic Operations.
Java Keywords  Reserved Words Part of the Java language Examples: public, static, void  Pre-defined Java Identifiers Defined in Java Libraries Examples:
CSE 110: Programming Language I Matin Saad Abdullah UB 1222.
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.
Week 4 - Friday.  What did we talk about last time?  Examples  switch statements.
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.
Week 3 - Monday.  What did we talk about last time?  Using Scanner to get input  Basic math operations  Lab 2.
CompSci 230 S Programming Techniques
Week 3 - Wednesday CS 121.
PowerPoint Presentation Authors of Exposure Java
Multiple variables can be created in one declaration
Type Conversion, Constants, and the String Object
Java Programming: From Problem Analysis to Program Design, 4e
Week 3: Basic Operations
Escape Sequences What if we wanted to print the quote character?
CS 177 Week 3 Recitation Slides
Type Conversion, Constants, and the String Object
Chapter 2: Basic Elements of Java
Fundamentals 2.
Data Types, Concatenation, PEMDAS, Shortcuts, and Comments
elementary programming
Fundamental OOP Programming Structures in Java: Comments, Data Types, Variables, Assignments, Operators.
In this class, we will cover:
Just Enough Java 17-May-19.
Week 3 - Friday COMP 1600.
Presentation transcript:

1 CS 177 Week 3 Recitation Slides Basic Math Operations, Booleans, and Character Operations

2 Announcements Project 1 was posted last Friday. It is due on February, 4 th at 9pm TAs started consulting hours this week  Tue-Thu 6:00pm to 9:00 pm For the project, make sure to:  Properly indent your code In Dr. Java, select all (CTRL+A) and then press TAB  Comment the variables you use  YOU WILL LOSE POINTS IF THIS IS NOT DONE!

3 QUESTIONS???

4 Basic Operations Recap

Operations On Integers +, -, *, /  Addition, subtraction, multiplication and division  Note that division of integers drops the fractional part +=, -=, *=, /=  a += 4;  a = a + 4;  c *= 5;  c = c * 5; ++, --  a ++;  a = a + 1; %  Remainder of division  a = 10 % 3; // a contains 1 5  b -= 3;  b = b - 3;  d /= 2;  b = b / 2;  b --;  b = b - 1;

Question What are the ways we can write to increment variable a by 1?  a = a + 1;  a += 1;  a ++; 6

7 Basic Operations w/Integers Code Example 1 public class IntegerOperations { public static void main(String[] args) { int a; int b; a = ; // a contains 33 b = a / 11; // b contains 3 System.out.println("a = " + a); System.out.println("b = " + b); a -= 7; System.out.println("a = " + a); b = a / b; // Result = 8.66 but int type means 8 b++; // Increment b from 8 to 9 System.out.println("b = " + b); } Output a = 33 b = 3 a = 26 b = 9

8 Basic Operations On Doubles Same operations as integers But the fractional part is retained

9 Basic Operations w/Doubles Code Example 1 public class DoubleOperations { public static void main(String[] args) { double a; double b; double c; double d; a = 4.0 / 3.0; b = a - 1; c = b + b + b * 2; d = 9 / 4; d--; System.out.println("a = " + a); System.out.println("b = " + b); System.out.println("c = " + c); System.out.println("d = " + d); } Output a = b = c = d = 1.0 Question Variable d is a double or an integer?

10 Casting in Java int a = (int) 1.8; // convert double 1.8 into an int 1 Convert one data type to another loss of precision float  int, number is rounded down Let the Java compiler know that you are aware that you are going to lose some information, but you are ok with that.

11 Math Library in Java Java contains a Math class that includes a variety of math functions that can be used to perform other operations on integers and/or doubles The term “library” just means that it is a collection of predefined methods/functions that a programmer can leverage Brief example: double x = 16.0; double y; y = Math.sqrt(x); // y will be 4.0 after this line executes

12 Math Library in Java Return typeNameJob doublesin( double theta ) Find the sine of angle theta doublecos( double theta ) Find the cosine of angle theta doubletan( double theta ) Find the tangent of angle theta doubleexp( double a ) Raise e to the power of a (e a ) doublelog( double a ) Find the natural log of a doublepow( double a, double b ) Raise a to the power of b (a b ) longround( double a ) Round a to the nearest integer doublerandom() Create a random number in [0, 1) doublesqrt( double a ) Find the square root of a

13 Math Operations Code Example public class MathOperations { public static void main(String[] args) { double a = 25; double b = 4; double x = 2.0; double y = 6.731; double z = 0.5; a = Math.sqrt(a); b = Math.pow(b, 2); x = Math.pow(x, 5) / 8; y = Math.round(y); z = Math.cos(z); System.out.println("a is " + a); System.out.println("b is " + b); System.out.println("x is " + x); System.out.println("y is " + y); System.out.println("z is " + z); } Output a is 5.0 b is 16.0 x is 4.0 y is 7.0 z is Note Math.round(y); (int) (y + 0.5); These are the same.

14 Boolean Operations OperatorSymbolFunction NOT! true  false, false  true AND&& Outputs true only if both operands are true OR|| Outputs true if either or both operands are true XOR^ Outputs true if one but not both operands are true

15 Boolean Operations Code Example public class BooleanOperations { public static void main(String[] args) { boolean test1 = true; boolean test2 = false; boolean test3 = test1 && test2; boolean test4 = test1 || test2; boolean test5 = test1 ^ test2; boolean test6 = test1 && test1; boolean test7 = test1 ^ test1; System.out.println("NOT " + test1 + " is " + !test1); System.out.println("NOT " + test2 + " is " + !test2); System.out.println(test1 + " AND " + test2 + " is " + test3); System.out.println(test1 + " OR " + test2 + " is " + test4); System.out.println(test1 + " XOR " + test2 + " is " + test5); System.out.println(test1 + " AND " + test1 + " is " + test6); System.out.println(test1 + " XOR " + test1 + " is " + test7); } Output NOT true is false NOT false is true true AND false is false true OR false is true true XOR false is true true AND true is true true XOR true is false

16 Characters in Java A digit, a letter or a symbol Denoted by single quotes in Java  ‘T’, ‘2’ Represented by numbers in computer  Char ch = ‘T’; // ch contains integer 84 // ch contains character ‘T’ Escape sequences \  single quote ‘\’’  New line ‘\n’  Tab ‘\t’  Back slash ‘\\’ char number

17 Character Operations Characters are actually integers +, -, ++, --, +=, -= Operations  ASCII number change. Become another character.  char ch = ‘a’ + 2; // ch contains number 99 representing ‘c’  ch += 3; // ch contains number 102 representing ‘f’  int dis = ‘g’ – ‘c’; // dis contains 4, no cast required

18 Character Operations Code Example public class CharacterOperations { public static void main(String[] args) { char letter; int number; letter = ‘l'; // letter contains ‘l' letter++; // letter contains ‘m' System.out.println("letter = '" + letter + "'"); number = letter; // no cast required System.out.println("number = " + number); letter = ‘h'; number = letter - 'a' + 1; System.out.println("'" + letter + "' is the " + number + "th letter of the alphabet"); } Output letter = 'm' number = 109 'h' is the 8th letter of the alphabet

19 Strings in Java A list of characters Denoted by double quotes  String str = “Computer”; +, += operators : concatenation  String str1 = “Java is”;  String str2 = str1 + “ programming language.”;  str1 += “ a cup of coffee.”; Can concatenate variables of other types as text strings  int a = 1; int b = 3; int c = a + b; String str3 = a + “ + “ + b + “ = “ + c;

20 String Class The String class contains several methods that can be used to perform operations on a string. Method Name Return Type DescriptionUsage compareTo(String t)intCompares two stringsstring1.compareTo(string2); length()intGets length of stringstring1.length(); charAt(int i)charFinds ith characterstring1.charAt(3); equals(String t)BooleanAre two strings equal?string1.equals(string2); substring(int i, int j)StringFinds substring from ith character to character before jth one String1.substring(0, 2)

Methods in String Class String str = “Boiler Up!”; Comparison  int a = str.compareTo(“Purdue”); // a contains a negative number  boolean b = str.equals(“Purdue”); // b contains false length() gives number of characters in the string  int l = str.length();// l contains 10 21

Methods in String Class String str = “Boiler Up!”; charAt(int i) get the character at position i  char c = charAt(2); // index starts from 0, c contains ‘i’, not ‘o‘ substring(int i, int j) gives the substring from position i and to the position before j  String str2 = str.substring(0, 6);// str2 contains “Boiler”  String str3 = str.substring(7, str.length());// str3 contains “Up!” Boiler Up!

23 Strings Class Code Example public class StringOperations { public static void main(String[] args) { String word1; String word2; word1 = “chrome"; word2 = “home"; System.out.println(“Does " + word1 + " = " + word2 + "?"); System.out.println( word1.equals(word2) + "!"); System.out.println("The length of " + word2 + " is: " + word2.length() ); int position = 3; System.out.println("Position " + position + " in " + word2 + " is '" + word2.charAt(position) + "'"); word1 = "computers are cool"; word2 = word1.substring(3, 8); System.out.println(word2); } Output Is chrome the same as home? false! The length of home is: 4 Position 3 in home is 'e' puter

Question If we have String word1 = “Purdue”; String word2 = “Purdue”; This statement will return true or false? word1.equals(word2); What about this one? word1 == word2; 24

25 Wrapper Classes Each primitive data type in Java has a wrapper class Integer converts between int  String  String  int String str = “345”; int a = Integer.parseInt(str);  int  String int value = 890; String str = Integer.toString(value); Double is similar. double  String  String  double: double d = Double.parseDouble(“345.12”);  double  String : String str = Double.toString(3.14);

26 Wrapper Classes Character  gives information about a particular char  Remind from last week: boolean b = Character.isLowerCase(‘c’); b = Character.isUpperCase(‘c’); b = Character.isLetter(‘c’); b = Character.isDigit(‘c’);

27 Wrapper Classes Code Example 1 public class Wrappers { public static void main(String[] args) { String number1 = "666"; String number2 = "4.51"; int value1 = Integer.parseInt( number1 ); double value2 = Double.parseDouble( number2 ); System.out.println("The integer is " + value1); System.out.println("The double is " + value2); } } What would happen if the parseInt and parseDouble methods were not used? (i.e.: int value1 = number1;) Output The integer is 666 The double is 4.51

28 Wrapper Classes Code Example 2 public class Wrappers { public static void main(String[] args) { char c = 'U'; char d = '4'; System.out.println(c + " is:"); System.out.println("a letter:\t" + Character.isLetter(c)); System.out.println("a digit:\t" + Character.isDigit(c)); System.out.println("uppercase:\t" + Character.isUpperCase(c)); System.out.println("lowercase:\t" + Character.isLowerCase(c)); System.out.println(d + " is:"); System.out.println("a letter:\t" + Character.isLetter(d)); System.out.println("a digit:\t" + Character.isDigit(d)); System.out.println("uppercase:\t" + Character.isUpperCase(d)); System.out.println("uppercase:\t" + Character.isLowerCase(d)); } } Output U is: a letter:true a digit:false uppercase:true lowercase:false 4 is: a letter:false a digit:true uppercase:false

29 Final QUESTIONS???