Chapter 2 Input / Output Variables Operators

Similar documents
INPUT AND OUTPUT STREAMS

Chapter 2: Elements of Java

Creating a Simple, Multithreaded Chat System with Java

public static void main(string[] args) { System.out.println("hello, world"); } }

Chulalongkorn University International School of Engineering Department of Computer Engineering Computer Programming Lab.

READING DATA FROM KEYBOARD USING DATAINPUTSTREAM, BUFFEREDREADER AND SCANNER

Handout 1. Introduction to Java programming language. Java primitive types and operations. Reading keyboard Input using class Scanner.

Explain the relationship between a class and an object. Which is general and which is specific?

First Java Programs. V. Paúl Pauca. CSC 111D Fall, Department of Computer Science Wake Forest University. Introduction to Computer Science

Introduction to Java Applications Pearson Education, Inc. All rights reserved.

Lesson: All About Sockets

java.util.scanner Here are some of the many features of Scanner objects. Some Features of java.util.scanner

CS 1302 Ch 19, Binary I/O

JAVA - FILES AND I/O

Event-Driven Programming

CS 106 Introduction to Computer Science I

Crash Course in Java

Introduction to Java

Name: Class: Date: 9. The compiler ignores all comments they are there strictly for the convenience of anyone reading the program.

Chapter 1 Java Program Design and Development

Introduction to Java. CS 3: Computer Programming in Java

AP Computer Science Java Subset

1) Which of the following is a constant, according to Java naming conventions? a. PI b. Test c. x d. radius

Scanner. It takes input and splits it into a sequence of tokens. A token is a group of characters which form some unit.

Object-Oriented Programming in Java

Java Interview Questions and Answers

13 File Output and Input

Java Basics: Data Types, Variables, and Loops

Chapter 2 Introduction to Java programming

Java Programming Fundamentals

File class in Java. Scanner reminder. Files 10/19/2012. File Input and Output (Savitch, Chapter 10)

Variables, Constants, and Data Types

CSE 1223: Introduction to Computer Programming in Java Chapter 7 File I/O

Java Crash Course Part I

Stream Classes and File I/O

Object Oriented Software Design

CS 141: Introduction to (Java) Programming: Exam 1 Jenny Orr Willamette University Fall 2013

JAVA - QUICK GUIDE. Java SE is freely available from the link Download Java. So you download a version based on your operating system.

Chapter 20 Streams and Binary Input/Output. Big Java Early Objects by Cay Horstmann Copyright 2014 by John Wiley & Sons. All rights reserved.

Topics. Parts of a Java Program. Topics (2) CS 146. Introduction To Computers And Java Chapter Objectives To understand:

The Java I/O System. Binary I/O streams (ascii, 8 bits) The decorator design pattern Character I/O streams (Unicode, 16 bits)

Object Oriented Software Design

MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question.

Lecture 5: Java Fundamentals III

D06 PROGRAMMING with JAVA

J a v a Quiz (Unit 3, Test 0 Practice)

WRITING DATA TO A BINARY FILE

Chapter 3. Input and output. 3.1 The System class

Using Files as Input/Output in Java 5.0 Applications

Chapter 2 Elementary Programming

Files and input/output streams

Pemrograman Dasar. Basic Elements Of Java

Bachelors of Computer Application Programming Principle & Algorithm (BCA-S102T)

What is an I/O Stream?

Building Java Programs

CS1020 Data Structures and Algorithms I Lecture Note #1. Introduction to Java

Programming Languages CIS 443

JDK 1.5 Updates for Introduction to Java Programming with SUN ONE Studio 4

UIL Computer Science for Dummies by Jake Warren and works from Mr. Fleming

Chapter 10. A stream is an object that enables the flow of data between a program and some I/O device or file. File I/O

CS 111 Classes I 1. Software Organization View to this point:

An Overview of Java. overview-1

Programming and Data Structures with Java and JUnit. Rick Mercer

Simple C++ Programs. Engineering Problem Solving with C++, Etter/Ingber. Dev-C++ Dev-C++ Windows Friendly Exit. The C++ Programming Language

Java CPD (I) Frans Coenen Department of Computer Science

CS506 Web Design and Development Solved Online Quiz No. 01

CSE 1223: Introduction to Computer Programming in Java Chapter 2 Java Fundamentals

Mail User Agent Project

Building Java Programs

Division of Informatics, University of Edinburgh

Conditionals (with solutions)

Chapter One Introduction to Programming

java Features Version April 19, 2013 by Thorsten Kracht

1 of 1 24/05/ :23 AM

C++ Language Tutorial

Part I. Multiple Choice Questions (2 points each):

Object-Oriented Design Lecture 4 CSU 370 Fall 2007 (Pucella) Tuesday, Sep 18, 2007

