Quick Introduction to Java



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

AP Computer Science Java Subset

Introduction to Java

Java Programming Fundamentals

Fundamentals of Java Programming

Object-Oriented Programming in Java

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

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

Crash Course in Java

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

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

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

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

Computer Programming I

Introduction to Java Lecture Notes. Ryan Dougherty

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

An Overview of Java. overview-1

Chapter 2: Elements of Java

Moving from CS 61A Scheme to CS 61B Java

Java Interview Questions and Answers

Lecture 5: Java Fundamentals III

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

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

Basic Programming and PC Skills: Basic Programming and PC Skills:

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

The Sun Certified Associate for the Java Platform, Standard Edition, Exam Version 1.0

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

Pemrograman Dasar. Basic Elements Of Java

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

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

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

6.1. Example: A Tip Calculator 6-1

qwertyuiopasdfghjklzxcvbnmqwerty uiopasdfghjklzxcvbnmqwertyuiopasd fghjklzxcvbnmqwertyuiopasdfghjklzx cvbnmqwertyuiopasdfghjklzxcvbnmq

D06 PROGRAMMING with JAVA

CS 106 Introduction to Computer Science I

Chapter 2. println Versus print. Formatting Output withprintf. System.out.println for console output. console output. Console Input and Output

CS506 Web Design and Development Solved Online Quiz No. 01

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

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

Chapter 3. Input and output. 3.1 The System class

Java Application Developer Certificate Program Competencies

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 Design Lecture 4 CSU 370 Fall 2007 (Pucella) Tuesday, Sep 18, 2007

Java from a C perspective. Plan

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

Week 1: Review of Java Programming Basics

Variables, Constants, and Data Types

Programming Languages CIS 443

Files and input/output streams

Java CPD (I) Frans Coenen Department of Computer Science

WA2099 Introduction to Java using RAD 8.0 EVALUATION ONLY. Student Labs. Web Age Solutions Inc.

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

Object Oriented Software Design

Event-Driven Programming

13 File Output and Input

Syllabus for CS 134 Java Programming

Creating a Simple, Multithreaded Chat System with Java

Chapter 2 Introduction to Java programming

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

Programmation 2. Introduction à la programmation Java

CSC 551: Web Programming. Fall 2001

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

Using Files as Input/Output in Java 5.0 Applications

Introduction to Java. CS 3: Computer Programming in Java

Install Java Development Kit (JDK) 1.8

Chapter 1 Java Program Design and Development

Comp 248 Introduction to Programming

Java Crash Course Part I

1 of 1 24/05/ :23 AM

Java Cheatsheet. Tim Coppieters Laure Philips Elisa Gonzalez Boix

CS 1302 Ch 19, Binary I/O

CS106A, Stanford Handout #38. Strings and Chars

Habanero Extreme Scale Software Research Project

02 B The Java Virtual Machine

java Features Version April 19, 2013 by Thorsten Kracht

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

PROBLEM SOLVING SEVENTH EDITION WALTER SAVITCH UNIVERSITY OF CALIFORNIA, SAN DIEGO CONTRIBUTOR KENRICK MOCK UNIVERSITY OF ALASKA, ANCHORAGE PEARSON

Informatica e Sistemi in Tempo Reale

#820 Computer Programming 1A

Building a Multi-Threaded Web Server

Chapter 7D The Java Virtual Machine

Semantic Analysis: Types and Type Checking

Computer Programming I

Lecture 1 Introduction to Java

Programmierpraktikum

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

Example of a Java program

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

core. Volume I - Fundamentals Seventh Edition Sun Microsystems Press A Prentice Hall Title ULB Darmstadt

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

Object Oriented Software Design

No no-argument constructor. No default constructor found

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

Java (12 Weeks) Introduction to Java Programming Language

Java Programming Language

Getting Started with the Internet Communications Engine

Android Application Development Course Program

We will learn the Python programming language. Why? Because it is easy to learn and many people write programs in Python so we can share.

Chapter 1 Fundamentals of Java Programming

Transcription:

