F28DA11 Command Line Java Survival. Phil Trinder and David H. Marwick

Similar documents
INPUT AND OUTPUT STREAMS

Stream Classes and File I/O

Creating a Simple, Multithreaded Chat System with Java

Files and input/output streams

What is an I/O Stream?

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

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

READING DATA FROM KEYBOARD USING DATAINPUTSTREAM, BUFFEREDREADER AND SCANNER

JAVA - FILES AND I/O

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

Lesson: All About Sockets

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

Programming in Java

Java CPD (I) Frans Coenen Department of Computer Science

Chapter 1 Java Program Design and Development

AP Computer Science Java Subset

Event-Driven Programming

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

Division of Informatics, University of Edinburgh

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

An Overview of Java. overview-1

CS 1302 Ch 19, Binary I/O

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

13 File Output and Input

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

D06 PROGRAMMING with JAVA

Contents. 9-1 Copyright (c) N. Afshartous

Object-Oriented Programming in Java

WRITING DATA TO A BINARY FILE

Java Programming Fundamentals

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

java Features Version April 19, 2013 by Thorsten Kracht

CS 106 Introduction to Computer Science I

Introduction to programming

CS506 Web Design and Development Solved Online Quiz No. 01

Introduction to Java

Java Network Programming. The java.net package contains the Socket class. This class speaks TCP (connection-oriented protocol).

Quick Introduction to Java

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

Input / Output Framework java.io Framework

Java Interview Questions and Answers

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