Introduction to Java. Module 12: Networking (Java Sockets) Prepared by Costantinos Costa for EPL 233. ΕΠΛ233 Αντικειμενοστρεφής Προγραμματισμός 1

Moving from CS 61A Scheme to CS 61B Java

Number Representation

Question1-part2 What undesirable consequences might there be in having too long a DNS cache entry lifetime?

Handout 3 cs180 - Programming Fundamentals Spring 15 Page 1 of 6. Handout 3. Strings and String Class. Input/Output with JOptionPane.

Java Cheatsheet. Tim Coppieters Laure Philips Elisa Gonzalez Boix

Building a Multi-Threaded Web Server

The C Programming Language course syllabus associate level

Basic Java Constructs and Data Types Nuts and Bolts. Looking into Specific Differences and Enhancements in Java compared to C

Classes and Objects in Java Constructors. In creating objects of the type Fraction, we have used statements similar to the following:

Readings and References. Topic #10: Java Input / Output. "Streams" are the basic I/O objects. Input & Output. Streams. The stream model A-1.

Keywords are identifiers having predefined meanings in C programming language. The list of keywords used in standard C are : unsigned void

Masters programmes in Computer Science and Information Systems. Object-Oriented Design and Programming. Sample module entry test xxth December 2013

Sources: On the Web: Slides will be available on:

Lecture J - Exceptions

File I/O - Chapter 10. Many Stream Classes. Text Files vs Binary Files

Simple Java I/O. Streams

CS 121 Intro to Programming:Java - Lecture 11 Announcements

COSC Introduction to Computer Science I Section A, Summer Question Out of Mark A Total 16. B-1 7 B-2 4 B-3 4 B-4 4 B Total 19

Primitive data types in Java

Learning Outcomes. Networking. Sockets. TCP/IP Networks. Hostnames and DNS TCP/IP

Building Java Programs

Topic 11 Scanner object, conditional execution

Transcription:

Chapter 2 Input / Output Variables Operators Sample program Involving Input/Output write a program to: read a string from user a prompt should be used echo it on screen. Input a line of text: my name is Joe Bloggs Your input was: my name is Joe Bloggs 1