Quick Introduction to Java Dr. Chris Bourke Department of Computer Science & Engineering University of Nebraska Lincoln Lincoln, NE 68588, USA Email: cbourke@cse.unl.edu 2015/10/30 20:02:28 Abstract These are lecture notes used in CSCE 155 and CSCE 156 (Computer Science I & II) at the University of Nebraska Lincoln. They represent a short introduction to the Java programming language for students who already have a strong foundation in at least one high-level programming language. Contents 1 Overview 3 1.1 History....................................... 3 1.2 Key Aspects.................................... 3 1.3 Hello World Demo................................ 4 2 Variables 5 2.1 Primitives..................................... 5 2.2 Assignments & Literals.............................. 6 2.3 Declaration.................................... 7 3 Operators 8 4 Strings 8 5 Arrays 9 1

6 Conditionals 10 7 Loops 11 8 Input & Output 12 8.1 Command Line Arguments............................ 12 8.2 Standard I/O................................... 13 8.3 File Output.................................... 14 9 Searching & Sorting 15 10 Classes 16 11 Exceptions 18 Code Samples 1 Hello World Java Program............................ 5 2 Demonstration of Java Wrapper Classes.................... 6 3 Different Bases in Java.............................. 7 4 Casting in Java.................................. 7 5 Strings in Java.................................. 9 6 Arrays in Java................................... 10 7 Conditionals in Java............................... 10 8 Loops in Java................................... 11 9 Java Command Line Arguments......................... 13 10 Java Buffered Input................................ 13 11 Java Scanner................................... 14 12 Java File Output................................. 14 13 Searching & Sorting................................ 15 14 Bank Account class in Java........................... 17 15 Exceptions in Java................................ 19 2

1 Overview 1.1 History Developed by James Gosling, Sun Microsystems (1995) Designed with 5 basic principles Simple, Object-oriented, familiar Robust and secure Architecture-neutral and portable High performance Interpreted, threaded and dynamic Version History 1.0 1996 1.1 1997 introduced JDBC, inner classes, reflection 1.2 1998 Collections framework 1.3 2000 JNDI, HotSpot JVM 1.4 2002 Library improvements 1.5 2004 Generics introduced, enhanced-for loop (foreach loop), concurrency utilities SE6 2006 JVM improvements (synch, compiler, garbage collection), Update 26 (June 7, 2011) 1.7 July 2011 2009 2010: Oracle purchases Sun Summer 2012: Oracle loses lawsuit to Google (APIs, interfaces cannot be copyrighted) 1.2 Key Aspects C-style syntax: semicolons, bracketed code blocks, identifiers Objected-oriented: everything is a class or belongs to a class No memory management Built-in garbage collection When no valid references to an object exist, it is eligible for garbage collection 3

JVM uses sophisticated algorithms to determine when it is optimal to perform garbage collection Little or no control on when or how this occurs Portable Write once, compile once, run anywhere Compiled code is run within a Java Virtual Machine 1.3 Hello World Demo Packages Packages allow you to organize code into a tree-like structure Period delimits packages-subpackages Naming convention: all lower case, underscores; should go from general to specific Actual code is stored in a directory tree corresponding to the package names Class declarations Java: everything is a class or belongs to a class Code must be in a file with the same name as the class, HelloWorld.java Naming convention: UpperCamelCase Comments follow C-style comments //single line comments /* multi line comments */ Javadoc style comments Main method declaration Standard output (System.out.println) JDK Libraries http://download.oracle.com/javase/6/docs/api/ java.lang, java.util, java.io, java.sql, java.net, java.math, java.security Collections: List, ArrayList, Set, HashSet, Map, HashMap 4