How To Write A Program In Java (Programming) On A Microsoft Macbook Or Ipad (For Pc) Or Ipa (For Mac) (For Microsoft) (Programmer) (Or Mac) Or Macbook (For

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

6.1. Example: A Tip Calculator 6-1

Building a Multi-Threaded Web Server

Topics. Introduction. Java History CS 146. Introduction to Programming and Algorithms Module 1. Module Objectives

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

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

Programming Languages CIS 443

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

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

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

Web Development in Java

How to Install Java onto your system

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

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

Free Java textbook available online. Introduction to the Java programming language. Compilation. A simple java program

1.00 Lecture 1. Course information Course staff (TA, instructor names on syllabus/faq): 2 instructors, 4 TAs, 2 Lab TAs, graders

Java Cheatsheet. Tim Coppieters Laure Philips Elisa Gonzalez Boix

Fundamentals of Java Programming

Crash Course in Java

Computing Concepts with Java Essentials

AVRO - SERIALIZATION

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

Chapter 2: Elements of Java

Mail User Agent Project

Java programming for C/C++ developers

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

Lecture 5: Java Fundamentals III

Free Java textbook available online. Introduction to the Java programming language. Compilation. A simple java program

Chapter 1 Fundamentals of Java Programming

Computer Programming I

Install Java Development Kit (JDK) 1.8

Assignment 4 Solutions

More on Objects and Classes

Advanced Network Programming Lab using Java. Angelos Stavrou

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

Building Java Programs

Programmation 2. Introduction à la programmation Java

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

Introduction to Programming

Socket Programming in Java

About the Tutorial. Audience. Prerequisites. Copyright & Disclaimer. AVRO Tutorial

Network Communication

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

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

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

Java Crash Course Part I

Report of the case study in Sistemi Distribuiti A simple Java RMI application

Today s Outline. Computer Communications. Java Communications uses Streams. Wrapping Streams. Stream Conventions 2/13/2016 CSE 132

Text file I/O and simple GUI dialogues

Java from a C perspective. Plan

Preet raj Core Java and Databases CS4PR. Time Allotted: 3 Hours. Final Exam: Total Possible Points 75

Variables, Constants, and Data Types

Programmation Orientée Objets. et langage Java

Third AP Edition. Object-Oriented Programming and Data Structures. Maria Litvin. Gary Litvin. Phillips Academy, Andover, Massachusetts

The Java Series. Java Essentials I What is Java? Basic Language Constructs. Java Essentials I. What is Java?. Basic Language Constructs Slide 1

Transcription:

F28DA11 Command Line Java Survival Guide Phil Trinder and David H. Marwick

Java with BlueJ BlueJ is a Java development environment explicitly for teaching introductory objectoriented programming Java has a steep learning curve BlueJ allows easy piecemeal testing of methods very useful for development Running a Java program means allowing it to control what is happening F28DA1: Data Structs & Algs 2

Java without BlueJ (App E) BlueJ hides functionality needed to run Java programs thus, easing the learning process To progress, you must learn some of this hidden functionality You must write code to create objects of your classes, and to create appropriate interaction between these objects F28DA1: Data Structs & Algs 3

Java Execution In BlueJ, to execute a program, typically you create an object of a control class. For example, in the address book programs (Ch 12) an AddressBookDemo object is created, and an appropriate method is invoked from that object This is eased by right-clicks within the BlueJ environment But what is actually happening? F28DA1: Data Structs & Algs 4

Java Execution An object is created by invoking a constructor of the class. The hidden code is: addressb1 = new AddressBookDemo(); Then we invoke the method showinterface() by right clicking on the object addressb1. The hidden code is addressb1.showinterface(); How can we execute this code if BlueJ does not exist? We have to tell the Java SDK where to start As no object can exist before the program starts execution, we must point to a class method in the control class F28DA1: Data Structs & Algs 5

Control Class A control class is used to start and control the operation of the program Typically, it is a small class containing class variables and methods It must include the method main with the signature: public static void main(string[] args); There will be no created object of this class What is a class method? class variable? F28DA1: Data Structs & Algs 6

AddressBookDemo The control class for the address book projects is AddressBookDemo The contents of this class is now public class AddressBookDemo{ private static AddressBook book; private static AddressBookTextInterface interaction; public static void main(string[] args); } //Note all variables and methods are static The program starts by executing main F28DA1: Data Structs & Algs 7

main() main contains the code to start the program, including creating any objects necessary for example: public static void main(string[] args) { ContactDetails[] sampledetails = { new ContactDetails("david", "08459 100000", "address 1"),... new ContactDetails("ruth", "08459 800000", "address 8"), }; book = new AddressBook(); for(contactdetails details : sampledetails) { book.adddetails(details); } interaction = new AddressBookTextInterface(book); interaction.run(); } Compare this with the existing code of the class AddressBookDemo using the text-based interface F28DA1: Data Structs & Algs 8

Executing using main This can all be achieved within BlueJ After compilation, execution is simply right clicking on AddressBookDemo and invoking the method main No object creation of AddressBookDemo is necessary Other objects are created within the program itself No parameters are necessary However, Java programs must be able to run without using the BlueJ environment F28DA1: Data Structs & Algs 9

Command line execution A (compiled) Java program can be run from a command line (in both Unix and Windows) by typing the command: java AddressBookDemo This causes the Java virtual machine to start executing the method main in the control class AddressBookDemo if main is not found, you get the error Exception in thread "main" java.lang.nosuchmethoderror: main i.e. you can run only the control class The parameter of main enables data to be passed in the command (Command Line Arguments) F28DA1: Data Structs & Algs 10

Compiling a Java program The Java compiler expects to find a text file of Java source code This can be created using any text editor Notepad, Emacs, vi, etc (or even BlueJ) Beware, do not use a word processor To compile using a command line: javac AddressBookDemo.java F28DA1: Data Structs & Algs 11

Java Files The Java source code must be stored in a text file with the name of the class and the extension.java The Java compiler creates code files with the extension.class one for each class Note that to compile, the.java extension is used to run, the.class extension is not used BlueJ has other files used only within BlueJ F28DA1: Data Structs & Algs 12

Summary The control class is a separate class which must have a class method main main must exist main must be public main must be static (class method) main must have a String array parameter To run, only main can be invoked F28DA1: Data Structs & Algs 13

Class diagram for address-book Note that the class diagram does not change main creates objects and invokes the run method in the interface class F28DA1: Data Structs & Algs 14

Simple I/O in Java In BlueJ, input and output are often done using the interface Stand alone Java programs must use the Java classes to achieve appropriate i/o We will now look at how to read data from the keyboard and display data on the screen F28DA1: Data Structs & Algs 15

Java Input/Output In Java, data is read from & written to streams A stream is an abstraction that produces or consumes data To access real data, it is attached to a physical device It always behaves in the same manner regardless of the physical device used: Keyboard Disc file Network socket Thus, stream classes (and methods) apply to all devices F28DA1: Data Structs & Algs 16

Types of Stream There are two types of stream Character streams read and write Unicode characters they are used for handling character data Byte streams read and write bytes (an 8-bit signed integer they are used for handling binary data As all input is byte-oriented, the character stream classes convert bytes to characters automatically F28DA1: Data Structs & Algs 17

byte streams Stream Hierarchy Object char streams InputStream OutputStream Reader Writer InputStream and OutputStream are the abstract superclasses for all byte I/O streams Reader and Writer are the abstract superclasses for all character I/O streams F28DA1: Data Structs & Algs 18

Standard Streams The standard streams are: the standard input stream, normally the keyboard the standard output stream, normally the screen the standard error stream, normally the screen The standard streams are based on the basic streams System.in an InputStream object System.out PrintStream objects, a System.err a subclass of OutputStream F28DA1: Data Structs & Algs 19

Example: Sum 10 numbers int sum, i, number; sum = 0; for (i = 0; i<10; i=i+1){ number = Integer.parseInt(System.in.readln()); sum = sum + number; } System.out.println("Sum = "+sum); This code would not work because System.in is an InputStream object and does not recognise line terminators It reads bytes only F28DA1: Data Structs & Algs 20

Character Streams - Reader Reader InputStreamReader BufferedReader InputStreamReader is the main class underlying the reading of character data BufferedReader is the class usually used for reading character data F28DA1: Data Structs & Algs 21

Reading Characters The main constructors of these classes are: public InputStreamReader(InputStream input); public BufferedReader(Reader input); Note that System.in is an InputStream object reading bytes InputStreamReader has methods which takes bytes and converts them to characters So a BufferedReader object normally builds on an InputStreamReader object F28DA1: Data Structs & Algs 22

Reading from System.in InputStreamReader keys = new InputStreamReader(System.in) BufferedReader keyboard = new BufferedReader(keys) OR BufferedReader keyboard = new BufferedReader(new InputStreamReader(System.in)) F28DA1: Data Structs & Algs 23

BufferedReader The reason for using a BufferedReader object is to use the method public String readline() throws IOException This reads a line of characters from the input stream (excluding the line terminator) A line is a structure within a character stream F28DA1: Data Structs & Algs 24

Example: Sum 10 numbers int sum, i, number; BufferedReader keyboard = new BufferedReader(new InputStreamReader(System.in)); sum = 0; for (i = 0; i<10; i=i+1){ number = Integer.parseInt (keyboard.readline().trim()); sum = sum + number; } System.out.println("Sum = "+sum); F28DA1: Data Structs & Algs 25

System.out System.out is a PrintStream object PrintStream is a subclass of OutputStream, a byte stream PrintStream permits output of characters The statement System.out.println("Sum = "+sum); causes sum to be converted to a String and the whole parameter is output to the screen on one line F28DA1: Data Structs & Algs 26

Writer Writer PrintWriter The main constructors are: public PrintWriter(OutputStream output, boolean flush); public PrintWriter(Writer output, boolean flush); F28DA1: Data Structs & Algs 27

PrintWriter Methods println()buffers and displays the parameter followed by a new line print() buffers without a new line (and so, does not display) flush() causes the buffer to be flushed (and so, displayed) the second parameter in the constructor specifies if the stream is flushed after println F28DA1: Data Structs & Algs 28

Output Note that System.out is an OutputStream object writing bytes So a PrintWriter object can be connected to System.out (using the first constructor on slide 32) PrintWriter screen = new PrintWriter(System.out, true); Note that the PrintWriter methods can also be used with System.out F28DA1: Data Structs & Algs 29

Output We can invoke the methods of this stream to display our output - for example screen.print("enter an integer: "); screen.flush(); Output values are buffered prior to output In order to display the data, the buffer must be flushed a new line also flushes the buffer F28DA1: Data Structs & Algs 30

Example with keyboard & screen public static void main(string[] args) throws IOException{ int sum, i, number; BufferedReader keyboard = new BufferedReader(new InputStreamReader(System.in)); PrintWriter screen = new PrintWriter(System.out, true); sum = 0; } for (i = 0; i<10; i=i+1){ screen.print("enter an integer: "); screen.flush(); number = Integer.parseInt(keyboard.readLine().trim()); sum = sum + number; } screen.println("sum = "+sum); F28DA1: Data Structs & Algs 31

Wrapper Classes Wrapper classes provide an object wrapper around primitive data types They are used to provide methods to convert from a String to a primitive type Strings that do not represent a value of a primitive type throw an exception F28DA1: Data Structs & Algs 32

Wrapper Classes (cont.) two Integer methods widely used are: public static int parseint(string s) throws NumberFormatException; public int intvalue(); parseint is a method which does not operate on an Integer object a class method n = Integer.parseInt(keyboard.readLine().trim()); intvalue does operate on an Integer object an instance method n = new Integer(keyboard.readLine().trim()).intValue(); F28DA1: Data Structs & Algs 33

Wrapper Classes (cont.) Integer also has two public class constants MAX_VALUE and MIN_VALUE, which give the range of ints there are similar wrapper classes for Double, Long, Float, Short, and Byte, e.g. public static double parsedouble(string s) throws NumberFormatException; public double doublevalue(); F28DA1: Data Structs & Algs 34

Useful String methods String methods can be used to manipulate the input string e.g. trim()removes all leading and trailing white space in a String object. Thus, keyboard.readline().trim() returns a trimmed String object To access a single char value: char ch = keyboard.readline(). charat(0); which returns the character at position 0 (left-most) of the trimmed String objecttrim(). F28DA1: Data Structs & Algs 35

Summary main method: public static void main(string[] args); Compile: javac myprog.java Run: java myprog Java I/O: Streams, standard streams like System.in Reading from streams, e.g. keyboard Writing to streams, e.g. screen 2008-09 F28DA1: Data Struct & Algs 36