import java.io.*; public class Echo { public static void main (String[] args) throws IOException {// must include this, more later // create a text input stream BufferedReader stdin = new BufferedReader (new InputStreamReader (System.in)); String message; System.out.println("Input a line of text"); message = stdin.readline(); System.out.println("Your input was: " + message); 3 Predefined Objects for Input/Output System.out System.err PrintStream PrintStream Input a line Error in Input System.out.println("Input a line"); System.error.println( Error in Input"); InputStream System.in String message = System.in.readln();? No Such method! 2

InputStream class provides methods for reading bytes. Java uses Unicode encoding (which allows most world languages to be handled) uses 2 bytes per character. To read characters from System.in we need to chain a InputStreamReader object as in: InputStreamReader reader = new InputStreamReader(System.in); char ch = reader.read(); However to read a line at a time we have to chain it to a BufferedReader object as in: BufferedReader console = new BufferedReader( new InputStreamReader(System.in)); String message = console.readline(); Chaining the objects console BufferedReader in String readline() InputStreamReader in char readline() System.in InputStream byte readline() 3

Error Handling Reading java docs for the BufferedReader method readline()... public String readline() throws IOException This method threatens to throw an exception if any errors encountered while reading. When a method (within a class throws) an exception we can either Catch the exception and deal with it Pass it on by adding the phrase such as throws IOException as in class Echo { public static void main (String[] args) throws IOException { Write a program to add two numbers where are the numbers coming from? Are they whole numbers? decimal part allowed? where should the output go to? Input the first integer number: 5 Input the second integer number: 7 The sum is: 12 4

import java.io.*; public class AddingInts { public static void main (String[] args) throws IOException { BufferedReader stdin = new BufferedReader (new InputStreamReader (System.in)); String string1, string2; int num1, num2, sum; System.out.println ("Input an integer number"); string1 = stdin.readline(); num1 = Integer.parseInt (string1); System.out.println ("Input another integer number"); string2 = stdin.readline(); num2 = Integer.parseInt (string2); sum = num1 + num2; System.out.print("The sum is: " + sum); System.out.println(); So, what s new? To store whole numbers use integer variables as in: int num1, num2, sum; To add the values stored in num1 and num2 and to store it in sum use an assignment statement as in: num1 12 num2 30 sum sum = num1 + num2; The use of + with a String and an int an in: System.out.println("The sum is: " + sum); 5

How did we read an integer? Create and chain the BufferedReader object to System.in BufferedReader stdin = new BufferedReader (new InputStreamReader (System.in)); Read and store the user input in a String object String string1; string1 = stdin.readline(); Be prepared to handle the exception thrown by readline() public static void main (String[] args) throws IOException { To convert a String to integer use Integer.parseInt(.) as in num1 = Integer.parseInt (string1); Too tedious. Can we delegate this job to another class? ConsoleReader class facilitates input This user-created class is used in the book to facilitate input. First create a ConsoleReader object associated System.in ConsoleReader console = new ConsoleReader(System.in); Subsequently to read an integer use: int num1 = console.readint(); Reading strings and doubles are just as easy! String line = console.readline(); double d = console.readdouble(); console ConsoleReader int readint() double readdouble() String readline() 6

1 st program rewritten using ConsoleReader import java.io.*; public class Echo { public static void main (String[] args) { ConsoleReader console=new ConsoleReader(System.in); System.out.println("Input a line of text"); String message = console.readline(); System.out.println("Your input was: " + message); The ConsoleReader class must be in the same directory No need to chain No need to handle exceptions All these details are handled by class itself. console ConsoleReader int readint() double readdouble() String readline() 2 nd program rewritten using ConsoleReader import java.io.*; public class AddingInts { public static void main (String[] args) { ConsoleReader console=new ConsoleReader(System.in); int num1, num2, sum; System.out.println ("Input an integer number"); num1 = console.readint(); System.out.println ("Input another integer number"); num2 = console.readint(); sum = num1 + num2; System.out.println("The sum is: " + sum); No Chaining No exception handling No Strings required No conversion to ints required All details handled by class 7

Quick look at ConsoleReader class import java.io.*; public class ConsoleReader { public ConsoleReader(InputStream instream) { reader = new BufferedReader(new InputStreamReader(inStream)); private BufferedReader reader; public String readline() { String inputline = ""; try { inputline = reader.readline(); catch(ioexception e) { System.out.println(e); System.exit(1); return inputline; Constructor: initializes instance variable Only instance variable a reference to BefferedReader This method catches and handles any exceptions thrown in the try block public int readint() { String inputstring = readline(); int n = Integer.parseInt(inputString); return n; public double readdouble() { String inputstring = readline(); double n = Double.parseDouble(inputString); return n; Conversion to the appropriate type is done here. 8

Coding Style Class Names start with a capital letter If there are several words start each word with uppercase letter Echo, AddingInts, HelloWorld For variables start with a lowercase letter int anintegercolor; String employeename; Variables and Constants How do we instruct the compiler we need a variable (declare)? int num1; double rate; // reserves 4 bytes // reserves 8 bytes var_type varname; // general format Can we initialize at declaration? int num1 = 100l; double rate = 12.56 * 2; // general format var_type varname = expression; num1 rate num1 1001 rate 25.12 9

Variables and Constants What if I want the value to remain fixed? final int MAX_STUDENTS = 100; final int TAX_BRACKET = 30000; The keyword final has different meanings when applied to different things such as classes and methods. Quiz: Which of the following are valid statements? (a) final double PI = 3.14; (b) final PI; (c) final double PI = 3.1; PI = 3.14; PI = 3.14; Use all uppercase letters for constants Primitives and Objects Primitives such as ints and doubles are created and manipulated directly using their names. (Though compiler uses their addresses it does not concern us) int x = 10; x = x + 2; x 10 12 Objects have no names and are manipulated indirectly using an object reference. Rectangle rect = new Rectangle(10,5,40,50); rect.translate(20,40); rect Rectangle x=10 30 y = 5 45 w=40 h =50 translate() 10

Primitive Data Types Primitives in Java are byte, short, int, float, double, char and boolean. The first 4 are numeric types. Some problems require us to handle whole numbers while others require floating point numbers (with decimal part). What kind of variable would you use for: day, month, year? Temperature, weight(kg)? Integers and Floating Point Integer numbers (using byte, short and int) are stored using exact representation Floating point numbers are stored separately using the mantissa and exponent.as the number of significant digits that can be stored is limited they cannot be represented exactly. Hence Floating point representations are only approximations. 27.56 = 2.756 * 10 1 mantissa = 2756 exponent = 1 Most high-level languages don t specify the sizes of their data types - impediment for portability. Java specifies the sizes precisely (independent of platform) 11

Java Numeric Types Type Size Minimum Maximum Byte 8 bits 128 127 Short 16 bits 32,768 32,767 Int 32 bits 2,147,483,648 2,147,483,647 Long 64 bits 9,223,372,036,854,775,808 9,223,372,036,854,775,807 Float 32 bits App. 3.4E+38 App. +3.4E+38 Double 64 bits App. 1.7E+308 App. +1.7E+308 Typically use int for integers and double for floating point For large integers use long For small integers (day,month,year) you may use byte if memory is a constraint Data Types char and boolean Most languages such as C, Pascal use 1 byte for char (8 bits) allowing only 256 distinct characters to be stored. Java uses 2 bytes (Unicode) for characters allowing asian languages to be stored (up to 65536 values) But most Operating Systems use 1 byte character - hence we have to convert them using classes such as InputStreamReader. char input = q ; char ch = \n ; // \n == new line \t == tab boolean is used for storing true / false values boolean stop = false; 12

Strings String name = new String( Charles ); is equivalent to: (strings are special) String name = Charles ; What if I write the statement below next? String name = Charles Theva ; A new String object will be created and it s address will be assigned to name. The old String object (at address 1000) will be marked for garbage collection. Once a String object is created it cannot be changed (immutable object) in any way! name 1000 name 2000 1000 String Charles 1000 String Charles String Charles Theva 2000 What will be the output? import java.awt.rectangle; public class HelloRectangle { public static void main(string[] args){ Rectangle rect1 = new Rectangle(10,5,20,30); Rectangle rect2 = rect1; rect1.translate(20,30); // shifting rect2.translate(10,20); System.out.println(rect1); Output from the program rect1 8000 rect2 8000 Rectangle Object (initial state) Rectangle x=10, y=5, width=20, height=30 java.awt.rectangle[x =, y =, width = 20, height = 30] 13

String Operations String myname = "George"; the snapshot of memory is 0 1 2 3 4 5 G e O r g e Note that the first index is 0, not 1. Once a String object is created we can use its methods, such as myname.charat(2); // returns o myname.indexof( e ); // returns 1, it is the first e Comparing Strings the strings are compared character by character, until one character in s1 is less than its corresponding character in s2, then s1.compareto (s2) < 0 is true if s1 is shorter than s2, and the characters in s1 are identical to the corresponding characters in s2, then s1.compareto (s2) < 0 is true Examples: "George".compareTo ("George") == 0 is true "Georg".compareTo ("George") < 0 is true "George".compareTo ("Georg") > 0 is true "GEORGE".compareTo ("George") < 0 is true " pam".compareto ("pam") < 0 is true 14

Operators Arithmetic Operators + - * / % What will be the output? int x = 10; x = x + 5; // short form x += 5; (assignment operator) x = x / 4; // short form x /= 4; x = x % 2; // short form x %= 2; System.out.println( Current value of x is +x); Casting What will be the output? double ratio1, ratio2, ratio3; int x = 10; int y = 20; ratio1 = x/y; ratio2 = (double) (x / y); ratio3 = (double) x / y; System.out.println( ratio1 = + ratio1 ); System.out.println( ratio2 = + ratio2 ); System.out.println( ratio3 = + ratio3 ); 15

Relational and Logical Operators The relational operators <, <=, >, >= have the natural meaning yielding a boolean value(true/false). To further manipulate these values Java provides the logical operators && (AND), (OR), ^ (XOR), and! (NOT). The values of these operations are given by the truth tables shown below. a b!a a && b a b a^b T T F T T F T F F F T T F T T F T T F F T F F F What will be the output? public class Ops { public static void main(string[] args) { int x = 10, y = 20, z = 15; boolean check1, check2, check3, check4; check1 = y > x; check2 = y > x && x > y; check3 = y > x x > y; check4 = y > x &&!(x > y); System.out.println("check1 = " +check1); System.out.println("check2 = " +check2); System.out.println("check3 = " +check3); System.out.println("check4 = " +check4); 16

Unary Operators (only one operand) unary minus -x oparators ++ and -- ( can be post or pre) What will be the output? public class Ops { public static void main(string[] args) { int a = 10,p,q,r,s; p = a++; q = ++a; r = --a; s = a--; System.out.println("p = " + p); System.out.println("q = " + q); System.out.println("r = " + r); System.out.println("s = " + s); System.out.println( a = " + a); Operator precedence ategory Operators Associativity perations on references. [] L to R nary ++ --! - (type) R to L Multiplicative * / % L to R dditive + - L to R hift (bitwise) << >> >>> L to R elational < <= > >= instanceof L to R quality ==!= L to R oolean (or bitwise) AND & L to R oolean (or bitwise) XOR ^ L to R oolean (or bitwise) OR L to R ogical AND && L to R ogical OR L to R onditional?: R to L ssignment = *= /= %= += -= R to L 17

What s wrong with this program? Correct it! public class Ops { public static void main(string[] args) { double a = 10.0; double b = 20.0; double aver = a + b / 2; System.out.println("average of a and b = " + aver); Errors in Chapter 2 Page 41: program (lower half) message = ConsoleReader.readline(); message = console.readline(); Page 42: program readdouble() method int n = Integer.parseInt(inputString); double n = Double.parseInt(inputString); (The throws clause in main() can be removed for both programs) 18