Code Sample 1: Hello World Java Program 1 package unl. cse ; // package declaration 2 3 // imports would go here 4 5 /** 6 * A basic hello world program in Java 7 */ 8 public class HelloWorld { 9 10 // static main method 11 public static void main ( String args []) { 12 System. out. println (" Hello World!"); 13 } 14 15 } Command line demo Editing Compiling: javac HelloWorld.java Produces a.class file (Java Bytecode) Running: java HelloWorld IDE (Eclipse) demo Create a project, package, class Compiling: automatic; running 2 Variables 2.1 Primitives A primitive is a type that is built-in to a language Java defines 8 primitives (see Table 1) Java does define default values for variables: zero for numeric types, false for boolean types Wrapper classes provide an object-equivalent version for each primitive type 5

Type Details Wrapper Class byte 8-bit signed 2s complement integer Byte short 16-bit signed 2s complement integer Short int 32-bit signed 2s complement integer Integer long 64-bit signed 2s complement integer Long float 32-bit IEEE 754 floating point number Float double 64-bit floating point number Double boolean may be set to true or false Boolean char 16-bit unicode character Character Table 1: Primitive types in Java Wrapper classes have many utility functions for conversion, parsing, etc. Instances can be null, may need to make null pointer checks Instances of such classes are immutable: once created, they cannot be changed; only new instances can be created Code Sample 2: Demonstration of Java Wrapper Classes 1 // convert a string to an integer : 2 String s = " 1234 " 3 int a = Integer. parseint (s); 4 String a_bin = Integer. tostring (a, 2); 5 System. out. println (a + " in binary is " + a_bin ); 6 Integer b; 7 a += b; // would result in a NullPointerException 2.2 Assignments & Literals The standard assignment operator, = Standard numerical literals integers, floats (f), longs (l); scientific notation supported, 4.2e1 or 4.2E1 Different bases supported (see Code Sample 3) Character literals delimited by single quotes, char a = C or unicode (hex) escape: char a = \u4ffa String literals delimited by double quotes, String s = "hello"; Standard escape sequences 6

Sequence Meaning \b backspace \t tab \n line feed \f form feed \r carriage return \" double quote \ single quote \\ backslash Code Sample 3: Different Bases in Java 1 int n; 2 n = 0 b0010_1010 ; // binary, Java 7 only 3 n = 052; // octal, leading zero 4 n = 42; // decimal 5 n = 0 x2a ; // hex 2.3 Declaration Java is strongly typed; every variable must be declared to have a particular type and will always be that type (aka statically typed) Identifier rules: Identifiers can include characters A-Z, a-z, 0-9, _, $ but cannot begin with a digit Identifiers are case sensitive Naming convention: lowercamelcase Naming convention: CAPS_FOR_STATIC_CONSTANTS Cannot be a reserved word (see http://download.oracle.com/javase/tutorial/ java/nutsandbolts/_keywords.html) Scoping rules: variables are only valid within the block in which they are declared Casting: java does not allow implicit type casting when downcasting, does allow explicit; see Code Sample 4 Code Sample 4: Casting in Java 1 Double x = 10; // compile error 2 double y = 10; // okay (!) 7

3 Integer z = 10. 0; // compile error 4 int a = 10. 0; // compile error 5 // explicit type casting is required : 6 int a = 10; 7 double b = 10. 5; 8 double x = a + b; // okay 9 int c = a + b; // compile error 10 int d = ( int ) ( a + b); // explicit cast ok, truncation occurs 3 Operators Unary operators: increment/decrement, ++, -- Arithmetic: * / + - % Relational <, <=, >, >= Equality: ==,!=: careful when used with objects: reference comparison Logical:!, &&, (can only be applied to boolean expressions or variables, not integers!) 4 Strings Strings are a class provided as standard by the language Immutable; mutable version: StringBuilder Concatenation operator: + Comparison Using == is a reference operator, not a content comparison Strings are naturally ordered (lexicographically) by the language Meaning: they implement the Comparable interface They have a method: a.compareto(b) which returns: 0 if a, b have the same content < 0 if a precedes b (a comes before b) > 0 if a succeeds b (b comes before a) 8

