Java in 21 minutes. Hello world. hello world. exceptions. basic data types. constructors. classes & objects I/O. program structure.

Similar documents
1993: renamed "Java"; use in a browser instead of a microwave : Sun sues Microsoft multiple times over Java

needs to be reliable, easy to change, retarget efficiency is secondary implemented as interpreter, with virtual machine

1993: renamed "Java"; use in a browser instead of a microwave : Sun sues Microsoft multiple times over Java

I/O in Java I/O streams vs. Reader/Writer. HW#3 due today Reading Assignment: Java tutorial on Basic I/O

1993: renamed "Java"; use in a browser instead of a microwave : Sun sues Microsoft multiple times over Java

Crash Course in Java. Why Java? Java notes for C++ programmers. Network Programming in Java is very different than in C/C++

COT 3530: Data Structures. Giri Narasimhan. ECS 389; Phone: x3748

File IO. Computer Science and Engineering College of Engineering The Ohio State University. Lecture 20

Programming Language Concepts: Lecture 2

Introduction Unit 4: Input, output and exceptions

Agenda & Reading. Python Vs Java. COMPSCI 230 S Software Construction

Getting Started in Java. Bill Pugh Dept. of Computer Science Univ. of Maryland, College Park

Input from Files. Buffered Reader

Byte and Character Streams. Reading and Writing Console input and output

Full file at

Introduction IS

09-1. CSE 143 Java GREAT IDEAS IN COMPUTER SCIENCE. Overview. Data Representation. Representation of Primitive Java Types. Input and Output.

Input, Output and Exceptions. COMS W1007 Introduction to Computer Science. Christopher Conway 24 June 2003

Programming Language Concepts: Lecture 2

Special error return Constructors do not have a return value What if method uses the full range of the return type?

Java Input/Output. 11 April 2013 OSU CSE 1

Exceptions and Working with Files

Lecture 11.1 I/O Streams

IT101. File Input and Output

F1 A Java program. Ch 1 in PPIJ. Introduction to the course. The computer and its workings The algorithm concept

HST 952. Computing for Biomedical Scientists Lecture 8

COMP 213. Advanced Object-oriented Programming. Lecture 19. Input/Output

1.00 Lecture 30. Sending information to a Java program

Exceptions vs. Errors Exceptions vs. RuntimeExceptions try...catch...finally throw and throws

Software Practice 1 - File I/O

Programming Languages and Techniques (CIS120)

Darshan Institute of Engineering & Technology for Diploma Studies

Getting started with Java

Any serious Java programmers should use the APIs to develop Java programs Best practices of using APIs

Lec 3. Compilers, Debugging, Hello World, and Variables

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

Internet Technology 2/7/2013

Each command-line argument is placed in the args array that is passed to the static main method as below :

PIC 20A Streams and I/O

Object-Oriented Programming Design. Topic : Streams and Files

CS1092: Tutorial Sheet: No 3 Exceptions and Files. Tutor s Guide

Classes Basic Overview

Object Oriented Software Design

Object Oriented Software Design

תוכנה 1 תרגול 8 קלט/פלט רובי בוים ומתי שמרת

Introduction to Programming Using Java (98-388)

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

CSC 1214: Object-Oriented Programming

Lab 5: Java IO 12:00 PM, Feb 21, 2018

Character Stream : It provides a convenient means for handling input and output of characters.

Today s plan Discuss the Lab 1 Show Lab 2 Review basic Java materials Java API Strings Java IO

Brief Summary of Java

Remedial Java - io 8/09/16. (remedial) Java. I/O. Anastasia Bezerianos 1

23 Error Handling What happens when a method is called? 23.1 What is Exception Handling? A.m() B.n() C.p()

ITI Introduction to Computing II

CSC Java Programming, Fall Java Data Types and Control Constructs

ITI Introduction to Computing II

Week 12. Streams and File I/O. Overview of Streams and File I/O Text File I/O

Today s plan Discuss the Bb quiz 1 Clarify Lab 1 Review basic Java materials Classes, Objects, Interfaces Strings Java IO. Understanding Board

Simple Java Input/Output

Lecture 14 Summary 3/9/2009. By the end of this lecture, you will be able to differentiate between errors, exceptions, and runtime exceptions.

Today. Book-keeping. File I/O. Subscribe to sipb-iap-java-students. Inner classes. Debugging tools

Java Intro 3. Java Intro 3. Class Libraries and the Java API. Outline

COMP 213. Advanced Object-oriented Programming. Lecture 20. Network Programming

CS 231 Data Structures and Algorithms Fall 2018

WOSO Source Code (Java)

1 Shyam sir JAVA Notes

CPSC 319. Week 2 Java Basics. Xiaoyang Liu & Sorting Algorithms

16-Dec-10. Consider the following method:

Object-Oriented Programming in the Java language

What is the purpose of exceptions and exception handling? Vocabulary: throw/raise and catch/handle Exception propagation Java checked and unchecked

