Session 3. Basic Java Data Types, Control Structures. 8 primitive or built-in data types

Similar documents
1.00 Lecture 3. Main()

Announcements. 1. Forms to return today after class:

JAVA OPERATORS GENERAL

1.00 Lecture 4. Promotion

Prof. Navrati Saxena TA: Rochak Sachan

b. Suppose you enter input from the console, when you run the program. What is the output?

CS111: PROGRAMMING LANGUAGE II

Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following groups:

Java Basic Programming Constructs

Lecture Set 4: More About Methods and More About Operators

Operators in java Operator operands.

Object Oriented Programming Using C++ Mathematics & Computing IET, Katunayake

CS313D: ADVANCED PROGRAMMING LANGUAGE

Basic operators, Arithmetic, Relational, Bitwise, Logical, Assignment, Conditional operators. JAVA Standard Edition

Outline. Parts 1 to 3 introduce and sketch out the ideas of OOP. Part 5 deals with these ideas in closer detail.

Programming: Java. Chapter Objectives. Control Structures. Chapter 4: Control Structures I. Program Design Including Data Structures

Lecture Set 4: More About Methods and More About Operators

CT 229. Java Syntax 26/09/2006 CT229

CSC 1214: Object-Oriented Programming

Chapter 3 Selection Statements

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

CCHAPTER SELECTION STATEMENTS HAPTER 3. Objectives

The Arithmetic Operators. Unary Operators. Relational Operators. Examples of use of ++ and

Learning the Java Language. 2.1 Object-Oriented Programming

The Arithmetic Operators

Sequence structure. The computer executes java statements one after the other in the order in which they are written. Total = total +grade;

CT 229 Java Syntax Continued

Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following groups:

Object-oriented programming. and data-structures CS/ENGRD 2110 SUMMER 2018

Chapter 4: Control Structures I

Introduction. Following are the types of operators: Unary requires a single operand Binary requires two operands Ternary requires three operands

CS 112 Introduction to Computing II. Wayne Snyder Computer Science Department Boston University

3. Java - Language Constructs I

Basics of Java Programming

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

Chapter 6 Primitive types

COMP Primitive and Class Types. Yi Hong May 14, 2015

Operators and Expressions:

cis20.1 design and implementation of software applications I fall 2007 lecture # I.2 topics: introduction to java, part 1

4 Programming Fundamentals. Introduction to Programming 1 1

13 th Windsor Regional Secondary School Computer Programming Competition

Object-Oriented Programming. Topic 2: Fundamental Programming Structures in Java

CSE 201 JAVA PROGRAMMING I. Copyright 2016 by Smart Coding School

Basic computer skills such as using Windows, Internet Explorer, and Microsoft Word. and Java. Chapter 2 Primitive Data Types and Operations

CS 106 Introduction to Computer Science I

Operators. Java operators are classified into three categories:

CMPT 125: Lecture 4 Conditionals and Loops

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

Motivating Examples (1.1) Selections. Motivating Examples (1.2) Learning Outcomes. EECS1022: Programming for Mobile Computing Winter 2018

1007 Imperative Programming Part II

Operators and Expressions

bitwise inclusive OR Logical logical AND && logical OR Ternary ternary? : Assignment assignment = += -= *= /= %= &= ^= = <<= >>= >>>=

Java+- Language Reference Manual

Lecture 14. 'for' loops and Arrays

Control Flow. COMS W1007 Introduction to Computer Science. Christopher Conway 3 June 2003

Chapter 3: Operators, Expressions and Type Conversion

Building Java Programs

Tools : The Java Compiler. The Java Interpreter. The Java Debugger

CS 61B Data Structures and Programming Methodology. June David Sun

3. Java - Language Constructs I

Java Notes. 10th ICSE. Saravanan Ganesh

Object-Oriented Programming

Boolean Expressions. So, for example, here are the results of several simple Boolean expressions:

Building Java Programs

Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal

COSC 236 Section 101 Computer Science 1 -- Prof. Michael A. Soderstrand

Announcements. Lab Friday, 1-2:30 and 3-4:30 in Boot your laptop and start Forte, if you brought your laptop

Unit 3. Operators. School of Science and Technology INTRODUCTION