a b Result foo bar positive bar baz negative foo foo zero aaa aaaa negative Table 2: Examples results of a.compareto(b) Various other member and static methods exist: public char charat(int) - returns the character at the specified position public String substring(int, int) - returns the substring between the indices (inclusive/exclusive) public String replaceall(string, String) - replaces all matches to the (first) regular expression with the second More: http://docs.oracle.com/javase/6/docs/api/java/lang/string.html Code Sample 5: Strings in Java 1 String s1 = " Hello " + " " + " World!"; 2 System. out. println (s1); 3 4 StringBuilder sb = new StringBuilder (); 5 sb. append (" Goodbye "); 6 sb. append (" "). append (" World!"); 7 String s2 = sb. tostring (); 8 System. out. println (s2); 9 10 if(s1. compareto (s2) > 0) { 11 System. out. println (" Goodbye World! comes second "); 12 else if(s1. compareto (s2) < 0) { 13 System. out. println (" Hello World! comes second "); 14 } else { 15 System. out. println (" They are equal somehow "); 16 } 17 18 // replace all whitespace with underscores : 19 String s3 = s1. replaceall ("\s", "_"); 5 Arrays All arrays are statically typed 9

Implicit size declaration: String mystrings[] = {"Hello", "world", "how", "are", "you"}; Dynamic declaration using the new operator: String mystrings[] = new String[10]; int myids[] = new String[20]; Arrays are zero-indexed and contiguous; size is kept track through a.length property: Multidimensional arrays supported Dynamic Collections alternative: ArrayList Code Sample 6: Arrays in Java 1 int myids [] = new int [ 10]; 2 myids [0] = 10; 3 System. out. println (" myids is an array of size " + myids. length + ", and the first element is " + myids [ 0]) ; 4 5 int mymatrix [][] = new int [5][5]; 6 mymatrix [ 0][ 4] = 10; // first row, last column 7 8 ArrayList < Integer > mylist = new ArrayList < Integer >() ; 9 mylist. add (10) ; 10 mylist. add (20) ; 11 mylist. add (30) ; 12 System. out. println (" mylist is an array list of size " + mylist. size () + ", and the first element is " + mylist. get (0) ); 6 Conditionals All the basic if-statements are supported Switch statements supported for integers Switch statements supported for Strings as of Java 7 Code Sample 7: Conditionals in Java 1 if(a > b) { 2 System. out. println (" foo "); 3 } 10

4 5 if(a > b) { 6 System. out. println (" foo "); 7 } else { 8 System. out. println (" bar "); 9 } 10 11 if(a > b) { 12 System. out. println (" foo "); 13 } else if (a == b) { 14 System. out. println (" bar "); 15 } else { 16 System. out. println (" baz "); 17 } 18 19 int month =...; 20 switch ( month ) { 21 case 1: 22 System. out. println (" January "); 23 break ; 24 case 2: 25 System. out. println (" February "); 26 break ; 27 case 3: 28 System. out. println (" March "); 29 break ; 30 default : 31 System. out. println (" Smarch "); 32 break ; 33 } 7 Loops Basic loops supported: for, while, do-while Enhanced for-loop for collections (arrays or any class that implements the Iterable interface) Code Sample 8: Loops in Java 1 for ( int i =0; i <10; i ++) { 2 System. out. println ("i = " + i); 3 } 4 11

5 int j = 0; 6 while (j < 10) { 7 System. out. println ("j = " + j); 8 j ++; 9 } 10 11 j = 0; 12 do { 13 System. out. println ("j = " + j); 14 j ++; 15 } while (j <10); 16 17 String mystrings [] = {" hello ", " world ", " foo ", " bar ", " baz "}; 18 for ( String s : mystrings ) { 19 System. out. println (s); 20 } 21 22 // older idiom for Iterable collections : 23 while (c. hasnext ()) { 24 System. out. println (c. next ()); 25 } 8 Input & Output 8.1 Command Line Arguments Most programs do not involve a user interface or even involve human interaction. Instead, programs executed from the command line can be configured by specifying command line arguments which are passed to the program when invoking it. For example: ~>./programname argument1 argument2 When a Java class is executed through the JVM via the command line, arguments can be passed to the class in a similar manner: ~>java JavaClass arg1 arg2 arg3 Note: Arguments are accessible in the main method through the args array: public static void main(string args[]) In most languages, the first argument is the name of the executable file. However, for Java, the first argument is not the class In the example above, arg[0] would hold the string arg1, etc. 12