CSPP : Introduction to Object-Oriented Programming

Introduction to Java

Objec&ves. Review. Standard Error Streams

CS193j, Stanford Handout #26. Files and Streams

Lecture Notes CPSC 224 (Spring 2012) Today... Java basics. S. Bowers 1 of 8

1. Download the JDK 6, from

CS 231 Data Structures and Algorithms, Fall 2016

Software 1 with Java. Recitation No. 7 (Java IO) May 29,

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

Chapter 1 Getting Started

Outline. Java Models for variables Types and type checking, type safety Interpretation vs. compilation. Reasoning about code. CSCI 2600 Spring

Overview CSE 143. Data Representation GREAT IDEAS IN COMPUTER SCIENCE. Representation of Primitive Java Types. CSE143 Au

Overview CSE 143. Data Representation GREAT IDEAS IN COMPUTER SCIENCE

Overview CSE 143. Data Representation GREAT IDEAS IN COMPUTER SCIENCE. Representation of Primitive Java Types. CSE143 Sp

A Third Look At Java. Chapter Seventeen Modern Programming Languages, 2nd ed. 1

Overview CSE 143. Input and Output. Streams. Other Possible Kinds of Stream Converters. Stream after Stream... CSE143 Wi

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

ITI Introduction to Computer Science II

Course Content. Objectives of Lecture 22 File Input/Output. Outline of Lecture 22. CMPUT 102: File Input/Output Dr. Osmar R.

Overview CSE 143. Data Representation GREAT IDEAS IN COMPUTER SCIENCE

Course information. Petr Hnětynka 2/2 Zk/Z

Exceptions and I/O: sections Introductory Programming. Errors in programs. Exceptions

Introductory Programming Exceptions and I/O: sections

Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal

Pace University. Fundamental Concepts of CS121 1

CISC 323 (Week 9) Design of a Weather Program & Java File I/O

CS 61B Discussion 5: Inheritance II Fall 2014

File Operations in Java. File handling in java enables to read data from and write data to files

Array. Prepared By - Rifat Shahriyar

Transcription:

Java in 21 minutes hello world basic data types classes & objects program structure constructors garbage collection I/O exceptions Strings Hello world import java.io.*; public class hello { public static void main(string[] args) { System.out.println("hello, world"); compiler creates hello.class javac hello.java execution starts at main in hello.class java hello filename has to match class name libraries in packages loaded with import java.lang is core of language System class contains stdin, stdout, etc. java.io is basic I/O package file system access, input & output streams,...

Basic data types public class fahr { public static void main(string[] args){ for (int fahr = 0; fahr < 300; fahr += 20) System.out.println(fahr + " " + 5.0 * (fahr - 32) / 9.0); basic types: boolean true / false byte 8 bit signed char 16 bit unsigned (Unicode character) int 32 bit signed short, long, float, double String is sort of built in "..." is a String holds chars, NOT bytes does NOT have a null terminator + is string concatenation operator System.out.println(s) is only for a single string formatted output is a total botch 2 versions of echo public class echo { public static void main(string[] args) { for (int i = 0; i < args.length; i++) if (i < args.length-1) System.out.print(args[i] + " "); else System.out.println(args[i]); public class echo1 { public static void main(string[] args) { String s = ""; for (int i = 0; i < args.length-1; i++) s += args[i] + " "; if (args.length > 0) s += args[args.length-1]; if (s!= "") System.out.println(s); arrays have a length field (a.length) subscripts are always checked Strings have a length() function (s.length() )

Classes, objects and all that data abstraction and protection mechanism originally from Simula 67, via C++ and others class thing { public part: methods: functions that define what operations can be done on this kind of object private part: functions and variables that implement the operation defines a new data type "thing" can declare variables and arrays of this type, pass to functions, return them, etc. object: an instance of a class variable method: a function defined within the class (and visible outside) private variables and functions are not accessible from outside the class not possible to determine HOW the operations are implemented, only WHAT they do Classes & objects in Java, everything is part of some object all classes are derived from class Object public class RE { String re; // regular expression int start, end; // of last match public RE(String r) {... // constructor public int match(string s) {... public int start() { return _start; int matchhere(string re, String text) {... // or matchhere(string re, int ri, String text, int ti) member functions are defined inside the class internal variables defined but shouldn't be public internal functions shouldn't be public (e.g., matchhere) all objects are created dynamically have to call new to construct an object RE re; // null: doesn't yet refer to an object re = new RE("abc*"); // now it does int m = re.match("abracadabra"); int start = re.start(); int end = re.end();

Constructors: making a new object public RE(String re) { this.re = re; RE r; r = new RE(s); "this" is the object being constructed or running the code can use multiple constructors with different arguments to construct in different ways: public RE() { /*??? */ Class variables & instance variables every object is an instance of some class created dynamically by calling new class variable: a variable declared static in class only one instance of it in the entire program exists even if the class is never instantiated the closest thing to a global variable in Java public class RE { static int num_res = 0; public RE(String re) { num_res++;... class methods most methods associated with an object instance if declared static, associated with class itself e.g., main()

Program structure typical structure is class RE { private variables public RE methods, including constructor(s) private functions public static void main(string[] args) { extract re for (i = 1; i < args.length; i++) fin = open up the file... grep(re, fin) static int grep(string regexp, FileReader fin) { RE re = new RE(regexp); for each line of fin if (re.match(line))... order doesn't matter Destruction & garbage collection interpreter keeps track of what objects are currently in use memory can be released when last use is gone release does not usually happen right away has to be garbage-collected garbage collection happens automatically separate low-priority thread manages garbage collection no control over when this happens can set object reference to null to encourage it Java has no destructor (unlike C++) can define a finalize() method for a class to reclaim other resources, close files, etc. no guarantee that a finalizer will ever be called garbage collection is a great idea but this is not a great design

I/O and file system access import java.io.* byte I/O InputStream and OutputStream character I/O (Reader, Writer) InputReader and OutputWriter InputStreamReader, OutputStreamWriter BufferedReader, BufferedWriter file access buffering exceptions in general, use character I/O classes Character I/O InputStreamReader reads Unicode chars OutputStreamWriter write Unicode chars use Buffered(Reader Writer) for speed because it has a readline method public class cp4 { public static void main(string[] args) { int b; try { BufferedReader bin = new BufferedReader( new InputStreamReader( new FileInputStream(args[0]))); BufferedWriter bout = new BufferedWriter( new OutputStreamWriter( new FileOutputStream(args[1]))); while ((b = bin.read()) > -1) bout.write(b); bin.close(); bout.close(); catch (IOException e) { System.err.println("IOException " + e);

Line at a time I/O public class cat3 { public static void main(string[] args) { BufferedReader in = new BufferedReader( new InputStreamReader(System.in)); BufferedWriter out = new BufferedWriter( new OutputStreamWriter(System.out)); try { String s; while ((s = in.readline())!= null) { out.write(s); out.newline(); out.flush(); // required!!! catch (Exception e) { System.err.println("IOException " + e); Exceptions C-style error handling ignore errors -- can't happen return a special value from functions, e.g., -1 from system calls like open() NULL from library functions like fopen() leads to complex logic error handling mixed with computation repeated code or goto's to share code limited set of possible return values extra info via errno and strerr: global data some functions return all possible values no possible error return value is available Exceptions are the Java solution (also in C++) exception indicates unusual condition or error occurs when program executes a throw statement control unconditionally transferred to catch block if no catch in current function, passes to calling method keeps passing up until caught ultimately caught by system at top level

try { catch { a method can catch exceptions public void foo() { try { // if anything here throws an IO exception // or a subclass, like FileNotFoundException catch (IOException e) { // this code will be executed // to deal with it or it can throw them, to be handled by caller a method must list exceptions it can throw exceptions can be thrown implicitly or explicitly public void foo() throws IOException { // if anything here throws an exception // foo will throw an exception // to be handled by its caller Why exceptions? reduced complexity if a method returns normally, it worked each statement in a try block knows that the previous statements worked, without explicit tests if the try exits normally, all the code in it worked error code grouped in a single place can't unconsciously ignore possibility of errors have to at least think about what exceptions can be thrown public static void main(string args[]) throws IOException { int b; while ((b = System.in.read()) >= 0) System.out.write(b);

String methods a String is sequence of Unicode chars immutable: each update makes a new String s += s2 makes a new s each time indexed from 0 to str.length()-1 useful String methods charat(pos) character at pos substring(start, len) substring for (i = 0; i < s.length(); i++) if (s.charat(i)!= s.substring(i, 1)) // can't happen String parsing String[] fld = str.split("\\s+"); StringTokenizer st = new StringTokenizer (str); while (st.hasmoretokens()) { String s = st.nexttoken();... "Real" example: regular expressions simple class to look like RE uses the Java 1.4 regex mechanism provides a better interface (or at least less clumsy) import java.util.regex.*; public class RE { Pattern p; Matcher m; public RE(String pat) { p = Pattern.compile(pat); public boolean match(string s) { m = p.matcher(s); return m.find(); public int start() { return m.start(); public int end() { return m.end();

Java vs. C and C++ no preprocessor import instead of #include constants use static final declaration C-like basic types, operators, expressions sizes, order of evaluation are specified byte, short, int, long: signed integers (no unsigned) char: unsigned 16-bit Unicode character boolean: true or false really object-oriented everything is part of some class objects all derived from Object class static member function applies to whole class references instead of pointers for objects null references, garbage collection, no destructors == is object identity, not content identity all arrays are dynamically allocated int[] a; a = new int[100]; strings are more or less built in C-like control flow, but labeled break and continue instead of goto exceptions: try { catch(exception) { threads for parallelism within a single process in language, not a library add-on