CS5000: Foundations of Programming. Mingon Kang, PhD Computer Science, Kennesaw State University

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

The Java language has a wide variety of modifiers, including the following:

JAVA Programming Fundamentals

Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following g roups:

Java is an objet-oriented programming language providing features that support

JAC444 - Lecture 1. Introduction to Java Programming Language Segment 4. Jordan Anastasiade Java Programming Language Course

Chapter 2 Primitive Data Types and Operations

Introduction to Programming Using Java (98-388)

Programming with Java

DM550 / DM857 Introduction to Programming. Peter Schneider-Kamp

Language Fundamentals Summary

PROGRAMMING FUNDAMENTALS

Selections. EECS1021: Object Oriented Programming: from Sensors to Actuators Winter 2019 CHEN-WEI WANG

Le L c e t c ur u e e 2 To T p o i p c i s c t o o b e b e co c v o e v r e ed e Variables Operators

DATA TYPES AND EXPRESSIONS

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

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

CT 229 Java Syntax Continued

Module 3 SELECTION STRUCTURES 2/15/19 CSE 1321 MODULE 3 1

Full file at

Eng. Mohammed S. Abdualal

Chapter 2 Primitive Data Types and Operations. Objectives

A variable is a name that represents a value. For

1.00 Lecture 19. Numerical Methods: Root Finding

Lesson 3: Accepting User Input and Using Different Methods for Output

Java Primer 1: Types, Classes and Operators

SOFTWARE DEVELOPMENT 1. Operators 2018W A. Ferscha (Institute of Pervasive Computing, JKU Linz)

CSE115 / CSE503 Introduction to Computer Science I Dr. Carl Alphonce 343 Davis Hall Office hours:

1.1 Your First Program

DM550 Introduction to Programming part 2. Jan Baumbach.

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

Transcription:

Session 3 Basic Java Data Types, Control Structures Java Data Types 8 primitive or built-in data types 4 integer types (byte, short, int, long) 2 floating point types (float, double) Boolean (boolean) Character (char) These are not objects

Java Data Types These are defined (almost) identically on every machine on which Java runs, unlike other programming languages Java is a strongly typed language: Every variable must have a declared type Type byte short int long float double char boolean Size (bits) 8 16 32 64 32 64 16 1 Java Data Types Range -128 to 127-32,768 to 32,767-2,147,483,648 to 2,147,483,647-9,223,372,036,854,775,808L to 9,223,372,036,854,775,807L +/- 3.4E+38F (6-7 significant digits) +/- 1.8E+308 (15 significant digits) ISO Unicode character set true or false

What data type would you use? What would you use to store: Speed of light Your grade in this course Your grade point average this term Number of refrigerators in a room Location of a point on a screen 2 65 $234.77 Half of $234.77 Bits per second transmitted by modem What data type would you use? What would you use to store: Speed of light double Your grade in this course char Your grade point average this term double/float Number of refrigerators in a room int Location of a point on a screen float/int 2 65 BigInteger $234.77 double/int Half of $234.77 double/int Bits per second transmitted by modem int/float