Code Sample 9: Java Command Line Arguments 1 /** 2 * This program demonstrates command line argument usage 3 * by printing out all the arguments passed to it when invoked. 4 */ 5 public class CommandLineArgumentDemo { 6 public static void main ( String args []) { 7 if( args. length == 0) { 8 System. out. println (" No command line arguments provided " ); 9 } else { 10 for ( int i =0; i< args. length ; i ++) { 11 System. out. println (" args [" + i + "] = " + args [i]); 12 } 13 } 14 } 15 } 8.2 Standard I/O Standard Output: System.out (methods: print, println, printf) Printf-style formatting: String.format or System.out.printf Object-oriented formatting: java.util.formatter class Several classes exist BufferedReader, BufferedWriter, InputStream, OutputStream Better alternative: Scanner Code Sample 10: Java Buffered Input 1 try { 2 String line = null ; 3 // create a BufferedReader from a FileReader 4 BufferedReader br = new BufferedReader ( new FileReader (" input. txt ")); 5 // read the first line 6 line = br. readline (); 7 // while the line read is not null ( end of file ) 8 while ( line!= null ) { 9 // process the line 10 System. out. println ( line ); 11 // read the next line 13

12 line = br. readline (); 13 } 14 } catch ( Exception e) { 15... 16 } Code Sample 11: Java Scanner 1 // read from the standard input : 2 Scanner s = new Scanner ( System. in); 3 System. out. println (" Enter an integer : "); 4 int n = s. nextint (); 5 6 // read from a file 7 Scanner s = new Scanner ( new File (" input. txt ")); 8 int x = s. nextint (); 9 double y = s. nextdouble (); 10 String s = s. next (); 11 String line = s. nextline (); 12 while (s. hasnext ()) { 13 line = s. nextline (); 14 } 15 16 // by default, Scanner tokenizes on whitespace, 17 // you can reset this to any regular expression : 18 s. usedelimiter (","); 8.3 File Output Buffered text output: BufferedWriter and FileWriter Binary output: FileOutputStream Non-buffered text output: PrintWriter Code Sample 12: Java File Output 1 // Buffered text output : 2 File f = new File (" outfile. txt "); 3 BufferedWriter bw = new BufferedWriter ( new FileWriter ( f)); 4 // can write string or character data 5 bw. write (" Hello World \n"); 6 7 // Binary data output : 8 byte barray [] =...; 14

9 File f = new File (" outfile. bin "); 10 FileOutputStream fos = new FileOutputStream ( f); 11 fos. write ( barray ); 12 13 // Non - buffered text output ( easier, but fails silently ): 14 File f = new File (" outfile02. txt "); 15 PrintWriter pw = new PrintWriter ( f); 16 pw. print (" Hello "); 17 pw. print (10) ; 18 pw. print (3.14) ; 19 // or: 20 pw. printf ("%s, %d, %.4 f\n", " Hello ", 10, 3.14) ; 9 Searching & Sorting The Arrays class provides two sort methods for arrays Arrays.sort(...) Arrays.sort(T a[], Comparator<? super T> c) The Collections class provides two sort methods for lists Collections.sort(List<T> list) Collections.sort(List<T> list, Comparator<? super T> c) First version is for anything that is naturally ordered: any class that implements the Comparable interface Second version is for any type, but you must provide a Comparator for it Searching: binarysearch methods, collections have contains, indexof methods Code Sample 13: Searching & Sorting 1 int ids [] =...; 2 Arrays. sort ( ids ); 3 4 Comparator < Student > c = new Comparator < Student >() { 5 public int compare ( Student s1, Student s2) { 6 if(s1. getgpa () > s2. getgpa ()) { 7 return -1; 8 } else if (s1. getgpa () < s2. getgpa ()) { 9 return 1; 10 } else { 15

