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



Similar documents
INPUT AND OUTPUT STREAMS

Java from a C perspective. Plan

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

JAVA - FILES AND I/O

Java Interview Questions and Answers

An Overview of Java. overview-1

WRITING DATA TO A BINARY FILE

Building a Multi-Threaded Web Server

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

Creating a Simple, Multithreaded Chat System with Java

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

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

Using Files as Input/Output in Java 5.0 Applications

Lesson: All About Sockets

Crash Course in Java

Quick Introduction to Java

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

Stream Classes and File I/O

Files and input/output streams

Java Cheatsheet. Tim Coppieters Laure Philips Elisa Gonzalez Boix

Introduction to Java

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

CS506 Web Design and Development Solved Online Quiz No. 01

java Features Version April 19, 2013 by Thorsten Kracht

The C Programming Language course syllabus associate level

1 of 1 24/05/ :23 AM

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

13 File Output and Input

Java Programming Fundamentals

Unit 6. Loop statements

C++ INTERVIEW QUESTIONS

What is an I/O Stream?

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

CS 121 Intro to Programming:Java - Lecture 11 Announcements

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

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

Event-Driven Programming

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

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

D06 PROGRAMMING with JAVA

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

Moving from CS 61A Scheme to CS 61B Java

Chapter 2 Introduction to Java programming

Lecture J - Exceptions

JAVA - EXCEPTIONS. An exception can occur for many different reasons, below given are some scenarios where exception occurs.

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

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

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

AP Computer Science Java Subset

CS 106 Introduction to Computer Science I

Java Crash Course Part I

CSC 551: Web Programming. Fall 2001

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

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

Input / Output Framework java.io Framework

Network/Socket Programming in Java. Rajkumar Buyya

Object-Oriented Programming in Java

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

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

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

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

Exception Handling. Overloaded methods Interfaces Inheritance hierarchies Constructors. OOP: Exception Handling 1

C++ Programming Language

Lecture 5: Java Fundamentals III

Sample CSE8A midterm Multiple Choice (circle one)

Debugging. Common Semantic Errors ESE112. Java Library. It is highly unlikely that you will write code that will work on the first go

Pemrograman Dasar. Basic Elements Of Java

Fundamentals of Java Programming

CS 1302 Ch 19, Binary I/O

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

Continuous Integration Part 2

Course Intro Instructor Intro Java Intro, Continued

Network Communication

Programming Languages CIS 443

I. INTRODUCTION. International Journal of Computer Science Trends and Technology (IJCST) Volume 3 Issue 2, Mar-Apr 2015

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

Programming in Java

Introduction to Java. CS 3: Computer Programming in Java

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

Eryq (Erik Dorfman) Zeegee Software Inc. A Crash Course in Java 1

D06 PROGRAMMING with JAVA

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

Semantic Analysis: Types and Type Checking

You are to simulate the process by making a record of the balls chosen, in the sequence in which they are chosen. Typical output for a run would be:

13 Classes & Objects with Constructors/Destructors

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

Chapter 1 Java Program Design and Development

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

COS 217: Introduction to Programming Systems

Introduction to Object-Oriented Programming

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

C++FA 5.1 PRACTICE MID-TERM EXAM

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

C++ Outline. cout << "Enter two integers: "; int x, y; cin >> x >> y; cout << "The sum is: " << x + y << \n ;

CSCI 253. Object Oriented Programming (OOP) Overview. George Blankenship 1. Object Oriented Design: Java Review OOP George Blankenship.

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,... 1

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() ) 2

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(); 3

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() 4

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 5

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); 6

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 7

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); 8

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(); 9

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 10