Using Java Data Types public class DataTypes { public static void main(string[] args) { boolean isreal=true; // Names are case sensitive, // start w/letter, have nos,_,$ byte d= 122; // Must be less than 127 short e= -29000; // Must be less than 32767 int f= 100000; // Must be less than 2.1 billion long g= 999999999999L; // Must put L on end float h= 234.99F; // Must be < 3E38; F on end double i= 55E100; char cvalue= '4'; // char '4' is not integer 4 // Strings are objects, not primitives. Example: String name= Claudius ; Arithmetic Operators Table in precedence order, highest precedence at top Operators ++ -- + (unary) - (unary) * / % + - Meaning increment decrement unary + ( x = +a) unary ( x = -a) multiplication division modulo addition subtraction Associativity Right to left Left to right Left to right

Using Arithmetic Operators public class DataType2 { public static void main(string[] args) { int j, k, m; int d= 122; j= d++; // j is 122 and d is 123 System.out.println("j= " + j); k= ++d; // k is 124 and d is 124 System.out.println("k= " + k); m= --d; // m is 123 and d is 123 System.out.println("m= " + m); m= k % j; // Remainder op for int types // k=124, j=122, so m= 2 System.out.println("m= " + m); j= 5; k= 3; m= j/k; // Integer division: m= 1 System.out.println("m= " + m); System.exit(0); Logical Operators Produce results of type boolean Comparisons use 8 operators: Equal Less than Greater than Logical and == < > && Not equal Less than or equal Greater than or equal Logical or!= <= >=

Logical Operators Example: double c= 0.0, b= 3.0; if (c!= 0.0 && b/c > 5.0) System.out.println( Boo ); // Never use == with float/double (this is bad // example) // Short circuit evaluation: quit after false // subexpression There are also bitwise operators we use later Assignment Operators Assignment is not the same as equality = is not the same as == Assignments are expressions: int x, y; x= y= 5; // Same as x = (y= 5); assoc from R to L Short cut forms exist: int x= 5, y= 3; x += y; // Same as x= x + y; Forms include +=, -=, *=, /=, &=, ^=, =, %=

Exercises Get the percent grad students in 1.00: int students= 240; int grads= 35; ; Represent 15*i correctly: int i= 100000000 + 100000000; ; Write expression to test if int x greater than double y and x less than y 2 and x not equal x 2 : ; if ( ; Increment int z by int a: ; ; // Declare x, y // Write logical expression // Declare a, z // Increment z by a Exercises Get the percent grad students in 1.00: int students= 240; int grads= 35; double pctgrad= grads/(double) students; Represent 15*i correctly: int i= 100000000 + 100000000; long j= 15L*i; Write expression to test if int x greater than double y and x less than y 2 and x not equal x 2 : int x; double y; if (x > y && x < y*y && x!= x*x) Increment int z by int a: int a=5, z=2; z += a;

Control Structures: Branch General form if (boolean) statement; if (boolean) statement1; else statement2; if (boolean1) statement1; else if (booleann) statementn; else statement; if (x == y) a = 20; if (x ==z) { b = 10; c = 20; if ( x == y ) a = 10; b = 20; else x = y; if ( x > 60) y = 20; else if (x < 30) { z += y; y = 25; else y= 40; { Example Control Structures: Branch A statement can be replaced by a block or set of statements enclosed in a pair of braces: { An else clause belongs to its nearest if statement. If you want to associate it with a farther if statement, put intervening if statements within { if (x > 3) { if (y < 7) z= 5; else // This else belongs to if (x > 3) z = y; Ternary comparison statement (boolean? expr_if_true : expr_if_false) boolean iscelsius= true; double tc= 10.0; double displaytemp= (iscelsius? tc : 1.8*tC + 32.0);

Input a, b and c Control example Solve ax 2 + bx + c= 0 discriminant = b*b - 4.0*a*c discriminant < 0 No discriminant 0 No Yes Yes Print Sorry, no real root root = - 0.5 * b / a root = (-b + discriminant) / 2*a root2 = (-b - discriminant) / 2*a Print root Print root Print root2 System.exit(0) Control example import javax.swing.*; // To support simple input public class Control { // Quadratic formula public static void main(string[] args) { final double TOL= 1E-15; // Constant (use final ) String input= JOptionPane.showInputDialog("Enter a"); double a= Double.parseDouble(input); input= JOptionPane.showInputDialog("Enter b"); double b= Double.parseDouble(input); input= JOptionPane.showInputDialog("Enter c"); double c= Double.parseDouble(input); double discriminant= b*b - 4.0*a*c; if ( discriminant < 0) System.out.println("Sorry, no real root"); else if (Math.abs(discriminant) <= TOL) { double root= -0.5 * b / a; System.out.println("Root is " + root); else { // Redefine root ; blocks have own scopes double root=(-b + Math.sqrt(discriminant))/ (2.0*a); double root2=(-b- Math.sqrt(discriminant))/ (2.0*a); System.out.println("Roots" + root +," + root2); System.exit(0);

Control example import javax.swing.*; // To support simple input public class Control { // Quadratic formula public static void main(string[] args) { final double TOL= 1E-15; // Constant(use final ) String input= JOptionPane.showInputDialog("Enter a"); double a= Double.parseDouble(input); input= JOptionPane.showInputDialog("Enter b"); double b= Double.parseDouble(input); input= JOptionPane.showInputDialog("Enter c"); double c= Double.parseDouble(input); Control example double discriminant= b*b - 4.0*a*c; if ( discriminant < 0) System.out.println("Sorry, no real root"); else if (Math.abs(discriminant) <= TOL) { double root= -0.5 * b / a; System.out.println("Root is " + root); else { // Redefine root ; blocks have own scopes double root=(-b + Math.sqrt(discriminant))/ (2.0*a); double root2=(-b- Math.sqrt(discriminant))/ (2.0*a); System.out.println("Roots" + root +," + root2); System.exit(0);

Control example The previous program has a deliberate, subtle bug Can you see it? Is it likely that you d find it by testing? Is it likely you d find it by using the debugger and reading the code? Fix the error by rearranging the order of the if-else clauses Control exercise 1 Write code in main() If demand d > supply s, raise price p by a(d-s) If demand == supply, do nothing If demand d < supply s, lower price p by b(d-s)

Control exercise 1 solution // Exercise 1. In Forte, declare, initialize all // variables. if (d > s) p += a*(d-s); else if (d < s) // Can omit if (d < s) p -= b*(d-s); // Can omit == clause since (d-s)=0 Control exercise 2 Write code in main() If weather today cloudy, tomorrow rain If weather today warm and cloudy, tomorrow is warmer If weather today sunny, tomorrow cloudy If weather today warm and sunny, tomorrow is colder and cloudy If weather today rain, tomorrow sunny (Use strings for cloudy, warm, etc.)

Control exercise solutions // Exercise 2. In Forte, declare, // initialize all variables. if (todaycloud.equals("sunny")) { tomorrowcloud= "Cloudy"; if (todaytemp.equals("warm")) tomorrowtemp= "Colder"; else if (todaycloud.equals("cloudy")) { tomorrowcloud= "Rain"; if (todaytemp.equals("warm")) tomorrowtemp= "Warmer"; else // Rain tomorrowcloud= "Sunny"; Control structure: Iteration while (boolean) statement; General form do statement; while (boolean); // Always executes stmt at least once for (start_expr; end_bool; cont_expr) statement; Example while (x > 0) { System.out.println( x= + x); x--; do { System.out.println( x= + x); x--; while (x > 0) for ( x= 20; x > 0; x--) System.out.println( x= + x);

For loops for (start_expr; end_bool; cont_expr) statement; for (j= 0; j < 20; j++) z += j; is equivalent to: start_expr; while (end_bool) { statement; cont_expr; j= 0; while (j < 20) { z += j; j++; Example Method-Computing ln(x) The natural logarithm of any number x is approximated by the formula ln(x) = (x-1) (x-1) 2 /2 + (x-1) 3 /3 -(x-1) 4 /4 + (x-1) 5 /5 +

Iteration Example 1: ln x import javax.swing.*; public class Iteration { public static void main(string[] args) { String input= JOptionPane.showInputDialog("Ent x (0-2)"); double x= Double.parseDouble(input); // Compute 20 terms of // ln x= (x-1) - (x-1)^2/2 + (x-1)^3/3 -... final int ITERATIONS= 20; // Fixed no of iterations double logx= 0.0; double x1= x-1; for (int i= 1; i <= ITERATIONS; i++) { if (i % 2 == 0) // i even logx -= Math.pow(x1, i)/i; else logx += Math.pow(x1, i)/i; System.out.println( ln x= " + logx); Iteration Example 2: ln x import javax.swing.*; // Same series as example 1 public class Iteration2 { public static void main(string[] args) { String input= JOptionPane.showInputDialog("Ent x (0-2)"); double x= Double.parseDouble(input); final double TOLERANCE= 0.00001; // Tol sets no of terms double logx= 0.0; double x1= x-1; int i= 1; double term= 0.0; // Define outside do { do { term= Math.pow(x1, i)/i; if (i % 2 == 0) // i even logx -= term; else logx += term; i++; while (Math.abs(term) > TOLERANCE); System.out.println( ln x= " + logx); System.out.println("Found in " + i + " iterations");