11 return 0; 12 } 13 } 14 }; 15 16 Student roster [] =...; 17 Arrays. sort ( roster, c); 18 19 ArrayList < Student > roster = new ArrayList < Student >() ; 20 Collections. sort ( roster, c); 10 Classes Object-oriented programming involves the interaction of complex, abstract data types (ADTs), often realized in programming languages as classes. Java is a class-based OOP language. Classes can be viewed as a blueprint for creating (called instantiating) instances which provide both state and behavior. Declaration Member variables: visibility-level type name; Visibility keywords (cf. Table 3), accessors/mutators: getters and setters Member methods: declared inside a class Constructors: same name as the class, no return type, multiple constructors can be defined; default one provided if none are defined Instantiation (new keyword invokes a constructor) Usage: dot operator Other modifiers static can be used with a method or variable to make it a member of the class instead of instances of the class. Access would then be through the class rather than an instance: BankAccount.foo() final can be used with a variable to make it a constant; attempts to modify a final variable are a compiler error final can also be used on methods (to make them non-virtual); and classes (to make them non-derivable) 16

Code Sample 14: Bank Account class in Java 1 public class BankAccount { 2 3 public static final String BANK_NAME = " First International Bank Co."; 4 5 private int bankaccountid ; 6 private String label ; 7 private double balance ; 8 private double apr ; 9 10 public BankAccount ( int bankaccountid, String label, double balance, double apr ) { 11 this. bankaccountid = bankaccountid ; 12 this. label = label ; 13 this. balance = balance ; 14 this. apr = apr ; 15 } 16 17 public BankAccount ( int bankaccountid, String label ) { 18 this ( bankaccountid, label, 0.0, 0. 0) ; 19 } 20 21 public int getbankaccountid () { 22 return this. id; 23 } 24 25 public void setbalance ( double balance ) { 26 this. balance = balance ; 27 } 28 29 // more getters and setters as desired here 30 31 public void deposit ( double deposit ) { 32 this. balance += deposit ; 33 } 34 35 public double getmonthlyinterestearned () { 36 return this. balance * this. apr / 12. 0; 37 } 38 39 private double getapy () { 40 return Math. exp ( this. apr ) - 1; 41 } 42 17

43 @Override 44 public String tostring () { 45 return this. label + " (" + this. bankaccountid + ") $" + this. balance ; 46 } 47 } 48 49... 50 51 BankAccount a = new BankAccount (1234, " Checking "); 52 a. setbalance (1000.0) ; 53 a. deposit (100.0) ; 54 a. deposit (a. getmonthlyinterestearned ()); 55 System. out. println (a); 56 57 System. out. println (" Bank Name : " + BankAccount. BANK_NAME ); Keyword Class Package Subclass(es) World public Y Y Y Y protected Y Y Y N public Y Y N N private Y N N N Table 3: Visibility Keywords and Access Levels 11 Exceptions Run-time errors occur when something goes wrong and your program cannot handle it (or by design shouldn t) We may be able to recover from some errors by handling them An Exception is an error that is not usual, but could be anticipated (FileNotFoundException ) Exceptions can be thrown or caught and handled Handling can be done in a try-catch-finally block Many predefined standard exceptions Uncaught exceptions will bubble up until caught or it kills the JVM process 18

Code Sample 15: Exceptions in Java 1 String s =...; 2 int n; 3 try { 4 // potentially unsafe code : 5 n = Integer. parseint (s); 6 } catch ( NumberFormatException nfe ) { 7 System. out. println (" String does not contain a valid numeric representation "); 8 } catch ( NullPointerException npe ) { 9 System. out. println (" String is null!"); 10 } catch ( Exception e) { 11 System. out. println (" Some other exception occurred, stack track follows... "); 12 e. printstacktrace (); 13 } finally { 14 // this code block will be executed whether or not an exception is thrown 15 // could be used to clean up any outstanding resources 16 } 17 18 // throwing : 19 if(n == 0) { 20 throw new RuntimeException (" cannot divide by zero!"); 21 } 19