Obj. Or. Prog. #1 1

Size: px
Start display at page:

Download "011 2562 Obj. Or. Prog. #1 1"

Transcription

1 OBJECT ORIENTED PROGRAMMING Feb Assist. Prof. Dr. Yunus Emre SELÇUK SCORING 1st midterm: %20, 06/04/2015 2nd midterm: %20, 11/05/2015 Final exam: %30, Project: %15, Lab: %15 GENERAL INFORMATION Unspecified dates and deadlines will be announced later The percentages can be changed slightly Do not forget what you have learned from the previous term, otherwise penalty points will be deduced from your scores. SUGGESTED BOOKS: Java Programming: Java How to Program, Harvey M. Deitel & Paul J. Deitel, Prentice-Hall. 7th ed. or newer Core Java 2 Volume I & II, C. S. Horstmann and G. Cornell, Prentice-Hall. 7th ed. or newer UML: UML Distilled, 3rd ed. (2003), Martin Fowler, Addison-Wesley. You can refer to any other book of your choice as well. 1 COURSE CONTENTS Introduction of the course. Primitives, wrappers, parameters. Exception handling Working with Files and Streams (Serialization). Introduction to generic classes using basic data structures (Lists). Introduction to generic classes using basic data structures (Maps). Typecasting, Enum classes, Inner classes. Introduction to Multithreading GUI Programming (with Swing) Obj. Or. Prog. #1 1

2 OBJECT ORIENTED PROGRAMMING LECTURE NOTES Assist. Prof. Dr. Yunus Emre SELÇUK PRIMITIVES AND WRAPPERS 3 PRIMITIVES AND WRAPPERS Primitive type: One unit of information (non-class). Wrapper: A class having one primitive number and some useful methods related with that member. Natural numbers in Java (Numbers without fractional parts): Primitive Meaning Range Wrapper int Integer (4 bytes) Lower: Higher: long short Big integer ( 8 bytes) Small integer ( 2 bytes) ( 9,22 x ) long natid = L; Lower: Higher: byte One byte Lower: 128 Higher: +127 Integer Long Short Byte Obj. Or. Prog. #1 2

3 PRIMITIVES AND WRAPPERS Real numbers in Java (Numbers with fractional parts): Primitive Meaning Range Wrapper double Large real number ( 1, ) Double float Small real number ( 3, ) Float Other primitives: Primitive Meaning Range Wrapper char Karakter 'A'-'Z', 'a'-'z', etc. (UTF-16 encoding) Character boolean Mantıksal false true Boolean I would also like to remind you the non-primitive type String soon. 5 PRIMITIVES AND WRAPPERS Operations with primitives: Arithmetic: + - * / %. Remember operator predecence ++, --, ++i and i++ differs: y * ++z, y * z++ Shorthands: += = *= /= %= Check the static methods of java.lang.math: pow, abs, round, Binary: Boolean algebra: & ~ ^ (and or not xor) Shifting: << >> Ex: The rightmost 4 th bit of n: (n&8)/8 or (n&(1<<3))>> Obj. Or. Prog. #1 3

4 PRIMITIVES AND WRAPPERS We use wrappers for their useful methods and in cases where primitives cannot be used. Serialization and map indexes are examples of such cases that we will cover in the later weeks. The wrappers reside in the java.lang package Some useful methods of class Integer (refer to Java API for further methods and more details) int compareto(integer anotherinteger) int intvalue() static int parseint(string s) String tostring() static String tostring(int i) static Integer valueof(string s) int ilkel1 = 5, ilkel2 = 7; Integer sarma1, sarma2; sarma1 = new Integer( ilkel1 ); sarma2 = new Integer( ilkel2 ); System.out.println("Sonuç1:"+sarma1.compareTo(sarma2)); //-1 7 PRIMITIVES AND WRAPPERS I would also like to remind you the non-primitive type String and some of its methods: int compareto(string anotherstring) int comparetoignorecase(string str) String concat(string str) //The + operation int indexof (String str) //-1, 0, "Selçuk". indexof ("ç") = 3 int length() String substring(int m, int n) Returns characters between positions m and n-1. Because Java (and indexof) begins counting from 0. "Selçuk".subString(0,3) = "Sel" String tolowercase() String touppercase() String trim() P.S. Problems with understanding the workings of these methods can mean that we have fundamental problems with the previous term's Object Oriented Concepts course Obj. Or. Prog. #1 4

5 PRIMITIVES AND WRAPPERS The primitive version of Enum classes: Sometimes, a variable should only hold a restricted set of values. For example, you may sell pizza in four sizes: small, medium, large, and extra large Of course, you could encode these sizes as integers 1, 2, 3, 4, or characters S, M, L, and X. But that is an error-prone setup. It is too easy for a variable to hold a wrong value (such as 0 or m). Example: Defining a primitive enum (in Size.java): public enum Size { SMALL, MEDIUM, LARGE, EXTRA_LARGE; Using in code: Size s = Size.MEDIUM; In fact, we have defined a class named Size and enforced that only four static instances of that class can be created. You cannot write Size s = Size.Medium or MEDIUM or M 9 PRIMITIVES AND METHOD PARAMETERS Java uses "call-by-value" calling style when passing primitive parameters to methods. This calling style works in the same way when you pass parameters without pointers in the C/C++ language. Java uses "call-by-value-of-references" when passing non-primitive parameters to methods. This calling style is different than the style "call-by-references", i.e. when you pass parameters as pointers in the C/C++ language. Well, this style is very similar to the pointer style, except you cannot change the memory address of object parameters This means that changes to object parameters are permanent, except re-initializing and swapping objects. Examine the following code and its output: Obj. Or. Prog. #1 5

6 PRIMITIVES AND METHOD PARAMETERS package oop00; public class MethodParametersTest1 { private Integer wrapi, wrapj; public void ilkelduzenle( int x ) { x++; public void sarmalayiciduzenle( Integer x ) { x++; public void ilkeldegistir( int x, int y ) { int temp; temp = x; x = y; y = temp; public void sarmalayicidegistir( Integer x, Integer y ) { Integer temp; temp = x; x = y; y = temp; public void sarmalayicidegistiralt(integer x, Integer y) { Integer temp; temp = new Integer(x); x = new Integer(y); y = new Integer(temp); public void swapforreal( ) { Integer temp = wrapi; wrapi = wrapj; wrapj = temp; public static void main(string[] args) { MethodParameters test = new MethodParameters(); test.tryme(); 11 PRIMITIVES AND METHOD PARAMETERS public void tryme() { int count = 3; System.out.println("Before : " + count ); this.ilkelduzenle(count); System.out.println("After: " + count ); Integer wrap = new Integer( 5 ); System.out.println("Before : " + wrap ); this.sarmalayiciduzenle(wrap); System.out.println("After: " + wrap ); int count1 = 1, count2 = 2; System.out.println("Before : " + count1 + ", " + count2 ); this.ilkeldegistir(count1, count2); System.out.println("After: " + count1 + ", " + count2 ); Integer wrap1 = new Integer( 1 ); Integer wrap2 = new Integer( 2 ); System.out.println("Before : " + wrap1 + ", " + wrap2 ); this.sarmalayicidegistir(wrap1, wrap2); System.out.println("After: " + wrap1 + ", " + wrap2 ); System.out.println("Before : " + wrap1 + ", " + wrap2 ); this.sarmalayicidegistiralt(wrap1, wrap2); System.out.println("After: " + wrap1 + ", " + wrap2 ); wrapi = 3; wrapj = 5; System.out.println("Before : " + wrapi + ", " + wrapj ); this.swapforreal(); System.out.println("After: " + wrapi + ", " + wrapj ); Obj. Or. Prog. #1 6

7 PRIMITIVES AND METHOD PARAMETERS The output: Before : 3 After: 3 Before : 5 After: 5 Before : 1, 2 After: 1, 2 Before : 1, 2 After: 1, 2 Before : 1, 2 After: 1, 2 Before : 3, 5 After: 5, 3 13 PRIMITIVES AND METHOD PARAMETERS Examine the following code and its output: package oop00; public class MethodParametersTest2 { public void tryme( ) { int x = 1, y = 2; System.out.println("Before : " + x + ", " + y ); int temp; temp = x; x = y; y = temp; System.out.println("After: " + x + ", " + y ); Integer sarma1 = new Integer( 3 ); Integer sarma2 = new Integer( 5 ); System.out.println("Before : " + sarma1 + ", " + sarma2 ); Integer gecici = sarma1; sarma1 = sarma2; sarma2 = gecici; System.out.println("After: " + sarma1 + ", " + sarma2 ); Obj. Or. Prog. #1 7

8 PRIMITIVES AND METHOD PARAMETERS public static void main(string[] args) { MethodParametersTest2 test = new MethodParametersTest2(); test.tryme(); The output: Before : 1, 2 After: 2, 1 Before : 3, 5 After: 5, 3 15 PRIMITIVES AND METHOD PARAMETERS Examine the following code and its output: package oop00; public class MethodParametersTest3 { public static void main(string[] args) { int[] dizi = { 1, 2, 3, 4, 5 ; LowHighSwap.doIt( dizi ); for( int j = 0; j < dizi.length; j++ ) System.out.print( dizi[j] + " " ); class LowHighSwap { static void doit( int[] z ) { int temp = z[ z.length - 1 ]; z[ z.length - 1 ] = z[ 0 ]; z[ 0 ] = temp; /* Using static has nothing to do with the * "call-by-value-of-references" issue. */ The output: Obj. Or. Prog. #1 8

9 OBJECT ORIENTED PROGRAMMING LECTURE NOTES Assist. Prof. Dr. Yunus Emre SELÇUK EXCEPTION HANDLING 17 EXCEPTION HANDLING "If that guy has any way of making a mistake, he will" Murphy's Law Some sources of error are: Bugs in JVM Wrong input by the user Buggy code written by us Acts of God A lone and humble programmer cannot control: every aspect of Internet traffic, file access rights, etc. But we should be aware of them and deal with them! There are multiple ways of dealing with errors. Boolean returns Form components with error checking mechanisms Exception handling. Exception handling is a form of error trapping Obj. Or. Prog. #1 9

10 EXCEPTION HANDLING Each exception is modeled by a class in Java. 19 EXCEPTION HANDLING java.lang.error: indicates serious problems that a reasonable application should not try to catch Depletion of system resources, internal JVM bugs, etc. java.lang.runtimeexception: This is mostly caused by our buggy code java.lang.nullpointerexception: We have tried to use an uninitialized object java.lang.indexoutofboundsexception: We have tried to access a non-existent member of an array. etc. java.io.ioexception: Something went wrong during a file operation or a network operation. These opearations are always risky, so we must have an alternate plan in case of something goes wrong. If having an alternate plan is a must, than the exception is determined as checked Obj. Or. Prog. #1 10

11 EXCEPTION HANDLING Handling checked exceptions is done by coding a try catch block. try { /* error-prone methods */; catch( AnException e ) { /* Dealing with error */ A programmer may opt to not handle a checked exception. However, someone will eventually handle it! amethod throws AnException { /* error-prone methods */ In this case, this someone is the one who calls that amethod 21 EXCEPTION HANDLING It is possible to handle multiple exceptions as well: try { /* error-prone methods */; catch( AnException e ) { /* Dealing with error */ catch( AnotherException e ) { /* Dealing with error */ About try blocks: Each new try block introduces a runtime overhead Therefore it's wiser to open one try block with multiple catch blocks Obj. Or. Prog. #1 11

12 EXCEPTION HANDLING What should I do in a catch block? Inform the user about the error with the e.printstacktrace( ) method. Log this error If this is a very serious error, you may release some resources and make a "clean exit" in the finally block. Scopes of the try block and the finally block are different. Therefore you cannot access the temporary variables/objects defined in the try block from the finally block. Plan your "clean exit" accordingly. The finally block executes whether an exception is thrown or not. try { /* error-prone methods */; catch( AnException e ) { /* Dealing with error */ catch( AnotherException e ) { /* Dealing with error */ finally { /* make a clean exit */ 23 EXCEPTION HANDLING public class ExceptionExample01 { MyScreenRenderer graphics; MyCADfile myfile; //Other methods of this class are omitted public void parsemycadfile( String filename ) { try { graphics = new MyScreenRenderer(); myfile = openfile( filename ); MyFigure figs[ ] = myfile.readfromfile( ); drawfigures( figs ); myfile.close(); catch( IOException e ) { System.out.println("An IO exception has occurred"+ " while opening or reading from file:"+ e.tostring( ) ); e.printstacktrace( ); System.exit(1); finally { graphics.releasesources(); Obj. Or. Prog. #1 12

13 EXCEPTION HANDLING You can create your own Exception classes by : inheriting from IOException if you want your exception to be a checked one, inheriting from RuntimeException if you want an unchecked one. public class MyFileFormatException extends IOException { public MyFileFormatException( ) { super( ); //was required in JDK versions older than 5 public MyFileFormatException( String errormessage ) { super( errormessage ); /* Ayrıca yapmak istediğiniz işler */ 25 EXCEPTION HANDLING Throwing an exception: If something terrible may happen during your code, you can throw an exception public class AProgram { public void processfile ( ) { some_statements(); if( an_unexpected_situation ) throw new MyFileFormatException("... happened"); Obj. Or. Prog. #1 13

14 Let's wrap it up all by an example: EXCEPTION HANDLING package oop01; import java.io.ioexception; /* Eğer RuntimeException'dan türetsek * tüm kodlarımız nasıl olacaktı inceleyiniz. public class ImpossibleInfo extends IOException { public ImpossibleInfo( String errormessage ) { super(errormessage); 27 package oop01; public class Person { private String name; private int age; EXCEPTION HANDLING public Person( String name ) { this.name = name; public String getname( ) { return name; public int getage( ) { return age; public String tostring() { return getname() + " " + getage( ); public void setage( int age ) throws ImpossibleInfo { if( age < 0 age > 150 ) throw new ImpossibleInfo("Impossible age: "+age); this.age = age; Obj. Or. Prog. #1 14

15 EXCEPTION HANDLING package oop01; import java.util.*; public class TestExceptions { public static void main(string[] args) { Scanner in = new Scanner(System.in); System.out.print("Enter person's name: "); String name = in.nextline(); Person insan = new Person(name); try { System.out.print("Enter age: "); int age = in.nextint(); insan.setage(age); System.out.println(insan); catch (ImpossibleInfo e) { e.printstacktrace(); finally { in.close(); You can wrap the statement that can cause an exception and the remaining statements with the try block or you can put all statements into the try block OBJECT ORIENTED PROGRAMMING LECTURE NOTES Assist. Prof. Dr. Yunus Emre SELÇUK INTRODUCTION TO GENERIC CLASSES AND BASIC DATA STRUCTURES IN JAVA Obj. Or. Prog. #1 15

16 INTRO. GENERIC CLASSES and DATA STRUCTURES in JAVA Generic programming means to write code that can be reused for objects of many different types. Recent languages such as Java and C# support generics. Generics are, at least on the surface, similar to templates in C++. The aim of this section is to make you familiar with the usage of generic classess. We will try to reach this aim by teaching you how to use some of the generic classes that comes with the Java language. We have chosen the examples from the basic data structures in the java.util library. Therefore, an introduction to these data structures exists in the course notes. The aim of this section is not to: Teach you how to write your own generic classes. Teach you about data structures. 31 INTRO. GENERIC CLASSES and DATA STRUCTURES in JAVA Introduction to Data Structures: A data structure is a scheme for organizing data in the memory of a computer In a general sense, any data representation is a data structure. Example: An integer. More typically, a data structure is meant to be an organization for a collection of data items. The way in which the data is organized affects the performance of a program for different tasks. The choice of data structure and algorithm can make the difference between a program running in a few seconds or many days! Some of the more commonly used data structures include arrays, lists, stacks, queues, heaps, trees, and graphs Obj. Or. Prog. #1 16

17 INTRO. GENERIC CLASSES and DATA STRUCTURES in JAVA Introduction to linked lists: Linear collection of self-referential class objects, called nodes Connected by pointer links (transparent to the programming user in Java) The first (head) and last (tail) nodes of the list are accessed via an object reference Traversing between the nodes is done by using using an iterator object obtained from the data structure You may write your own traversal code according to the organization of the data structure. Traversing an entire list is easier (thanks to the for-each loop). INTRO. GENERIC CLASSES and DATA STRUCTURES in JAVA An example linked list holding Integer objects: Head node An element (an object) and pointer Tail node NULL pointer (points to nothing) (end of list) Obj. Or. Prog. #1 17

18 INTRO. GENERIC CLASSES and DATA STRUCTURES in JAVA Advantages of linked lists over arrays: Enlarging a list costs nothing! Insertion and removal of elements to any position is faster. Sorting algorithms work faster on linked lists. Advantage of arrays over linked lists: Lists are traversed sequentially where any i th member of an array is directly accessible. Types of linked lists: Single-linked list: Only traversed in one direction Doubly-linked list: Allows traversals both forwards and backwards A list may also be circular. Pointer in the last node points back to the first node (like prayer beads) 35 INTRO. GENERIC CLASSES and DATA STRUCTURES in JAVA An example list implementation in java: The java.util.arraylist class Based on arrays, single-linked, thread-unsafe. Initialization: ArrayList mylist = new ArrayList(); In such definition, the nodes are instances of Object. This makes typecasting mandatory in order to use the node objects. Luckily, support for 'Generic Programming' is introduced in JSE 5.0. Generic programming means to write code that can be reused for objects of many different types. For example, you don t want to program or use separate classes to collect String and File objects. And you don t have to! The single class ArrayList collects objects of any class and constitutes an example of generic programming. Example: Creating an ArrayList instance which will contain Person instances ArrayList<Person> liste = new ArrayList<Person>(); Obj. Or. Prog. #1 18

19 INTRO. GENERIC CLASSES and DATA STRUCTURES in JAVA Fundamental methods of the ArrayList class: add( <T> object ): Adds an element (an object of type T) to the end of the list. <T> get( int i ): Returns the i th element. int size( ): Returns the number of elements in this list Remember that the entire list can be easily traversed by using the foreach loop. A selection of the other methods of the ArrayList class: ensurecapacity( int size ): Increases the capacity of this ArrayList instance, if necessary. trimtosize( ): Trims the capacity of this ArrayList instance to be the list's current size. set( int i, <T> element ): Replaces the element at the specified position in this list with the specified element. remove( int i ): Removes the i th element from this list. If the current size is less than i, an IndexOutOfBoundsException is throwed (unchecked). 37 INTRO. GENERIC CLASSES and DATA STRUCTURES in JAVA Let's implement a multiplicty association (1-*) by using ArrayList Obj. Or. Prog. #1 19

20 INTRO. GENERIC CLASSES and DATA STRUCTURES in JAVA package oop02a; import java.util.*; public class Course { private String code; private String name; private int capacity; private ArrayList<Student> students; public Course(String code, String name, int capacity) { this.code = code; this.name = name; this.capacity = capacity; students = new ArrayList<Student>(); public String getcode() { return code; public String getname() { return name; public int getcapacity() { return capacity; public int getstudentcount() { return students.size(); public boolean addstudent( Student astudent ) { if( getstudentcount() == capacity findstudent(astudent.getnumber())!= null ) return false; students.add(astudent); return true; 39 INTRO. GENERIC CLASSES and DATA STRUCTURES in JAVA public Student findstudent( String number ) { for( Student astudent : students ) if( astudent.getnumber().compareto(number) == 0 ) return astudent; return null; public void increasecapacity( int newcapacity ) { if( newcapacity <= capacity ) return; capacity = newcapacity; public void showclasslist( ) { System.out.println("Class List of "+code+" "+name); System.out.println("Student# Name, Surname"); System.out.println(" "); for( Student astudent : students ) System.out.println(aStudent.getNumber()+ " " + astudent.getname()); Please compare this code with the ones you can write by using arrays and see how much cleaner your code has become (show from oop02x). In this example, the member "capacity" exists only for business logic, not for array operations Obj. Or. Prog. #1 20

21 INTRO. GENERIC CLASSES and DATA STRUCTURES in JAVA package oop02x; public class Course { private String code; private String name; private int capacity, studentcount; private Student[ ] students; public Course(String code, String name, int capacity) { this.code = code; this.name = name; this.capacity = capacity; students = new Student[capacity]; studentcount = 0; public String getcode() { return code; public String getname() { return name; public int getcapacity() { return capacity; public int getstudentcount() { return studentcount; public boolean addstudent( Student astudent ) { if( studentcount == capacity findstudent(astudent.getnumber())!= null ) return false; students[studentcount] = astudent; studentcount++; return true; public Student findstudent( String number ) { for( int i = 0; i < studentcount; i++ ) if( students[i].getnumber().compareto(number) == 0 ) return students[i]; return null; Continues on the next slide 41 INTRO. GENERIC CLASSES and DATA STRUCTURES in JAVA Continued from the next slide public void increasecapacity( int newcapacity ) { if( newcapacity <= capacity ) return; Student[ ] gecicidizi = new Student[ newcapacity ]; for( int i = 0; i < studentcount; i++ ) gecicidizi[i] = students[i]; students = gecicidizi; capacity = newcapacity; public void showclasslist( ) { System.out.println("Class List of "+code+" "+name); System.out.println("Student# Name, Surname"); System.out.println(" "); for( Student astudent : students ) if( astudent!= null ) //dizi gerçeklemesinde gerekli! System.out.println(aStudent.getNumber()+" "+astudent.getname()); Obj. Or. Prog. #1 21

22 INTRO. GENERIC CLASSES and DATA STRUCTURES in JAVA Introduction to map structures: The map data structure lets you to easily reach an existing element according to its unique identifier This operation is also much faster with map structures than with array and list structures Element = value, unique identifier = key INTRO. GENERIC CLASSES and DATA STRUCTURES in JAVA A map implementation in Java: The java.util.hashmap class java.util.hashmap<k,v> K: Key, V: Value Fundamental methods of the HashMap class : public V get( Object key ); Returns the value to which the specified key is mapped. public V put( K key, V value ); Associates the specified value with the specified key in this map. I suggest you to obtain the key from the value (by using the necessary get method to access its unique identifier). If a value already exists in the data structure with the given key, the old value is deleted and returned, whereas the new value is inserted into the collection. public Collection<V> values( ); Returns a list of all values stored in this table which can easily be traversed by using the for-each loop. At this point, it is not necessary to know the specifics of the generic Collection interface Obj. Or. Prog. #1 22

23 INTRO. GENERIC CLASSES and DATA STRUCTURES in JAVA Let's implement the previous example by using HashMap: package oop02b; import java.util.*; public class Course { private String code; private String name; private int capacity; private HashMap<String,Student> students; public Course(String code, String name, int capacity) { this.code = code; this.name = name; this.capacity = capacity; students = new HashMap<String,Student>(); public String getcode() { return code; public String getname() { return name; public int getcapacity() { return capacity; public int getstudentcount() { return students.size(); public boolean addstudent( Student astudent ) { if( getstudentcount() == capacity findstudent(astudent.getnumber())!= null ) return false; students.put(astudent.getnumber(), astudent); return true; 45 INTRO. GENERIC CLASSES and DATA STRUCTURES in JAVA public Student findstudent( String number ) { return students.get(number); public void increasecapacity( int newcapacity ) { if( newcapacity <= capacity ) return; capacity = newcapacity; public void showclasslist( ) { System.out.println("Class List of "+code+" "+name); System.out.println("Student# Name, Surname"); System.out.println(" "); for( Student astudent : students.values() ) System.out.println(aStudent.getNumber()+ " " + astudent.getname()); Please compare this code which uses maps with the previous one which uses lists and notice the conveniences for the programmer Obj. Or. Prog. #1 23

24 INTRO. GENERIC CLASSES and DATA STRUCTURES in JAVA TESTING We wrote some code, but we didn't test it for bugs. Let's do it: public class USIS { public static void main(string[] args) { Course oop = new Course(" ", "Obj. Or. Prog.", 3); Student yasar = new Student(" ","Yaşar Nuri Öztürk"); if(!oop.addstudent(yasar) ) System.out.println("Problem #1"); if( oop.addstudent(yasar) ) System.out.println("Problem #2"); Student yunus = new Student(" ","Yunus Emre Selçuk"); oop.addstudent(yunus); Student fatih = new Student(" ","Fatih Çıtlak"); oop.addstudent(fatih); Student cemalnur = new Student(" ","Cemalnur Sargut"); if( oop.addstudent(cemalnur) ) System.out.println("Problem #3"); if( oop.findstudent(" ")!= fatih ) System.out.println("Problem #4"); System.out.println("End of test"); Why isn't there a package name? How can we document this new class? 47 INTRO. GENERIC CLASSES and DATA STRUCTURES in JAVA SUMMARY OF FUNDAMENTAL DATA STRUCTURE IMPLEMENTATIONS: java.util.linkedlist<e> implements List<E> Faster insertions and deletions Slower random access Doubly-linked (Can be traversed backwards by obtaining a ListIterator instance [not to be covered?] ). java.util.arraylist<e> implements List<E> Slower insertions and deletions Faster random access java.util.vector<e> implements List<E> Similar to ArrayList synchronized Suitable for multi-threaded use, slower in single-threaded use java.util.hashmap<k,v> implements Map<K,V> Used for fast searches by a key (indexed) java.util.hashtable<k,v> implements Map<K,V> Similar to HashMap but synchronized Suitable for multi-threaded use, slower in single-threaded use Attention: Lowercase t in class name Hashtable Obj. Or. Prog. #1 24

25 OBJECT ORIENTED PROGRAMMING LECTURE NOTES Assist. Prof. Dr. Yunus Emre SELÇUK TYPECASTING 49 TYPECASTING Remember the following rule of inheritance: An instance of a sub class can be used wherever an instance of its super class is expected. This is a type-safe operation and it is done automatically. We can convert a specific object to a more general one without loosing any information. Conversion in the opposite direction is risky, therefore it is done manually. The Java terminology uses the word "type casting" for converting the type of an object. You can make a manual cast from one type to another, according to the following rules: From the interface to the class of the object From the super class to the sub class However, this is an unsafe operation and therefore you need to make a check beforehand Obj. Or. Prog. #1 25

26 Example: TYPECASTING TYPECASTING Coding class MarketShelf: import java.util.*; public class MarketShelf { private LinkedList<Item> items; public MarketShelf() { items = new LinkedList<Item>(); public boolean doesexist( Item anitem ) { for( Item item : items ) if( item == anitem ) return true; return false; public boolean additem( Item anitem ) { if( doesexist(anitem) ) return false; items.add(anitem); return true; Obj. Or. Prog. #1 26

27 TYPECASTING Coding class MarketShelf: public void checkforexpiration( ) { boolean hasexpireditem = false; System.out.println("Expired item(s): "); for( Item item : items ) { if( item instanceof Food ) if( ((Food)item).isExpired() ) { hasexpireditem = true; System.out.println(item); if( hasexpireditem == false ) System.out.println("All items are fresh!"); Checking for type compliance and typecasting Coding class MarketShelf: TYPECASTING public static void main( String[] args ) { MarketShelf fridge = new MarketShelf(); Calendar cal = Calendar.getInstance(); cal.add(calendar.day_of_month,1); Date future = cal.gettime(); cal.set(calendar.year, 2010); cal.set(calendar.month, 0); //0: January cal.set(calendar.date, 12); Date past = cal.gettime(); fridge.additem( new Food(past) ); fridge.additem( new Food(future) ); fridge.additem( new Electronics() ); fridge.checkforexpiration(); Using java.util.date and Calendar classes Obj. Or. Prog. #1 27

28 Coding class Food: TYPECASTING package oop03b; import java.util.date; public class Food implements Item { private Date expiredate; public Food(Date expiredate) { this.expiredate = expiredate; public Date getexpiredate() { return expiredate; public boolean isexpired( ) { Date today = new Date(); if( expiredate.before(today) ) return true; else return false; public String tostring() { return "A food expiring at " + expiredate; Using java.util.date class continues TYPECASTING Critique of typecasting: Typecasting is a "necessary evil". Use it sparingly. Back in the days where generic classes were not available in Java, we had to make typecasting frequently. Nowadays, we need typecasting only when we make deserialization (topic of the next lecture). We can always make designs without typecasting. Let's modify our design: In other cases, we can make good use of abstract classes and polymorphism. In those cases, we are advised to avoid any relationship with the subclasses Obj. Or. Prog. #1 28

29 OBJECT ORIENTED PROGRAMMING LECTURE NOTES Assist. Prof. Dr. Yunus Emre SELÇUK WORKING WITH FILES 57 RELATED EXCEPTIONS WORKING WITH FILES java.io.ioexception: Represents I/O exceptions in general. java.io.eofexception extends IOException: Indicates that the end of file or stream has been reached unexpectedly. java.io.filenotfoundexception extends IOException: Indicates that the requested file cannot be found in the given path. java.lang.securityexception extends java.lang.runtimeexception: Indicates that the requested operation cannot be executed due to security constraints. GENERAL INFORMATION ABOUT FILE OPERATIONS File operations are separated into two main groups in Java: File management: Opearations such as creating, renaming, deleting files and folders. I/O operations. I/O operations are not only done with files but also with different sources such as TPC sockets, web pages, console, etc. Therefore I/O operations: have been separated from file operations coded in the same way for all these different sources. This approach is in harmony with the nature of object oriented paradigm. However, the complexity has been increased as a side effect Obj. Or. Prog. #1 29

30 WORKING WITH FILES FILE MANAGEMENT Coded by using the java.io.file class which represents both the files and the folders in the hard drive. Creating a File object does not mean to create an actual file or folder. Creating a File object : Done by using the File( String filename) constructor. filename should contain both the path and the name of the file/folder. Full path vs. relative path. Using full path degrades portability Relativity is tricky as well: IDEs may keep source and class files in different folders. Path separator: Windows uses \ (should be denoted as \\ in Strings), Unix uses /. What about portability? public static String File.separator public static char File.separatorChar File( String path, String name) and File( File path, String name ) constructors: Represents a file/folder with the given name in the folder given by the path parameter. 59 FILE MANAGEMENT WORKING WITH FILES Some methods of the class java.io.file: boolean exists( ); tells whether the file exists or not. boolean isfile( ); returns true if this File object represents a file, false otherwise, i.e. this object represents a folder. File getparentfile( ); Returns the directory where this file/folder resides. String getcanonicalpath( ) throws IOException; Returns the full path of the file/folder, including the file name. boolean canread( ); Can this application read form this file? boolean canwrite( ); Can this application write to this file? boolean createnewfile( ); Actually creates the file. boolean mkdir( ); Actually creates the folder. boolean mkdirs( ); Actually creates the folder with all necessary parent folders boolean renameto( File newname ); Renames the file. boolean delete( ); Deletes the file. boolean returns: True if the operation is successful. You do not have to memorize all those methods Obj. Or. Prog. #1 30

31 WORKING WITH FILES I/O OPERATIONS USING STREAMS Any I/O source is represented as stream in Java Files, memory, command prompt, network, etc. Binary vs. Text format: Binary I/O is fast and efficient, but it is not easily readable by humans. Text I/O is the opposite. Random vs. Sequential access: Sequential access: All records are accessed from the beginning to the end Random access: A particular record can be accessed directly. Disk files are random access, but streams of data from a network are not. Java chains streams together for different working styles. We will study a mechanism which allows makes it possible to write any object to a stream and read it again later. This process is called serialization in the Java terminology. 61 I/O OPERATIONS USING STREAMS WORKING WITH FILES Serialization Output operations: We will write entire objects to a file on disk. The classes of objects to be serialized should implement the java.io.serializable interface. You do not need to do anything else as the java.io.serializable interface does not have any methods. ObjectOutputStream and FileOutputStream objects are chained together for serialization. Multiple objects can and should be sent to the same stream Obj. Or. Prog. #1 31

32 I/O OPERATIONS USING STREAMS Example record: the class Arkadas WORKING WITH FILES public class Arkadas implements java.io.serializable { private static final long serialversionuid = 1L; private String isim, telefon, eposta; public Arkadas( String name ) { this.isim = name; public String getisim( ) { return isim; public String gettelefon( ) { return telefon; public void settelefon( String telefon ) { this.telefon = telefon; public String geteposta( ) { return eposta; public void seteposta( String posta ) { eposta = posta; public String tostring( ) { return isim + " - " + telefon + " - " + eposta; 63 I/O OPERATIONS USING STREAMS WORKING WITH FILES About the lines beginning : These are special commands called annotations. They work at the meta level, i.e. they contain information about information. They give information to the IDE, compiler, another programme, etc. about this program. We have used the annotation mechanism to remove the warnings. In fact, warnings must be taken into consideration. In the previous examples, we have disabled these warnings with annotations. In the example above, we didn t use annotation as the warning is directly related with our current subject Obj. Or. Prog. #1 32

33 WORKING WITH FILES I/O OPERATIONS USING STREAMS About the serialversionuid member: private static final long serialversionuid = 1L; We can give a particular version instead of 1, or we can have the IDE to generate a unique identifier automatically. If we do not code this member, we can hide the related warning with command. What does this member mean? There will be applications which save and load objects from different sources. In time, the source code of the classes of these objects may change, as well as the source code of the aforementioned applications. Different versions of all those classes can exist together. In order to avoid incompatibilities, we need a versioning mechanism. This mechanism is implemented by giving a different (and possibly increasing) serial number to classes and by checking this serial in the applications. 65 I/O OPERATIONS USING STREAMS WORKING WITH FILES An application for writing the objects to a file (serialization/output): import java.util.*; import java.io.*; public class ArkadasOlustur { public static void main(string[] args) { Integer arkadassayisi; Arkadas[ ] arkadaslar; Scanner giris = new Scanner( System.in ); System.out.println("Bu program arkadaşlarınızın iletişim " + " bilgilerini diskteki bir dosyaya kaydeder."); System.out.print("Kaç arkadaşınızın bilgisini gireceksiniz? "); arkadassayisi = giris.nextint( ); giris.nextline( ); arkadaslar = new Arkadas[arkadasSayisi]; for( int i = 0; i < arkadassayisi; i++ ) { System.out.print((i+1)+". arkadaşınızın ismi nedir? "); arkadaslar[i] = new Arkadas( giris.nextline() ); System.out.print("Bu arkadaşınızın telefonu nedir? "); arkadaslar[i].settelefon( giris.nextline() ); System.out.print("Bu arkadaşınızın e-posta adresi nedir? "); arkadaslar[i].seteposta( giris.nextline() ); Obj. Or. Prog. #1 33

34 WORKING WITH FILES I/O OPERATIONS USING STREAMS Serialization example (cont d): try { String dosyaadi = "arkadaslar.dat"; ObjectOutputStream yazici = new ObjectOutputStream( new FileOutputStream( dosyaadi ) ); yazici.writeobject( arkadassayisi ); for( Arkadas arkadas : arkadaslar ) yazici.writeobject( arkadas ); yazici.close(); System.out.println("Girilen bilgiler " + dosyaadi + " adlı dosyaya başarıyla kaydedildi."); catch( IOException e ) { System.out.println("Dosyaya kayıt işlemi sırasında"+ " bir hata oluştu."); e.printstacktrace(); 67 WORKING WITH FILES I/O OPERATIONS USING STREAMS Deserialization Input operations: We will read entire objects form a file on disk. ObjectInputStream and FileInputStream objects are chained together for deserialization. Typecasting is required as the objects read from a stream comes as instances of the class Object. If these objects are to be stored in an array, we need to know how many objects there will be. In the data structures that may grow dynamically, we are not faced with this inconvenience Obj. Or. Prog. #1 34

35 WORKING WITH FILES I/O OPERATIONS USING STREAMS An application for reading the objects from a file (deserialization/input): import java.io.*; public class ArkadasGoster { public static void main( String[] args ) { String dosyaadi = "arkadaslar.dat"; try { ObjectInputStream okuyucu = new ObjectInputStream( new FileInputStream( dosyaadi ) ); Integer kayitsayisi = (Integer)okuyucu.readObject(); for( int i = 0; i < kayitsayisi; i++ ) { Arkadas arkadas = (Arkadas) okuyucu.readobject(); System.out.println(arkadas); okuyucu.close(); 69 I/O OPERATIONS USING STREAMS Deserialization example (cont d): WORKING WITH FILES catch( IOException e ) { System.out.println("Dosya okuma işlemleri sırasında" + " bir hata oluştu."); e.printstacktrace(); catch( ClassNotFoundException e ) { System.out.println("Okunan kayıtları işlerken " + "bir hata oluştu."); e.printstacktrace(); Obj. Or. Prog. #1 35

36 WORKING WITH FILES I/O OPERATIONS USING STREAMS More on object streams: There is no safe and efficient way to determine whether the end of a stream has been reached. Therefore we couldn't use a while loop such as: try { ObjectInputStream okuyucu = new ObjectInputStream( new FileInputStream( dosyaadi ) ); Arkadas arkadas = (Arkadas) okuyucu.readobject(); while okuyucu.hasnext() { System.out.println(arkadas); arkadas = (Arkadas) okuyucu.readobject(); okuyucu.close(); Does not work! 71 I/O OPERATIONS USING STREAMS WORKING WITH FILES There is a method, int ObjectInputStream.available( ), but this is somewhat buggy Moreover, readobject() doesn't return null at EOF You can code a solution by letting the exception to happen, and terminate the loop in the catch block. However, exception handling is not invented for altering the program flow. A better alternative to writing the data object count beforehand is to use only one container object which stores references all the data objects. This container object will be a data structure, such as a list or a map. However, the objects in the container must implement the java.io.serializable interface. Will be shown in the next slide. If there is a relation A B, both A and B must implement the java.io.serializable interface Obj. Or. Prog. #1 36

37 WORKING WITH FILES I/O OPERATIONS USING STREAMS Serializing data structures: package oop04b; import java.util.*; import public class ArkadasOlustur { public static void main(string[] args) { LinkedList<Arkadas> arkadaslar = new LinkedList<Arkadas>(); Scanner giris = new Scanner( System.in ); System.out.println("Bu program arkadaşlarınızın iletişim " + " bilgilerini diskteki bir dosyaya kaydeder."); System.out.print("Kaç arkadaşınızın bilgisini gireceksiniz? "); int arkadassayisi = giris.nextint( ); giris.nextline( ); for( int i = 0; i < arkadassayisi; i++ ) { System.out.print((i+1)+". arkadaşınızın ismi nedir? "); Arkadas arkadas = new Arkadas( giris.nextline() ); System.out.print("Bu arkadaşınızın telefonu nedir? "); arkadas.settelefon( giris.nextline() ); System.out.print("Bu arkadaşınızın e-posta adresi nedir? "); arkadas.seteposta( giris.nextline() ); arkadaslar.add(arkadas); 73 I/O OPERATIONS USING STREAMS Serializing data structures (cont'd): WORKING WITH FILES try { String dosyaadi = "arkadaslaralt.dat"; ObjectOutputStream yazici = new ObjectOutputStream( new FileOutputStream( dosyaadi ) ); yazici.writeobject( arkadaslar ); yazici.close(); System.out.println("Girilen bilgiler " + dosyaadi + " adlı dosyaya başarıyla kaydedildi."); catch( IOException e ) { System.out.println("Dosyaya kayıt işlemi sırasında"+ " bir hata oluştu."); e.printstacktrace(); Obj. Or. Prog. #1 37

38 WORKING WITH FILES I/O OPERATIONS USING STREAMS Deserializing data structures: package oop04b; import java.io.*; import java.util.*; public class ArkadasGoster { public static void main( String[] args ) { String dosyaadi = "arkadaslaralt.dat"; try { ObjectInputStream okuyucu = new ObjectInputStream( new FileInputStream( dosyaadi ) LinkedList<Arkadas> arkadaslar = (LinkedList<Arkadas>)okuyucu.readObject(); for( Arkadas arkadas : arkadaslar ) { System.out.println(arkadas); okuyucu.close(); 75 I/O OPERATIONS USING STREAMS WORKING WITH FILES Deserializing data structures (cont'd.): catch( IOException e ) { System.out.println("Dosya okuma işlemleri sırasında" + " bir hata oluştu."); e.printstacktrace(); catch( ClassNotFoundException e ) { System.out.println("Okunan kayıtları işlerken " + "bir hata oluştu."); e.printstacktrace(); What about working with text files? Refer to Vol.II of Core Java 8th ed. or any other book of your choice Obj. Or. Prog. #1 38

39 OBJECT ORIENTED PROGRAMMING LECTURE NOTES Assist. Prof. Dr. Yunus Emre SELÇUK ENUM CLASSES 77 ENUM CLASSES The primitive enum we have learned is in fact a class definition. Each member of an enum is an instance of that class. There cannot be any other members of an enum except the ones that are already defined. An enum type can member fields, methods and constructors as any other regular classes. The constructor of an enum class must be private. Example: package oop05a; This must be the first line of code! public enum Tariff { NETFREE(0,4,60), NET4(4,8,30), NET6(6,8,40); private int quota, speed, fee; private Tariff( int quota, int speed, int fee ) { this.quota = quota; this.speed = speed; this.fee = fee; public int getquota() { return quota; public int getspeed() { return speed; public int getfee() { return fee; Obj. Or. Prog. #1 39

40 ENUM CLASSES Example: 79 Creating and using an enum object: public class Test { ENUM CLASSES public static void main(string[] args) { Tariff tariff4 = Tariff.NET4; Person yunus = new Person("Yunus Emre"); yunus.subscribeto(tariff4); Person berkin = new Person("Berkin Gülay"); berkin.subscribeto(tariff.netfree); System.out.println(yunus); System.out.println(berkin); Obj. Or. Prog. #1 40

41 OBJECT ORIENTED PROGRAMMING LECTURE NOTES Assist. Prof. Dr. Yunus Emre SELÇUK INNER CLASSES 81 INNER CLASSES You can code a class within a class. An inner class is coded within an outer class. An inner class can: Access all members of the outer class, including the private ones. Be hidden from other classes of the same package, if defined as private. It is frequently used in form of anonymous inner classes in GUI programming. Anonymous = without a name! You cannot: define a static method in a an inner class. An example: Person and Employee classes Obj. Or. Prog. #1 41

42 INNER CLASSES package oop05b; public class Person { private String name; public Person( String name ) { this.name = private class Employee { //begin inner class private int salary; public Employee( int salary ) { this.salary = salary; public int getsalary() { return salary; public void setsalary(int salary) { this.salary = salary; public String tostring( ) { return name + " " + salary; //end inner class public static void main( String[] args ) { Employee[] staff = new Employee[3]; Person kisi; kisi = new Person("Osman Pamukoğlu"); staff[0] = kisi.new Employee( ); kisi = new Person("Nihat Genç"); staff[1] = kisi.new Employee( 7500 ); kisi = new Person("Barış Müstecaplıoğlu"); staff[2] = kisi.new Employee( 6000 ); for( Employee eleman: staff ) System.out.println( eleman ); 83 INNER CLASSES Previous example is a demonstration of how to: define an inner class access the outer object from the inner object access the inner object from the outer object The inner class in the previous example is private. Therefore, it is hidden from all classes, including the ones within the same package. Which means, the Person.main method cannot be moved to any other class. The next example will show how to access a public inner class from any other class Obj. Or. Prog. #1 42

43 package oop05c; INNER CLASSES public class Person { private String name; public Person( String name ) { this.name = name; public class Employee { private int salary; public Employee( int salary ) { this.salary = salary; public int getsalary() { return salary; public void setsalary(int salary) { this.salary = salary; public String tostring( ) { return name + " " + salary; 85 package oop05c; INNER CLASSES //this import is absolutely necessary import oop05c.person.employee; public class TestInnerClassDirectly { public static void main( String[] args ) { Employee[] staff = new Employee[3]; Person kisi; kisi = new Person("Osman Pamukoğlu"); staff[0] = kisi.new Employee( ); kisi = new Person("Nihat Genç"); staff[1] = kisi.new Employee( 7500 ); kisi = new Person("Barış Müstecaplıoğlu"); staff[2] = kisi.new Employee( 6000 ); for( Employee eleman: staff ) System.out.println( eleman ); PS: Instead of the import statement, you can write Person.Employee wherever necessary Obj. Or. Prog. #1 43

44 INNER CLASSES This example shows how to access a private inner class from any other class: By using a public method of the outer class package oop05d; public class Person { private String name; private Employee employee; public Person(String name) { this.name = name; public void enlist( int salary ) { employee = new Employee( salary ); public String tostring( ) { String mesaj = name; if( employee!= null ) mesaj += " " + employee.getsalary( ); return private class Employee { private int salary; public Employee( int salary ) { this.salary = salary; public int getsalary() { return salary; public void setsalary(int salary) { this.salary = salary; 87 INNER CLASSES package oop05d; public class TestInnerClassViaOuterClass { public static void main(string[] args) { Person[] staff = new Person[3]; staff[0] = new Person( "Polat Alemdar" ); staff[0].enlist( ); staff[1] = new Person( "Memati Baş" ); staff[1].enlist( 7000 ); staff[2] = new Person( "Abdülhey Çoban" ); staff[2].enlist( 5000 ); for( Person insan: staff ) System.out.println( insan ); Obj. Or. Prog. #1 44

45 OBJECT ORIENTED PROGRAMMING LECTURE NOTES Assist. Prof. Dr. Yunus Emre SELÇUK INTRODUCTION TO MULTITHREADING 89 INTRODUCTION TO MULTITHREADING Multitasking, multiple processes and multithreading: Multitasking is the ability to have more than one program working at the same time. Nowadays, you are likely to have a computer with its CPU having multiple cores. Each core can execute one or more tasks, i.e. processes, depending on the CPU architecture. A process can sometimes be divided into threads that may run in parallel, i.e. concurrently running sub-processes. If there are enough hardware resources, i.e. cores, the time it takes to complete a process will drop significantly. However, this increase in the performance will not be in the order of the available cores. The concurrently running threads will sooner or later need to synchonize with each other. Moreover, creating a process or a thread takes some execution time as well. I have done significant simplifications while giving you this introduction! Obj. Or. Prog. #1 45

46 INTRODUCTION TO MULTITHREADING A state diagram showing the possible states of a thread and transitions between those states: new new start scheduler runnable yield, time slice notify, notifyall, IO complete, sleep expired, join complete terminate running IO, sleep, wait, join blocked dead 91 INTRODUCTION TO MULTITHREADING How should a thread wait? If a thread is unable to continue its task because of an obstacle, that thread should wait until the obstacle has been removed. Obstacle: The needed information has not arrived from: the network, another thread, the user, etc. You should not do busy waiting, i.e. executing dummy instructions such as running empty loops for times. Instead, you should put that thread into the blocked state by using the sleep command. A sleeping thread, unlike a busy waiting one, does not consume system resources. A sleeping thread is at risk of becoming unable to awake. You must catch the java.lang.interruptedexception, which is a checked exception Obj. Or. Prog. #1 46

47 INTRODUCTION TO MULTITHREADING Procedure for running a task in a separate thread: 1. Place the code for the task into the run method of a class that implements the Runnable interface. 2. Create an object of your class 3. Create a Thread object from the Runnable 4. Start the thread by using Thread.start method (do not call the run method directly) Let s make a demonstration with a nonsense application about people watching a match: Each person will shout for the team they support when he or she becomes excited. There is a possibility for each person to become excited in ms. Each person become exhausted after shouting 10 times. 93 package oop06a; import java.util.random; INTRODUCTION TO MULTITHREADING public class SoccerFan implements Runnable { public final static int STEPS = 10; public final static int DELAY = 1000; private String teamname, shoutphrase; public SoccerFan( String teamname, String shoutphrase ) { this.teamname = teamname; this.shoutphrase = shoutphrase; public void run() { Random generator = new Random(); try { for( int i = 0; i < STEPS; i++ ) { System.out.println( teamname + " " + shoutphrase ); Thread.sleep( generator.nextint(delay) ); catch (InterruptedException e) { e.printstacktrace(); Obj. Or. Prog. #1 47

48 package oop06a; INTRODUCTION TO MULTITHREADING public class Match { public static void main(string[] args) { Thread athread; athread = new Thread( new SoccerFan("G.S.", "Rulez!") ); athread.start( ); athread = new Thread( new SoccerFan("G.S.", "is the champ!") ); athread.start( ); athread = new Thread( new SoccerFan("F.B.", "is no.1!") ); athread.start( ); athread = new Thread( new SoccerFan("F.B.", "is the best!") ); athread.start( ); 95 INTRODUCTION TO MULTITHREADING Thread pools: Running a small number of tasks in separate threads is acceptable. But do not forget that actual processing units in a typical CPU is rather low, and creating a thread has also a processing cost. Therefore, if you are to execute a large number of tasks, you should use a thread pool instead. Java provides the following interfaces and classes for this purpose: Obj. Or. Prog. #1 48

49 INTRODUCTION TO MULTITHREADING java.util.concurrent.executorservice: public void shutdown( ) : Shuts down the executor, but allows the tasks currently in the pool to be completed. New threads are not accepted to the pool. public List<Runnable> shutdownnow( ) Shuts down immediately, stops the unfinished threads and returns them in a list. public boolean isshutdown( ): Returns true if the executor is shut down. public boolean isterminated( ): Returns true if all the tasks in the pool are terminated. Can be used in the main method for waiting the threads to be finished: 97 INTRODUCTION TO MULTITHREADING java.util.concurrent.executor: public void execute( Runnable object ): Executes the given task java.util.concurrent.executors: public static ExecutorService newfixedthreadpool( nthreads : int ) Creates a thread pool that reuses a fixed number of threads public static ExecutorService newcachedthreadpool( ) Creates a thread pool that creates new threads as needed, but will reuse previously constructed threads when they are available Obj. Or. Prog. #1 49

50 INTRODUCTION TO MULTITHREADING Let's modify our previous example to be run in a pool. The SoccerFan class will not be changed. Try using a fixed pool with different sizes! package oop06a; import java.util.concurrent.*; public class MatchWithPool { public static void main(string[] args) { ExecutorService pool = Executors.newCachedThreadPool( ); pool.execute( new SoccerFan("G.S.", "Rulez!") ); pool.execute( new SoccerFan("G.S.", "is the champ!") ); pool.execute( new SoccerFan("F.B.", "is no.1!") ); pool.execute( new SoccerFan("F.B.", "is the best!") ); pool.shutdown( ); 99 INTRODUCTION TO MULTITHREADING Race condition: In most practical multithreaded applications, two or more threads need to share access to the same data. What happens if two threads have access to the same object and each calls a method that modifies the state of the object? As you might imagine, the threads can step on each other s toes! Depending on the order in which the data were accessed, corrupted objects can result. Such a situation is often called a race condition Obj. Or. Prog. #1 50

51 INTRODUCTION TO MULTITHREADING Thread synchronization is needed to avoid race conditions. Consider the following example: This class diagram is descriptive enough, however, let s write the code and execute it. 101 INTRODUCTION TO MULTITHREADING package oop06b; public class Account { private double balance; public Account(double balance) { this.balance = balance; public double getbalance() { return balance; public void withdraw( double amt ){ double curbal = getbalance(); possibledelay( ); balance = curbal - amt; public void deposit( double amt ){ double curbal = getbalance(); possibledelay( ); balance = curbal + amt; private void possibledelay( ) { try { Thread.sleep(5); catch (InterruptedException e) { e.printstacktrace(); Obj. Or. Prog. #1 51

52 INTRODUCTION TO MULTITHREADING package oop06b; public class AccountDepositer implements Runnable { private Account account; private double amount; public AccountDepositer(Account account, double amount) { this.account = account; this.amount = amount; public void run() { account.deposit(amount); package oop06b; public class AccountWithdrawer implements Runnable { private Account account; private double amount; public AccountWithdrawer(Account account, double amount) { this.account = account; this.amount = amount; public void run() { account.withdraw(amount); 103 INTRODUCTION TO MULTITHREADING package oop06b; import java.util.concurrent.*; public class BankSimulation { public static void main(string[] args) { Account anaccount = new Account(0); System.out.println("Before: "+anaccount.getbalance()); ExecutorService executor = Executors.newCachedThreadPool( ); for( int i = 0; i < 100; i++ ) { AccountDepositer task=new AccountDepositer(anAccount,1); executor.execute(task); for( int i = 0; i < 50; i++ ) { AccountWithdrawer task=new AccountWithdrawer(anAccount,1); executor.execute(task); executor.shutdown(); while(!executor.isterminated() ); System.out.println("After: "+anaccount.getbalance()); What did you expect? What did you get? Obj. Or. Prog. #1 52

53 INTRODUCTION TO MULTITHREADING What has actually happened if two threads tried to withdraw from a BankAccount at the same time? *note: each thread has its own copy of local variables and parameters, but fields are shared between threads alice Client acct BankAcct balance alice s copy public of class BankAccount public class { private int balance; curbal: 1000 AccountWithdrawer implements Runnable public void withdraw( int amt ) {... { public void run() int curbal = getbalance(); { // possible delay acct.withdraw( 100 ); balance = curbal - amt; balance = = 900 bob s copy of curbal: 1000 balance = = 950 bob Client acct public class AccountWithdrawer implements Runnable {... public void run() { acct.withdraw( 50 ); 105 INTRODUCTION TO MULTITHREADING How can we prevent such a race? We determine the methods which can lead to a race and label them with the keyword synchronized. Only one thread can execute a synchronized mehod, others wait. package oop06c; public class Account { private double balance; public Account(double balance) { this.balance = balance; public synchronized void withdraw( double amt ) { double curbal = getbalance(); possibledelay( ); balance = curbal - amt; public synchronized void deposit( double amt ) { double curbal = getbalance(); possibledelay( ); balance = curbal + amt; public double getbalance() { return balance; public void possibledelay( ) { /*same as the previous one */ Obj. Or. Prog. #1 53

54 Other classes stay the same. Output: Before: 0.0 After: 50.0 INTRODUCTION TO MULTITHREADING Obj. Or. Prog. #1 54

55 OBJECT ORIENTED PROG., Section 1, CLASSROOM EXERCISE Answer these questions according to the UML class schema given above. You may need to extract hidden information from the schema and add necessary code while answering the questions. Question 1: Write the source code of class Pet. Question 2: Write the source code of class Cat or Dog. When a pet is passed to a thread, it prints out something such as: Meaow! (Garfield) Question 3: Write the source code of class DuplicateInformation. Question 4: Write the source code of class Person. Details of the methods of this class are as follows: addpet( Pet ): This method adds the given pet among others. The same pet should not be added and two pets with the same should not exist. activatepets( ): This method executes the pets in a thread pool. savepets( ): This method saves the pets to a file. If the pets are currently active, it must wait for the threads to be completed. loadpets( ): This method loads the pets from a file. If there are currently active pets, it must wait for the threads to be completed. public abstract class Pet implements Runnable, java.io.serializable { private static final long serialversionuid = 1L; private String name; public Pet(String name) { this.name = name; public String getname() { return name; public class Cat extends Pet { private static final long serialversionuid = 1L; public Cat(String name) { super(name); public void run() { System.out.println("(" + getname() + "): Meaow!"); import java.io.*; public class DuplicateInformation extends IOException { public DuplicateInformation( String msg ) { super(msg);

56 import java.util.*; import java.util.concurrent.*; import java.io.*; public class Person { private String name; private LinkedList<Pet> pets; private ExecutorService pool; public Person(String name) { this.name = name; pets = new LinkedList<Pet>(); pool = Executors.newCachedThreadPool( ); public Pet searchpet( String petname ) { for( Pet pet : pets ) if( pet.getname().equalsignorecase(petname) ) return pet; return null; public boolean searchpet( Pet apet ) { for( Pet pet : pets ) if( pet == apet ) return true; return false; public void addpet( Pet apet ) throws DuplicateInformation { if( searchpet(apet) == true ) throw new DuplicateInformation("Pet already exists!"); if( searchpet(apet.getname() )!= null ) throw new DuplicateInformation("Pet with the name " + apet.getname() + "already exists!"); pets.add(apet); //no else is necessary. See Main. public void activatepets( ) { for( Pet pet : pets ) { pool.execute(pet); public String getname() { return name; public void savepets( ) { while(!pool.isterminated() ); try { ObjectOutputStream stream = new ObjectOutputStream( new FileOutputStream(name+"sPets.dat") ); stream.writeobject(pets); stream.close(); catch (IOException e) { e.printstacktrace(); public void loadpets( ) { while(!pool.isterminated() ); try { ObjectInputStream stream = new ObjectInputStream( new FileInputStream(name+"sPets.dat") ); pets = (LinkedList<Pet>) stream.readobject( ); stream.close(); catch (IOException e) { e.printstacktrace(); catch (ClassNotFoundException e) { e.printstacktrace();

57 package oop07; public class Main { public static void main(string[] args) { Person jon = new Person("Jon Arbuckle"); Cat garfield = new Cat("Garfield"); try { jon.addpet(garfield); jon.addpet(garfield); catch (DuplicateInformation e) { e.printstacktrace(); System.out.println("What happens after exception?"); jon.activatepets();

58 OBJECT ORIENTED PROGRAMMING LECTURE NOTES Assist. Prof. Dr. Yunus Emre SELÇUK Part I Frames and Panels 1 General information: GUI editors in Java are not as easy to use as Microsoft's programming environments. Learning curve of GUI operations in Java is rather steep. Built-in GUI packages in Java are: The java.awt package: It has become obsolote The javax.swing package: Current one since Java 1.2 Based on classes in java.awt. Class names begin with J javax.swing.jframe java.awt.frame Don't forget the J! There are other 3rd party packages as well such as SWT of the eclipse foundation not to be covered in this course 2 OOP-08 1

59 General architecture of the Swing framework is based on the Model-View- Controller (MVC) design pattern. What is a design pattern? It is a general reusable solution to a commonly occurring problem within a given context in software design. A design pattern is not a finished design that can be transformed directly into code. It can rather be seen as a template for leading you to a "good" design. What is MVC? Model class: Represents raw information (data) View class: Represents different representations of the data Controller class: Receives user commands and handles them by reading and/or modifying data For more information, please refer to the classic GoF book and others. 3 Creating a basic window: The class javax.swing.jframe represents a basic window. Create your own windows by inheriting from this class. package oop08; import public class SimpleWindow extends JFrame { public static final int DEFAULT_WIDTH = 300; public static final int DEFAULT_HEIGHT = 200; public SimpleWindow( ) { setsize( DEFAULT_WIDTH, DEFAULT_HEIGHT ); public static void main(string[] args) { SimpleWindow window = new SimpleWindow( ); window.settitle("a Simple Window"); window.setdefaultcloseoperation(jframe.exit_on_close); window.setvisible(true); 4 OOP-08 2

60 What have we just done? We must set the size of the window in its constructor or in the main method by using the setsize( int width, int height ) method. Otherwise, its size will be 0 by 0! We must show the window by using the setvisible( boolean isvisible ) method. Otherwise, it will not be shown in the screen. We can set it's title by using the settitle( String title ) method. We must use setdefaultcloseoperation(jframe.exit_on_close) Otherwise the program will continue to execute (check the red stop button in eclipse) 5 Frames and Panels: The frame contains a top-level panel for you to put contents in it. Hence its named the content panel. A panel can contain other panels as well. This opens up some possibilities in layout organization and code reuse. The inheritance tree is shown on the left. 6 OOP-08 3

61 Some methods of the java.awt.frame class and its super classes: void setresizable(boolean resizable) void setextendedstate(int state): Sets the windows state into one of the following: Frame.NORMAL Frame.ICONIFIED Frame.MAXIMIZED_BOTH Frame.MAXIMIZED_HORIZ Frame.MAXIMIZED_VERT int getextendedstate( ) returns a value from the range above void setcontentpane( Container apanel ) Alternatively as of JSE 1.5, you call the add( Component ) method of the frame and it will be automatically added into the content pane. java.awt.component.repaint( ) Used for forcing the system to reflect the results of our drawing and adding operations to the screen as soon as possible. java.awt.window.setlocation( int posx, int posy ) Put the window wherever we want 7 Creating a better window: We should better give the window a size proportional to the screen resolution and locate it in a more strategic position. Let the size of the window to be exactly half of the screen and put it at the middle of the screen. In the meantime, let's give the window an icon. We will need to deal with the java.awt.toolkit class in order to accomplish these tasks. 8 OOP-08 4

62 Getting a Toolkit instance and learning the screen size: Toolkit kit = Toolkit.getDefaultToolkit(); Dimension screensize = kit.getscreensize(); int screenheight = screensize.height; int screenwidth = screensize.width; Loading an image and designating it as an icon: Image img = kit.getimage("icon.jpg"); seticonimage(img); Regarding to the relative location of the image: Put in the project directory if working with an IDE 9 Putting them alltogether: package oop08; import java.awt.*; import public class SizedWindowWithIcon extends JFrame { public SizedWindowWithIcon( ) { Toolkit kit = Toolkit.getDefaultToolkit(); Dimension screensize = kit.getscreensize(); int screenheight = screensize.height; int screenwidth = screensize.width; setsize(screenwidth / 2, screenheight / 2); setlocation(screensize.width / 4, screensize.height / 4); Image img = kit.getimage("icon.jpg"); seticonimage(img); settitle("a Sized Window With Icon"); public static void main(string[] args) { SizedWindowWithIcon window = new SizedWindowWithIcon( ); window.setvisible(true); window.setdefaultcloseoperation(jframe.exit_on_close); 10 OOP-08 5

63 The correct way to initialize Swing: Swing components are rather complex, therefore we need to initialize GUI components in a separate thread. This should be done from the event dispatch thread. i.e., the thread of control that passes events such as mouse clicks and keystrokes to the user interface components. Here is the code fragment used for this purpose: EventQueue.invokeLater(new Runnable() { public void run() { /* statements */ ); Now, what was that? We have just created an anonymous inner class which implements the Runnable interface. You can omit this magic code and go ahead as our previous examples and everything can go normal, but better be safe than sorry. 11 Drawing something into the panel: You cannot draw into the frame directly, you draw into its top-level panel. You should create a panel by inheriting from JPanel and overriding its paintcomponent method. Moreover, a panel is responsible from painting all components inside it. The easiest way to do this is by calling the super.paintcomponent method as the first command in the paintcomponent method. Drawing is done by using the parameter of type Graphics. Displaying text is considered a special kind of drawing. The Graphics class has a drawstring method for this purpose: g.drawstring( String text, int xpos, int ypos ) class NotHelloWorldPanel extends JPanel { public void paintcomponent(graphics g) { super.paintcomponent(g); g.drawstring("not a Hello, World program", 75, 100); 12 OOP-08 6

64 Putting them alltogether: package oop08; import javax.swing.*; import public class NotHelloWorld { public static void main(string[] args) { EventQueue.invokeLater(new Runnable() { public void run() { NotHelloWorldFrame frame = new NotHelloWorldFrame(); frame.setdefaultcloseoperation(jframe.exit_on_close); frame.setvisible(true); ); //to be continued in the next slide 13 Putting them alltogether (cont'd): //A frame that contains a message panel class NotHelloWorldFrame extends JFrame { public NotHelloWorldFrame(){ settitle("nothelloworld"); setsize(300, 200); NotHelloWorldPanel panel = new NotHelloWorldPanel(); add(panel); //A component that displays a message. class NotHelloWorldPanel extends JPanel { public void paintcomponent(graphics g){ super.paintcomponent(g); g.drawstring("not a Hello, World program", 60, 80); PS: We have coded all classes in NotHelloWord.java 14 OOP-08 7

65 Handcoding coordinates of the text is somewhat awkward Those who need to learn more about fonts, font metrics and details of working with 2D objects such as lines, rectangles, etc. can refer to the rest of the Section 7 of Core Java Vol.I We will proceed by learning how to react user input in the next week OBJECT ORIENTED PROGRAMMING LECTURE NOTES Assist. Prof. Dr. Yunus Emre SELÇUK Part II Event Handling 16 OOP-08 8

66 The examples in the previous section do not interact with user. We need to take input from the user by means of graphical controls such as text boxes, buttons, etc. But before that, we need to know about events and how to process them. All operating systems (OS) with GUI support work in terms of events and actions. Each movement of the mouse, each click, each key press and release, is an event. Whenever an event occurs, someone should make an action. The OS catches all events and make and action. Moreover, OS lets programming languages to intervene, i.e. it lets us to handle those events. Different programming languages have different approaches for event handling. 17 Event handling with Java: Different types of event sources create different types of events. GUI components such as JButton, JCheckBox, etc. OS itself: Mouse and keyboard events, etc. Event listeners listen to events of their preference. Listeners should implement sub-interfaces of java.util.eventlistener interface which are in java.awt.event package. Code for handling events are written in the method(s) defined in those interfaces. Programmer relates event sources with event listeners. The general format is: eventsourceobj.addeventnamelistener(alistenerobj); 18 OOP-08 9

67 Relating event sources with event listeners: Listeners of GUI events are associated with the GUI objects which is the source of that event. Listeners of OS events are associated with JFrame or JPanel objects. There can be *..* relation between event sources and listeners, but 1..* is suggested. 19 Events needed frequently ActionEvent AdjustmentEvent FocusEvent ItemEvent KeyEvent MouseEvent MouseWheelEvent WindowEvent and their listeners ActionListener AdjustmentListener FocusListener ItemListener KeyListener MouseListener MouseWheelListener WindowListener WindowFocusListener WindowStateListener All events and interfaces are within the java.awt.event package. 20 OOP-08 10

68 A working example of handling GUI events: Event source: A button object of type javax.swing.jbutton Event type: Button click Event listener interface: ActionListener Event class: ActionEvent Event handling method: void actionperformed(actionevent e) What to do: Create a window with three buttons, each having a color name as their caption. Change the background of the panel to appropriate color when a button is pressed. Code: oop09.buttontest 21 package oop09; import java.awt.*; import java.awt.event.*; import javax.swing.*; public class ButtonTest { public static void main(string[] args) { EventQueue.invokeLater(new Runnable() { public void run() { ButtonFrame frame = new ButtonFrame(); frame.setdefaultcloseoperation(jframe.exit_on_close); frame.setvisible(true); ); 22 OOP-08 11

69 class ButtonFrame extends JFrame { private JPanel buttonpanel; public static final int DEFAULT_WIDTH = 300; public static final int DEFAULT_HEIGHT = 200; public ButtonFrame() { settitle("buttontest"); setsize(default_width, DEFAULT_HEIGHT); // create buttons JButton yellowbutton = new JButton("Yellow"); JButton bluebutton = new JButton("Blue"); JButton redbutton = new JButton("Red"); buttonpanel = new JPanel(); // add buttons to panel buttonpanel.add(yellowbutton); buttonpanel.add(bluebutton); buttonpanel.add(redbutton); //continues in the next slide 23 // add panel to frame add(buttonpanel); // create button actions ColorAction yellowaction = new ColorAction(Color.YELLOW); ColorAction blueaction = new ColorAction(Color.BLUE); ColorAction redaction = new ColorAction(Color.RED); // associate actions with buttons yellowbutton.addactionlistener(yellowaction); bluebutton.addactionlistener(blueaction); redbutton.addactionlistener(redaction); //end of ButtonFrame constructor. //An action listener that sets the panel's background color. private class ColorAction implements ActionListener { private Color backgroundcolor; public ColorAction(Color c){ backgroundcolor = c; public void actionperformed(actionevent event){ buttonpanel.setbackground(backgroundcolor); /* coded as an inner class. You can write an alternative version with regular classes (ButtonTestV2) */ 24 OOP-08 12

70 A working example of handling Window events: Code: oop09.windoweventtest The WindowListener and WindowStateListener interfaces has been implemented package oop09; import java.awt.eventqueue; import java.awt.event.*; import javax.swing.*; public class WindowEventTest { public static void main(string[] args) { EventQueue.invokeLater(new Runnable() { public void run() { CaptureWindowEventsFrame frame = new CaptureWindowEventsFrame(); frame.setvisible(true); ); //continues in the next slide. 25 class CaptureWindowEventsFrame extends JFrame { private static final long serialversionuid = 1L; public static final int DEFAULT_WIDTH = 300; public static final int DEFAULT_HEIGHT = 200; public CaptureWindowEventsFrame(){ settitle("capturewindoweventstest"); setsize(default_width, DEFAULT_HEIGHT); addwindowlistener( new MyWindowListener( ) ); addwindowstatelistener( new MyWindowStateListener( ) ); //continues in the next slide. 26 OOP-08 13

71 class MyWindowListener implements WindowListener { public void windowopened(windowevent e) { System.out.println("Window has been opened"); public void windowclosing(windowevent e) { System.out.println("Window is to be closed"); public void windowclosed(windowevent e) { System.out.println("Window is closed"); //Bunu yazmadı! public void windowactivated(windowevent e) { System.out.println("Window has gained focus"); public void windowdeactivated(windowevent e) { System.out.println("Window has lost the focus"); public void windowiconified(windowevent e) { System.out.println("Window is minimized"); public void windowdeiconified(windowevent e) { System.out.println("Window is de-minimized"); //continues in the next slide. 27 /** * Meaning of returns from WindowEvent.getOldState() * and WindowEvent.getNewState() methods: * Frame.NORMAL (0), Frame.ICONIFIED (1), * Frame.MAXIMIZED_HORIZ (4), Frame.MAXIMIZED_VERT (2), * Frame.MAXIMIZED_BOTH (6=4+2) */ class MyWindowStateListener implements WindowStateListener { public void windowstatechanged( WindowEvent e ) { System.out.print( "Old state: " + e.getoldstate() ); System.out.println( ", New state: " + e.getnewstate() ); 28 OOP-08 14

72 About adapter classes: Remember the MyWindowListener class implementing WindowListener. It has 7 methods corresponding to 7 events. What if you need to handle just 1 event? In this case, create your listener class by inheriting from java.awt.event.windowadapter class. This class has default implementations for all events. You just override the method you need. Check out this adapter: package oop09; import java.awt.event.*; class MyWindowAdapter extends WindowAdapter { public void windowactivated(windowevent e) { System.out.println("Window has gained focus"); public void windowdeactivated(windowevent e) { System.out.println("Window has lost the focus"); 29 About adapter classes (cont'd): Now we can create WindowEventTestV2 using the newly created adapter as a classroom exercise. There are other adapters as well. Those are left for you to explore. 30 OOP-08 15

73 Events are divided into two groups: High-level (Logical) events: These purpose of these events is to initiate a process related to business logic. Clicking a button, resizing a window, advancing the scroll bar, etc. Low-level events: Keyboard and mouse events are of this type. These come together and constitute high-level events. For example, in order to click a button: Move the mouse on top of the button. Press the left mouse button. Release the left mouse button. 31 Handling keyboard events: Done via KeyListener interface or KeyAdapter class. Right and left Shift/Control/Alt/AltGr keys are special keys. You may need to control whether a key is pressed with a special key or not. Pressing c is not the same as pressing CTRL-C Example: oop09.keyboardeventstest import java.awt.*; import javax.swing.*; import java.awt.event.*; public class KeyboardEventsTest { public static void main(string[] args) { EventQueue.invokeLater(new Runnable() { public void run() { CaptureKeyboardEventsFrame frame = new CaptureKeyboardEventsFrame(); frame.setvisible(true); ); 32 OOP-08 16

74 class CaptureKeyboardEventsFrame extends JFrame { public static final int DEFAULT_WIDTH = 300; public static final int DEFAULT_HEIGHT = 200; public CaptureKeyboardEventsFrame(){ settitle("capturekeyboardeventstest"); setsize(default_width, DEFAULT_HEIGHT); addkeylistener(new SpecialKeyHandler() ); addkeylistener(new KeyHandler() ); Notice that we have associated listeners with the frame. Listeners can also be associated with panels, but this is rather tricky and not covered here. 33 class KeyHandler implements KeyListener { int lastkey; char lastchar; static String keytext; public void keypressed(keyevent event) { int keycode = event.getkeycode(); if( keycode!= lastkey) { System.out.print( "Key pressed, code: " + keycode ); lastkey = keycode; public void keyreleased(keyevent event) { int keycode = event.getkeycode(); System.out.println( "\nkey released, logical code: " + KeyEvent.getKeyText(keyCode) ); public void keytyped(keyevent event) { char keychar = event.getkeychar(); if( keychar!= lastchar ) { System.out.print( "\nkey typed: " + keychar ); lastchar = keychar; else System.out.print( keychar ); 34 OOP-08 17

75 class SpecialKeyHandler extends KeyAdapter { public void keytyped(keyevent event) { if( event.isshiftdown() ) System.out.print("***Shift key is used***"); if( event.iscontroldown() ) System.out.print("***Control key is used***"); if( event.isaltdown() ) System.out.print("***Alt key is used***"); if( event.isaltgraphdown() ) System.out.print("***AltGR key is used***"); if( event.ismetadown() ) System.out.print("***Meta key is used***"); 35 Handling mouse events: Pressing the buttons of the mouse and moving the mouse are handled via different listeners. Clicks are handled via MouseListener interface or MouseAdapter class. Movements are handled via MouseMotionListener interface or MouseMotionAdapter class Meanwhile, pressing of special keyboard keys can also be checked. Example: oop09.mouseeventstest package oop09; import java.awt.*; import javax.swing.*; import java.awt.event.*; public class MouseEventsTest { public static void main(string[] args) { EventQueue.invokeLater(new Runnable() { public void run() { CaptureMouseEventsFrame frame = new CaptureMouseEventsFrame(); frame.setvisible(true); ); 36 OOP-08 18

76 class CaptureMouseEventsFrame extends JFrame { public static final int DEFAULT_WIDTH = 300; public static final int DEFAULT_HEIGHT = 200; public CaptureMouseEventsFrame(){ settitle("capturemouseeventstest"); setsize(default_width, DEFAULT_HEIGHT); addmouselistener( new MouseHandler() ); addmousemotionlistener( new MouseMotionHandler() ); class MouseMotionHandler implements MouseMotionListener { public void mousedragged(mouseevent event) { double x,y; x = event.getpoint().getx(); y = event.getpoint().gety(); System.out.println("A mouse drag at ("+x+","+y+")"); public void mousemoved(mouseevent event) { double x,y; x = event.getpoint().getx(); y = event.getpoint().gety(); System.out.println("A mouse move at ("+x+","+y+")"); 37 class MouseHandler extends MouseAdapter { public void mouseclicked(mouseevent event) { double x,y;int z, e; x = event.getpoint().getx(); y = event.getpoint().gety(); z = event.getclickcount(); e = event.getmodifiersex(); System.out.println("A mouse click at ("+x+","+y+")x"+z); if( ( e & InputEvent.BUTTON1_DOWN_MASK)!= 0 ) System.out.println("This was a left-click."); if( (e & InputEvent.BUTTON3_DOWN_MASK)!= 0 ) System.out.println("This was a right-click."); if( (e & InputEvent.BUTTON2_DOWN_MASK)!= 0 ) System.out.println("This was a middle-click."); if( (e & InputEvent.SHIFT_DOWN_MASK)!= 0 ) System.out.println("The shift key was also pressed"); if( (e & InputEvent.CTRL_DOWN_MASK)!= 0 ) System.out.println("The control key was also pressed"); if( (e & InputEvent.ALT_DOWN_MASK)!= 0 ) System.out.println("The alt key was also pressed."); if( (e & InputEvent.ALT_GRAPH_DOWN_MASK)!= 0 ) System.out.println("The altgr key was also pressed."); if( (e & InputEvent.META_DOWN_MASK)!= 0 ) System.out.println("The meta key was also pressed."); System.out.println("Summary of mods in click: " + InputEvent.getModifiersExText(e); 38 OOP-08 19

77 OBJECT ORIENTED PROGRAMMING LECTURE NOTES Assist. Prof. Dr. Yunus Emre SELÇUK Part III Layout Management 39 LAYOUT MANAGEMENT You can determine the positions of components in panel by using layout managers. The java.awt package includes various layout managers, each having different rules and therefore answering to different needs. We will examine some of those layout managers this week. General usage: Assign a layout manager to a panel by using the Container.setLayout method Add a GUI component to the panel by using the Container.add( acomponent, layoutrule ) method. By adding child panels into a parent and using different layout managers, you can fulfill complex layout requirements. 40 OOP-08 20

78 FLOW LAYOUT: FlowLayout is the default layout manager Adds components horizontally next to each other as long as there is enough space. Advances to next line when no place is left Example: oop10.layout01flowlayout Same as the previous button example except the use of the layout manager. 41 package oop10; import java.awt.*; import java.awt.event.*; import javax.swing.*; /** * FlowLayout manager lines the components horizontally until * there is no room and then starts a new row of components. */ public class Layout01FlowLayout { public static void main(string[] args) { EventQueue.invokeLater(new Runnable() { public void run() { Frame01 frame = new Frame01(); frame.setdefaultcloseoperation(jframe.exit_on_close); frame.setvisible(true); ); 42 OOP-08 21

79 class Frame01 extends JFrame { private static final long serialversionuid = 1L; public static final int DEFAULT_WIDTH = 300; public static final int DEFAULT_HEIGHT = 200; public Frame01() { settitle("buttontest"); setsize(default_width, DEFAULT_HEIGHT); FlowLayoutPanel panel = new FlowLayoutPanel(); add(panel); 43 class FlowLayoutPanel extends Jpanel { public FlowLayoutPanel() { //Bileşenleri eklemeden önce setlayout kullan. setlayout(new FlowLayout(FlowLayout.RIGHT)); /*Alternatif değerler: * FlowLayout.LEFT * FlowLayout.CENTER (default), * FlowLayout.RIGHT *Alternatif kurucu: * FlowLayout(int align, int hgap, int vgap) * align: önceki değerler. * hgap: bileşenler arası yatay aralık. * vgap: dikey aralık. * Negatif aralıklar örtüşen bileşenlere sebep olur. * */ JButton yellowbutton = new JButton("Yellow"); JButton bluebutton = new JButton("Blue"); JButton redbutton = new JButton("Red"); 44 OOP-08 22

80 JButton yellowbutton = new JButton("Yellow"); JButton bluebutton = new JButton("Blue"); JButton redbutton = new JButton("Red"); add(yellowbutton); add(bluebutton); add(redbutton); ColorAction yellowaction = new ColorAction(Color.YELLOW); ColorAction blueaction = new ColorAction(Color.BLUE); ColorAction redaction = new ColorAction(Color.RED); yellowbutton.addactionlistener(yellowaction); bluebutton.addactionlistener(blueaction); redbutton.addactionlistener(redaction); 45 private class ColorAction implements ActionListener { private Color backgroundcolor; public ColorAction(Color c) { backgroundcolor = c; public void actionperformed(actionevent event) { setbackground(backgroundcolor); 46 OOP-08 23

81 BORDER LAYOUT Introduces 5 areas as layout rules: CENTER, EAST, WEST, NORTH, SOUTH This layout manager enlarges the component so that it covers the entire area. If we just need to position the component but not to enlarge it, we can put it in a panel with another layout manager and add that panel as a child of the first panel. Example: oop10.layout02borderlayout This example uses an inner class while the previous example uses a regular class in the same java file. We could also use a regular class in its own java file. The result does not matter. In order to show that the buttons work, the frame title is also changed in the button events. 47 package oop10; import java.awt.*; import java.awt.event.*; import javax.swing.*; /** * NORTH, SOUTH: Yükseklik sabit, genişlik pencere genişliği. * EAST, WEST: Yükseklik pencere yüksekliği, genişlik sabit. * CENTER: Diğer konumlardan geri kalan alanın tümü. */ public class Layout02BorderLayout extends JFrame { private static final long serialversionuid = 1L; public static final int DEFAULT_WIDTH = 300; public static final int DEFAULT_HEIGHT = 200; public Layout02BorderLayout() { settitle("buttontest"); setsize(default_width, DEFAULT_HEIGHT); BorderLayoutPanel panel = new BorderLayoutPanel(); add(panel); 48 OOP-08 24

82 public static void main(string[] args) { EventQueue.invokeLater(new Runnable() { public void run() { Layout02BorderLayout frame = new Layout02BorderLayout(); frame.setdefaultcloseoperation(jframe.exit_on_close); frame.setvisible(true); ); class BorderLayoutPanel extends JPanel { private static final long serialversionuid = 1L; public BorderLayoutPanel() { setlayout(new BorderLayout()); //veya BorderLayout( int hgap, int vgap ) JButton yellowbutton = new JButton("Yellow"); JButton bluebutton = new JButton("Blue"); JButton redbutton = new JButton("Red"); JButton greenbutton = new JButton("Green"); JButton whitebutton = new JButton("White"); 49 /* Renk değişikliği belli olsun istiyorsan * CENTER konumdakini remarkla. * Diğer konumlarda eleman * olmazsa o kısım hiç gösterilmiyor. */ add(yellowbutton, BorderLayout.WEST); add(bluebutton, BorderLayout.CENTER); add(redbutton, BorderLayout.EAST); add(greenbutton, BorderLayout.NORTH); add(whitebutton, BorderLayout.SOUTH); ColorAction yellowaction = new ColorAction(Color.YELLOW); ColorAction blueaction = new ColorAction(Color.BLUE); ColorAction redaction = new ColorAction(Color.RED); ColorAction greenaction = new ColorAction(Color.GREEN); ColorAction whiteaction = new ColorAction(Color.WHITE); yellowbutton.addactionlistener(yellowaction); bluebutton.addactionlistener(blueaction); redbutton.addactionlistener(redaction); greenbutton.addactionlistener(greenaction); whitebutton.addactionlistener(whiteaction); 50 OOP-08 25

83 private class ColorAction implements ActionListener { private Color backgroundcolor; public ColorAction(Color c) { backgroundcolor = c; public void actionperformed(actionevent event) { setbackground(backgroundcolor); settitle("buttontest: (" + backgroundcolor.getred() + "," + backgroundcolor.getgreen() + "," + backgroundcolor.getblue() + ")"); 51 GRID LAYOUT This layout manager divides the area into rows and columns, i.e. cells, of equal size. Components are extended to cover their cells. As the window is resized, the cells are resized as well. You cannot target a special row and column when adding components. Hint: You can leave a cell empty by adding an empty child panel into that cell. Example: oop10.layout03gridlayout 52 OOP-08 26

84 package oop10; import java.awt.*; import java.awt.event.*; import javax.swing.*; /** * Alanı satır ve sütunlara böler. Bileşenler eşit boyutta olur, * pencere büyüdükçe o oranda bileşenler de büyür. * Ortada biryerleri boş bırakmak istiyorsan oraya boş bir panel * eklemelisin. */ public class Layout03GridLayout { public static void main(string[] args) { EventQueue.invokeLater(new Runnable() { public void run() { Frame03 frame = new Frame03(); frame.setdefaultcloseoperation(jframe.exit_on_close); frame.setvisible(true); ); 53 class Frame03 extends JFrame { private static final long serialversionuid = 1L; public static final int DEFAULT_WIDTH = 300; public static final int DEFAULT_HEIGHT = 200; public Frame03() { settitle("buttontest"); setsize(default_width, DEFAULT_HEIGHT); GridLayoutPanel panel = new GridLayoutPanel(); add(panel); /* Pencere boyutunu içindeki bileşenlerin tercih * edilen veya varsayılan boyutlarını dikkate * alacak şekilde, layout manager kurallarına da * dikkat ederek yeniden boyutlandırır. * */ pack(); 54 OOP-08 27

85 class GridLayoutPanel extends JPanel { private static final long serialversionuid = 1L; public GridLayoutPanel() { setlayout(new GridLayout(2,2)); /* GridLayout( int satir, int sutun ); * GridLayout( int row, int col, int hgap, int vgap ); * */ JButton yellowbutton = new JButton("Yellow"); JButton bluebutton = new JButton("Blue"); JButton redbutton = new JButton("Red"); JButton greenbutton = new JButton("Green"); JButton whitebutton = new JButton("White"); add(yellowbutton); add(bluebutton); add(redbutton); add(greenbutton); add(whitebutton); 55 ColorAction yellowaction = new ColorAction(Color.YELLOW); ColorAction blueaction = new ColorAction(Color.BLUE); ColorAction redaction = new ColorAction(Color.RED); ColorAction greenaction = new ColorAction(Color.GREEN); ColorAction whiteaction = new ColorAction(Color.WHITE); yellowbutton.addactionlistener(yellowaction); bluebutton.addactionlistener(blueaction); redbutton.addactionlistener(redaction); greenbutton.addactionlistener(greenaction); whitebutton.addactionlistener(whiteaction); private class ColorAction implements ActionListener { private Color backgroundcolor; public ColorAction(Color c) { backgroundcolor = c; public void actionperformed(actionevent event) { setbackground(backgroundcolor); 56 OOP-08 28

86 GRIDBAG LAYOUT Using this layout manager is similar to designing HTML pages by using tables. Design the GUI on paper first, then divide it into rows and columns. Large components can extend multiple rows and/or columns. You can define constraints for individual cells: To enlarge or not to enlarge the component it contains. Alignment of the component within the cell (anchor) Padding value Red: Cell borders Green: Merged cells 57 GRIDBAG LAYOUT Best practice: GridBagLayout object is not used directly as its cumbersome to do so. We write a convenience class which models the constraints mentioned before and add the components with instances of that class. Our convenience class is named GBC. Example: oop10.layout04gridbaglayout Focus on layout at the moment, although you can see a preview of using some GUI components. 58 OOP-08 29

Fundamentals of Java Programming

Fundamentals of Java Programming Fundamentals of Java Programming This document is exclusive property of Cisco Systems, Inc. Permission is granted to print and copy this document for non-commercial distribution and exclusive use by instructors

More information

Java Interview Questions and Answers

Java Interview Questions and Answers 1. What is the most important feature of Java? Java is a platform independent language. 2. What do you mean by platform independence? Platform independence means that we can write and compile the java

More information

D06 PROGRAMMING with JAVA

D06 PROGRAMMING with JAVA Cicles Formatius de Grau Superior Desenvolupament d Aplicacions Informàtiques D06 PROGRAMMING with JAVA Ch16 Files and Streams PowerPoint presentation, created by Angel A. Juan - ajuanp(@)gmail.com, for

More information

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

The Sun Certified Associate for the Java Platform, Standard Edition, Exam Version 1.0 The following applies to all exams: Once exam vouchers are purchased you have up to one year from the date of purchase to use it. Each voucher is valid for one exam and may only be used at an Authorized

More information

Crash Course in Java

Crash Course in Java Crash Course in Java Based on notes from D. Hollinger Based in part on notes from J.J. Johns also: Java in a Nutshell Java Network Programming and Distributed Computing Netprog 2002 Java Intro 1 What is

More information

www.virtualians.pk CS506 Web Design and Development Solved Online Quiz No. 01 www.virtualians.pk

www.virtualians.pk CS506 Web Design and Development Solved Online Quiz No. 01 www.virtualians.pk CS506 Web Design and Development Solved Online Quiz No. 01 Which of the following is a general purpose container? JFrame Dialog JPanel JApplet Which of the following package needs to be import while handling

More information

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

CS 111 Classes I 1. Software Organization View to this point: CS 111 Classes I 1 Software Organization View to this point: Data Objects and primitive types Primitive types operators (+, /,,*, %). int, float, double, char, boolean Memory location holds the data Objects

More information

Java the UML Way: Integrating Object-Oriented Design and Programming

Java the UML Way: Integrating Object-Oriented Design and Programming Java the UML Way: Integrating Object-Oriented Design and Programming by Else Lervik and Vegard B. Havdal ISBN 0-470-84386-1 John Wiley & Sons, Ltd. Table of Contents Preface xi 1 Introduction 1 1.1 Preliminaries

More information

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

Free Java textbook available online. Introduction to the Java programming language. Compilation. A simple java program Free Java textbook available online "Thinking in Java" by Bruce Eckel, 4th edition, 2006, ISBN 0131872486, Pearson Education Introduction to the Java programming language CS 4354 Summer II 2015 The third

More information

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

Free Java textbook available online. Introduction to the Java programming language. Compilation. A simple java program Free Java textbook available online "Thinking in Java" by Bruce Eckel, 4th edition, 2006, ISBN 0131872486, Pearson Education Introduction to the Java programming language CS 4354 Summer II 2014 Jill Seaman

More information

Computer Programming I

Computer Programming I Computer Programming I COP 2210 Syllabus Spring Semester 2012 Instructor: Greg Shaw Office: ECS 313 (Engineering and Computer Science Bldg) Office Hours: Tuesday: 2:50 4:50, 7:45 8:30 Thursday: 2:50 4:50,

More information

AP Computer Science Java Subset

AP Computer Science Java Subset APPENDIX A AP Computer Science Java Subset The AP Java subset is intended to outline the features of Java that may appear on the AP Computer Science A Exam. The AP Java subset is NOT intended as an overall

More information

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

File class in Java. Scanner reminder. Files 10/19/2012. File Input and Output (Savitch, Chapter 10) File class in Java File Input and Output (Savitch, Chapter 10) TOPICS File Input Exception Handling File Output Programmers refer to input/output as "I/O". The File class represents files as objects. The

More information

Java Coding Practices for Improved Application Performance

Java Coding Practices for Improved Application Performance 1 Java Coding Practices for Improved Application Performance Lloyd Hagemo Senior Director Application Infrastructure Management Group Candle Corporation In the beginning, Java became the language of the

More information

CS 1302 Ch 19, Binary I/O

CS 1302 Ch 19, Binary I/O CS 1302 Ch 19, Binary I/O Sections Pages Review Questions Programming Exercises 19.1-19.4.1, 19.6-19.6 710-715, 724-729 Liang s Site any Sections 19.1 Introduction 1. An important part of programming is

More information

AP Computer Science A - Syllabus Overview of AP Computer Science A Computer Facilities

AP Computer Science A - Syllabus Overview of AP Computer Science A Computer Facilities AP Computer Science A - Syllabus Overview of AP Computer Science A Computer Facilities The classroom is set up like a traditional classroom on the left side of the room. This is where I will conduct my

More information

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

Basic Programming and PC Skills: Basic Programming and PC Skills: Texas University Interscholastic League Contest Event: Computer Science The contest challenges high school students to gain an understanding of the significance of computation as well as the details of

More information

java Features Version April 19, 2013 by Thorsten Kracht

java Features Version April 19, 2013 by Thorsten Kracht java Features Version April 19, 2013 by Thorsten Kracht Contents 1 Introduction 2 1.1 Hello World................................................ 2 2 Variables, Types 3 3 Input/Output 4 3.1 Standard I/O................................................

More information

Java SE 8 Programming

Java SE 8 Programming Oracle University Contact Us: 1.800.529.0165 Java SE 8 Programming Duration: 5 Days What you will learn This Java SE 8 Programming training covers the core language features and Application Programming

More information

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

Handout 1. Introduction to Java programming language. Java primitive types and operations. Reading keyboard Input using class Scanner. Handout 1 CS603 Object-Oriented Programming Fall 15 Page 1 of 11 Handout 1 Introduction to Java programming language. Java primitive types and operations. Reading keyboard Input using class Scanner. Java

More information

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

Chapter 20 Streams and Binary Input/Output. Big Java Early Objects by Cay Horstmann Copyright 2014 by John Wiley & Sons. All rights reserved. Chapter 20 Streams and Binary Input/Output Big Java Early Objects by Cay Horstmann Copyright 2014 by John Wiley & Sons. All rights reserved. 20.1 Readers, Writers, and Streams Two ways to store data: Text

More information

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

Introduction to Java Applications. 2005 Pearson Education, Inc. All rights reserved. 1 2 Introduction to Java Applications 2.2 First Program in Java: Printing a Line of Text 2 Application Executes when you use the java command to launch the Java Virtual Machine (JVM) Sample program Displays

More information

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

1.00 Lecture 1. Course information Course staff (TA, instructor names on syllabus/faq): 2 instructors, 4 TAs, 2 Lab TAs, graders 1.00 Lecture 1 Course Overview Introduction to Java Reading for next time: Big Java: 1.1-1.7 Course information Course staff (TA, instructor names on syllabus/faq): 2 instructors, 4 TAs, 2 Lab TAs, graders

More information

Building a Multi-Threaded Web Server

Building a Multi-Threaded Web Server Building a Multi-Threaded Web Server In this lab we will develop a Web server in two steps. In the end, you will have built a multi-threaded Web server that is capable of processing multiple simultaneous

More information

Introduction to Programming System Design. CSCI 455x (4 Units)

Introduction to Programming System Design. CSCI 455x (4 Units) Introduction to Programming System Design CSCI 455x (4 Units) Description This course covers programming in Java and C++. Topics include review of basic programming concepts such as control structures,

More information

Syllabus for CS 134 Java Programming

Syllabus for CS 134 Java Programming - Java Programming Syllabus Page 1 Syllabus for CS 134 Java Programming Computer Science Course Catalog 2000-2001: This course is an introduction to objectoriented programming using the Java language.

More information

Java Application Developer Certificate Program Competencies

Java Application Developer Certificate Program Competencies Java Application Developer Certificate Program Competencies After completing the following units, you will be able to: Basic Programming Logic Explain the steps involved in the program development cycle

More information

CS11 Java. Fall 2014-2015 Lecture 7

CS11 Java. Fall 2014-2015 Lecture 7 CS11 Java Fall 2014-2015 Lecture 7 Today s Topics! All about Java Threads! Some Lab 7 tips Java Threading Recap! A program can use multiple threads to do several things at once " A thread can have local

More information

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

Topics. Introduction. Java History CS 146. Introduction to Programming and Algorithms Module 1. Module Objectives Introduction to Programming and Algorithms Module 1 CS 146 Sam Houston State University Dr. Tim McGuire Module Objectives To understand: the necessity of programming, differences between hardware and software,

More information

Java from a C perspective. Plan

Java from a C perspective. Plan Java from a C perspective Cristian Bogdan 2D2052/ingint04 Plan Objectives and Book Packages and Classes Types and memory allocation Syntax and C-like Statements Object Orientation (minimal intro) Exceptions,

More information

INPUT AND OUTPUT STREAMS

INPUT AND OUTPUT STREAMS INPUT AND OUTPUT The Java Platform supports different kinds of information sources and information sinks. A program may get data from an information source which may be a file on disk, a network connection,

More information

13 File Output and Input

13 File Output and Input SCIENTIFIC PROGRAMMING -1 13 File Output and Input 13.1 Introduction To make programs really useful we have to be able to input and output data in large machinereadable amounts, in particular we have to

More information

An Overview of Java. overview-1

An Overview of Java. overview-1 An Overview of Java overview-1 Contents What is Java Major Java features Java virtual machine Java programming language Java class libraries (API) GUI Support in Java Networking and Threads in Java overview-2

More information

qwertyuiopasdfghjklzxcvbnmqwerty uiopasdfghjklzxcvbnmqwertyuiopasd fghjklzxcvbnmqwertyuiopasdfghjklzx cvbnmqwertyuiopasdfghjklzxcvbnmq

qwertyuiopasdfghjklzxcvbnmqwerty uiopasdfghjklzxcvbnmqwertyuiopasd fghjklzxcvbnmqwertyuiopasdfghjklzx cvbnmqwertyuiopasdfghjklzxcvbnmq qwertyuiopasdfghjklzxcvbnmqwerty uiopasdfghjklzxcvbnmqwertyuiopasd fghjklzxcvbnmqwertyuiopasdfghjklzx cvbnmqwertyuiopasdfghjklzxcvbnmq Introduction to Programming using Java wertyuiopasdfghjklzxcvbnmqwertyui

More information

Summit Public Schools Summit, New Jersey Grade Level / Content Area: Mathematics Length of Course: 1 Academic Year Curriculum: AP Computer Science A

Summit Public Schools Summit, New Jersey Grade Level / Content Area: Mathematics Length of Course: 1 Academic Year Curriculum: AP Computer Science A Summit Public Schools Summit, New Jersey Grade Level / Content Area: Mathematics Length of Course: 1 Academic Year Curriculum: AP Computer Science A Developed By Brian Weinfeld Course Description: AP Computer

More information

Java (12 Weeks) Introduction to Java Programming Language

Java (12 Weeks) Introduction to Java Programming Language Java (12 Weeks) Topic Lecture No. Introduction to Java Programming Language 1 An Introduction to Java o Java as a Programming Platform, The Java "White Paper" Buzzwords, Java and the Internet, A Short

More information

Software Engineering Techniques

Software Engineering Techniques Software Engineering Techniques Low level design issues for programming-in-the-large. Software Quality Design by contract Pre- and post conditions Class invariants Ten do Ten do nots Another type of summary

More information

AVRO - SERIALIZATION

AVRO - SERIALIZATION http://www.tutorialspoint.com/avro/avro_serialization.htm AVRO - SERIALIZATION Copyright tutorialspoint.com What is Serialization? Serialization is the process of translating data structures or objects

More information

PLV Goldstein 315, Tuesdays and Thursdays, 6:00PM-7:50PM. Tuesdays and Thursdays, 4:00PM-5:30PM and 7:50PM 9:30PM at PLV G320

PLV Goldstein 315, Tuesdays and Thursdays, 6:00PM-7:50PM. Tuesdays and Thursdays, 4:00PM-5:30PM and 7:50PM 9:30PM at PLV G320 CRN:22430/21519 Pace University Spring 2006 CS122/504 Computer Programming II Instructor Lectures Office Hours Dr. Lixin Tao, ltao@pace.edu, http://csis.pace.edu/~lixin Pleasantville Office: G320, (914)773-3449

More information

Creating a Simple, Multithreaded Chat System with Java

Creating a Simple, Multithreaded Chat System with Java Creating a Simple, Multithreaded Chat System with Java Introduction by George Crawford III In this edition of Objective Viewpoint, you will learn how to develop a simple chat system. The program will demonstrate

More information

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

Preet raj Core Java and Databases CS4PR. Time Allotted: 3 Hours. Final Exam: Total Possible Points 75 Preet raj Core Java and Databases CS4PR Time Allotted: 3 Hours Final Exam: Total Possible Points 75 Q1. What is difference between overloading and overriding? 10 points a) In overloading, there is a relationship

More information

CS193j, Stanford Handout #10 OOP 3

CS193j, Stanford Handout #10 OOP 3 CS193j, Stanford Handout #10 Summer, 2003 Manu Kumar OOP 3 Abstract Superclass Factor Common Code Up Several related classes with overlapping code Factor common code up into a common superclass Examples

More information

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

Chulalongkorn University International School of Engineering Department of Computer Engineering 2140105 Computer Programming Lab. Chulalongkorn University Name International School of Engineering Student ID Department of Computer Engineering Station No. 2140105 Computer Programming Lab. Date Lab 2 Using Java API documents, command

More information

Threads & Tasks: Executor Framework

Threads & Tasks: Executor Framework Threads & Tasks: Executor Framework Introduction & Motivation WebServer Executor Framework Callable and Future 12 April 2012 1 Threads & Tasks Motivations for using threads Actor-based Goal: Create an

More information

To Java SE 8, and Beyond (Plan B)

To Java SE 8, and Beyond (Plan B) 11-12-13 To Java SE 8, and Beyond (Plan B) Francisco Morero Peyrona EMEA Java Community Leader 8 9...2012 2020? Priorities for the Java Platforms Grow Developer Base Grow Adoption

More information

CS 2112 Spring 2014. 0 Instructions. Assignment 3 Data Structures and Web Filtering. 0.1 Grading. 0.2 Partners. 0.3 Restrictions

CS 2112 Spring 2014. 0 Instructions. Assignment 3 Data Structures and Web Filtering. 0.1 Grading. 0.2 Partners. 0.3 Restrictions CS 2112 Spring 2014 Assignment 3 Data Structures and Web Filtering Due: March 4, 2014 11:59 PM Implementing spam blacklists and web filters requires matching candidate domain names and URLs very rapidly

More information

Java CPD (I) Frans Coenen Department of Computer Science

Java CPD (I) Frans Coenen Department of Computer Science Java CPD (I) Frans Coenen Department of Computer Science Content Session 1, 12:45-14:30 (First Java Programme, Inheritance, Arithmetic) Session 2, 14:45-16:45 (Input and Programme Constructs) Materials

More information

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

First Java Programs. V. Paúl Pauca. CSC 111D Fall, 2015. Department of Computer Science Wake Forest University. Introduction to Computer Science First Java Programs V. Paúl Pauca Department of Computer Science Wake Forest University CSC 111D Fall, 2015 Hello World revisited / 8/23/15 The f i r s t o b l i g a t o r y Java program @author Paul Pauca

More information

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

java.util.scanner Here are some of the many features of Scanner objects. Some Features of java.util.scanner java.util.scanner java.util.scanner is a class in the Java API used to create a Scanner object, an extremely versatile object that you can use to input alphanumeric characters from several input sources

More information

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

CS 141: Introduction to (Java) Programming: Exam 1 Jenny Orr Willamette University Fall 2013 Oct 4, 2013, p 1 Name: CS 141: Introduction to (Java) Programming: Exam 1 Jenny Orr Willamette University Fall 2013 1. (max 18) 4. (max 16) 2. (max 12) 5. (max 12) 3. (max 24) 6. (max 18) Total: (max 100)

More information

API for java.util.iterator. ! hasnext() Are there more items in the list? ! next() Return the next item in the list.

API for java.util.iterator. ! hasnext() Are there more items in the list? ! next() Return the next item in the list. Sequences and Urns 2.7 Lists and Iterators Sequence. Ordered collection of items. Key operations. Insert an item, iterate over the items. Design challenge. Support iteration by client, without revealing

More information

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

The Java I/O System. Binary I/O streams (ascii, 8 bits) The decorator design pattern Character I/O streams (Unicode, 16 bits) Binary I/O streams (ascii, 8 bits) InputStream OutputStream The Java I/O System The decorator design pattern Character I/O streams (Unicode, 16 bits) Reader Writer Comparing Binary I/O to Character I/O

More information

ECE 122. Engineering Problem Solving with Java

ECE 122. Engineering Problem Solving with Java ECE 122 Engineering Problem Solving with Java Introduction to Electrical and Computer Engineering II Lecture 1 Course Overview Welcome! What is this class about? Java programming somewhat software somewhat

More information

Lecture J - Exceptions

Lecture J - Exceptions Lecture J - Exceptions Slide 1 of 107. Exceptions in Java Java uses the notion of exception for 3 related (but different) purposes: Errors: an internal Java implementation error was discovered E.g: out

More information

Lecture 7: Class design for security

Lecture 7: Class design for security Lecture topics Class design for security Visibility of classes, fields, and methods Implications of using inner classes Mutability Design for sending objects across JVMs (serialization) Visibility modifiers

More information

Using Files as Input/Output in Java 5.0 Applications

Using Files as Input/Output in Java 5.0 Applications Using Files as Input/Output in Java 5.0 Applications The goal of this module is to present enough information about files to allow you to write applications in Java that fetch their input from a file instead

More information

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

Explain the relationship between a class and an object. Which is general and which is specific? A.1.1 What is the Java Virtual Machine? Is it hardware or software? How does its role differ from that of the Java compiler? The Java Virtual Machine (JVM) is software that simulates the execution of a

More information

COMMUNITY COLLEGE OF CITY UNIVERSITY CITY UNIVERSITY OF HONG KONG

COMMUNITY COLLEGE OF CITY UNIVERSITY CITY UNIVERSITY OF HONG KONG COMMUNITY COLLEGE OF CITY UNIVERSITY CITY UNIVERSITY OF HONG KONG Information on a Course offered by Division of Applied Science and Technology Course Title: (English) Java Programming (Chinese) Course

More information

No no-argument constructor. No default constructor found

No no-argument constructor. No default constructor found Every software developer deals with bugs. The really tough bugs aren t detected by the compiler. Nasty bugs manifest themselves only when executed at runtime. Here is a list of the top ten difficult and

More information

Serialization in Java (Binary and XML)

Serialization in Java (Binary and XML) IOWA STATE UNIVERSITY Serialization in Java (Binary and XML) Kyle Woolcock ComS 430 4/4/2014 2 Table of Contents Introduction... 3 Why Serialize?... 3 How to Serialize... 3 Serializable Interface... 3

More information

Threads 1. When writing games you need to do more than one thing at once.

Threads 1. When writing games you need to do more than one thing at once. Threads 1 Threads Slide 1 When writing games you need to do more than one thing at once. Threads offer a way of automatically allowing more than one thing to happen at the same time. Java has threads as

More information

Java Programming Fundamentals

Java Programming Fundamentals Lecture 1 Part I Java Programming Fundamentals Topics in Quantitative Finance: Numerical Solutions of Partial Differential Equations Instructor: Iraj Kani Introduction to Java We start by making a few

More information

FILE I/O IN JAVA. Prof. Chris Jermaine cmj4@cs.rice.edu. Prof. Scott Rixner rixner@cs.rice.edu

FILE I/O IN JAVA. Prof. Chris Jermaine cmj4@cs.rice.edu. Prof. Scott Rixner rixner@cs.rice.edu FILE I/O IN JAVA Prof. Chris Jermaine cmj4@cs.rice.edu Prof. Scott Rixner rixner@cs.rice.edu 1 Our Simple Java Programs So Far Aside from screen I/O......when they are done, they are gone They have no

More information

What are exceptions? Bad things happen occasionally

What are exceptions? Bad things happen occasionally What are exceptions? Bad things happen occasionally arithmetic: 0, 9 environmental: no space, malformed input undetectable: subscript out of range, value does not meet prescribed constraint application:

More information

Java Programming Language

Java Programming Language Lecture 1 Part II Java Programming Language Additional Features and Constructs Topics in Quantitative Finance: Numerical Solutions of Partial Differential Equations Instructor: Iraj Kani Subclasses and

More information

CSC 551: Web Programming. Fall 2001

CSC 551: Web Programming. Fall 2001 CSC 551: Web Programming Fall 2001 Java Overview! Design goals & features "platform independence, portable, secure, simple, object-oriented,! Language overview " program structure, public vs. private "instance

More information

OBJECT ORIENTED PROGRAMMING LANGUAGE

OBJECT ORIENTED PROGRAMMING LANGUAGE UNIT-6 (MULTI THREADING) Multi Threading: Java Language Classes The java.lang package contains the collection of base types (language types) that are always imported into any given compilation unit. This

More information

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

UIL Computer Science for Dummies by Jake Warren and works from Mr. Fleming UIL Computer Science for Dummies by Jake Warren and works from Mr. Fleming 1 2 Foreword First of all, this book isn t really for dummies. I wrote it for myself and other kids who are on the team. Everything

More information

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

Scanner. It takes input and splits it into a sequence of tokens. A token is a group of characters which form some unit. Scanner The Scanner class is intended to be used for input. It takes input and splits it into a sequence of tokens. A token is a group of characters which form some unit. For example, suppose the input

More information

Course Intro Instructor Intro Java Intro, Continued

Course Intro Instructor Intro Java Intro, Continued Course Intro Instructor Intro Java Intro, Continued The syllabus Java etc. To submit your homework, do Team > Share Your repository name is csse220-200830-username Use your old SVN password. Note to assistants:

More information

Yosemite National Park, California. CSE 114 Computer Science I Inheritance

Yosemite National Park, California. CSE 114 Computer Science I Inheritance Yosemite National Park, California CSE 114 Computer Science I Inheritance Containment A class contains another class if it instantiates an object of that class HAS-A also called aggregation PairOfDice

More information

Agent Languages. Overview. Requirements. Java. Tcl/Tk. Telescript. Evaluation. Artificial Intelligence Intelligent Agents

Agent Languages. Overview. Requirements. Java. Tcl/Tk. Telescript. Evaluation. Artificial Intelligence Intelligent Agents Agent Languages Requirements Overview Java Tcl/Tk Telescript Evaluation Franz J. Kurfess, Cal Poly SLO 211 Requirements for agent Languages distributed programming large-scale (tens of thousands of computers)

More information

Java EE Web Development Course Program

Java EE Web Development Course Program Java EE Web Development Course Program Part I Introduction to Programming 1. Introduction to programming. Compilers, interpreters, virtual machines. Primitive types, variables, basic operators, expressions,

More information

Android Application Development Course Program

Android Application Development Course Program Android Application Development Course Program Part I Introduction to Programming 1. Introduction to programming. Compilers, interpreters, virtual machines. Primitive data types, variables, basic operators,

More information

LINKED DATA STRUCTURES

LINKED DATA STRUCTURES LINKED DATA STRUCTURES 1 Linked Lists A linked list is a structure in which objects refer to the same kind of object, and where: the objects, called nodes, are linked in a linear sequence. we keep a reference

More information

Tutorial: Getting Started

Tutorial: Getting Started 9 Tutorial: Getting Started INFRASTRUCTURE A MAKEFILE PLAIN HELLO WORLD APERIODIC HELLO WORLD PERIODIC HELLO WORLD WATCH THOSE REAL-TIME PRIORITIES THEY ARE SERIOUS SUMMARY Getting started with a new platform

More information

STORM. Simulation TOol for Real-time Multiprocessor scheduling. Designer Guide V3.3.1 September 2009

STORM. Simulation TOol for Real-time Multiprocessor scheduling. Designer Guide V3.3.1 September 2009 STORM Simulation TOol for Real-time Multiprocessor scheduling Designer Guide V3.3.1 September 2009 Richard Urunuela, Anne-Marie Déplanche, Yvon Trinquet This work is part of the project PHERMA supported

More information

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

File I/O - Chapter 10. Many Stream Classes. Text Files vs Binary Files File I/O - Chapter 10 A Java stream is a sequence of bytes. An InputStream can read from a file the console (System.in) a network socket an array of bytes in memory a StringBuffer a pipe, which is an OutputStream

More information

KITES TECHNOLOGY COURSE MODULE (C, C++, DS)

KITES TECHNOLOGY COURSE MODULE (C, C++, DS) KITES TECHNOLOGY 360 Degree Solution www.kitestechnology.com/academy.php info@kitestechnology.com technologykites@gmail.com Contact: - 8961334776 9433759247 9830639522.NET JAVA WEB DESIGN PHP SQL, PL/SQL

More information

Designing with Exceptions. CSE219, Computer Science III Stony Brook University http://www.cs.stonybrook.edu/~cse219

Designing with Exceptions. CSE219, Computer Science III Stony Brook University http://www.cs.stonybrook.edu/~cse219 Designing with Exceptions CSE219, Computer Science III Stony Brook University http://www.cs.stonybrook.edu/~cse219 Testing vs. Debugging Testing Coding Does the code work properly YES NO 2 Debugging Testing

More information

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

Object-Oriented Design Lecture 4 CSU 370 Fall 2007 (Pucella) Tuesday, Sep 18, 2007 Object-Oriented Design Lecture 4 CSU 370 Fall 2007 (Pucella) Tuesday, Sep 18, 2007 The Java Type System By now, you have seen a fair amount of Java. Time to study in more depth the foundations of the language,

More information

Continuous Integration Part 2

Continuous Integration Part 2 1 Continuous Integration Part 2 This blog post is a follow up to my blog post Continuous Integration (CI), in which I described how to execute test cases in Code Tester (CT) in a CI environment. What I

More information

Install Java Development Kit (JDK) 1.8 http://www.oracle.com/technetwork/java/javase/downloads/index.html

Install Java Development Kit (JDK) 1.8 http://www.oracle.com/technetwork/java/javase/downloads/index.html CS 259: Data Structures with Java Hello World with the IntelliJ IDE Instructor: Joel Castellanos e-mail: joel.unm.edu Web: http://cs.unm.edu/~joel/ Office: Farris Engineering Center 319 8/19/2015 Install

More information

3.5. cmsg Developer s Guide. Data Acquisition Group JEFFERSON LAB. Version

3.5. cmsg Developer s Guide. Data Acquisition Group JEFFERSON LAB. Version Version 3.5 JEFFERSON LAB Data Acquisition Group cmsg Developer s Guide J E F F E R S O N L A B D A T A A C Q U I S I T I O N G R O U P cmsg Developer s Guide Elliott Wolin wolin@jlab.org Carl Timmer timmer@jlab.org

More information

Glossary of Object Oriented Terms

Glossary of Object Oriented Terms Appendix E Glossary of Object Oriented Terms abstract class: A class primarily intended to define an instance, but can not be instantiated without additional methods. abstract data type: An abstraction

More information

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

Exception Handling. Overloaded methods Interfaces Inheritance hierarchies Constructors. OOP: Exception Handling 1 Exception Handling Error handling in general Java's exception handling mechanism The catch-or-specify priciple Checked and unchecked exceptions Exceptions impact/usage Overloaded methods Interfaces Inheritance

More information

Programming by Contract. Programming by Contract: Motivation. Programming by Contract: Preconditions and Postconditions

Programming by Contract. Programming by Contract: Motivation. Programming by Contract: Preconditions and Postconditions COMP209 Object Oriented Programming Designing Classes 2 Mark Hall Programming by Contract (adapted from slides by Mark Utting) Preconditions Postconditions Class invariants Programming by Contract An agreement

More information

Habanero Extreme Scale Software Research Project

Habanero Extreme Scale Software Research Project Habanero Extreme Scale Software Research Project Comp215: Java Method Dispatch Zoran Budimlić (Rice University) Always remember that you are absolutely unique. Just like everyone else. - Margaret Mead

More information

09336863931 : provid.ir

09336863931 : provid.ir provid.ir 09336863931 : NET Architecture Core CSharp o Variable o Variable Scope o Type Inference o Namespaces o Preprocessor Directives Statements and Flow of Execution o If Statement o Switch Statement

More information

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

JDK 1.5 Updates for Introduction to Java Programming with SUN ONE Studio 4 JDK 1.5 Updates for Introduction to Java Programming with SUN ONE Studio 4 NOTE: SUN ONE Studio is almost identical with NetBeans. NetBeans is open source and can be downloaded from www.netbeans.org. I

More information

Chapter 3. Input and output. 3.1 The System class

Chapter 3. Input and output. 3.1 The System class Chapter 3 Input and output The programs we ve looked at so far just display messages, which doesn t involve a lot of real computation. This chapter will show you how to read input from the keyboard, use

More information

Mobile App Design Project #1 Java Boot Camp: Design Model for Chutes and Ladders Board Game

Mobile App Design Project #1 Java Boot Camp: Design Model for Chutes and Ladders Board Game Mobile App Design Project #1 Java Boot Camp: Design Model for Chutes and Ladders Board Game Directions: In mobile Applications the Control Model View model works to divide the work within an application.

More information

Object Oriented Software Design

Object Oriented Software Design Object Oriented Software Design Introduction to Java - II Giuseppe Lipari http://retis.sssup.it/~lipari Scuola Superiore Sant Anna Pisa October 28, 2010 G. Lipari (Scuola Superiore Sant Anna) Introduction

More information

RARITAN VALLEY COMMUNITY COLLEGE ACADEMIC COURSE OUTLINE. CISY 105 Foundations of Computer Science

RARITAN VALLEY COMMUNITY COLLEGE ACADEMIC COURSE OUTLINE. CISY 105 Foundations of Computer Science I. Basic Course Information RARITAN VALLEY COMMUNITY COLLEGE ACADEMIC COURSE OUTLINE CISY 105 Foundations of Computer Science A. Course Number and Title: CISY-105, Foundations of Computer Science B. New

More information

Java SE 7 Programming

Java SE 7 Programming Java SE 7 Programming The second of two courses that cover the Java Standard Edition 7 (Java SE 7) Platform, this course covers the core Application Programming Interfaces (API) you will use to design

More information

INSTITUTE OF AERONAUTICAL ENGINEERING

INSTITUTE OF AERONAUTICAL ENGINEERING INSTITUTE OF AERONAUTICAL ENGINEERING (Autonomous) DUNDIGAL, HYDERABAD -500 043 COMPUTER SCIENCE AND ENGINEERING JAVA LIST OF EXPERIMENTS Course Title Course Code Regulation Course Structure Course Coordinator

More information

Java 6 'th. Concepts INTERNATIONAL STUDENT VERSION. edition

Java 6 'th. Concepts INTERNATIONAL STUDENT VERSION. edition Java 6 'th edition Concepts INTERNATIONAL STUDENT VERSION CONTENTS PREFACE vii SPECIAL FEATURES xxviii chapter i INTRODUCTION 1 1.1 What Is Programming? 2 J.2 The Anatomy of a Computer 3 1.3 Translating

More information

C# Cookbook. Stephen Teilhet andjay Hilyard. O'REILLY 8 Beijing Cambridge Farnham Köln Paris Sebastopol Taipei Tokyo '"J""'

C# Cookbook. Stephen Teilhet andjay Hilyard. O'REILLY 8 Beijing Cambridge Farnham Köln Paris Sebastopol Taipei Tokyo 'J' C# Cookbook '"J""' Stephen Teilhet andjay Hilyard O'REILLY 8 Beijing Cambridge Farnham Köln Paris Sebastopol Taipei Tokyo Tableof Contents Preface xv 1. Numbers 1 1.1 Determining Approximate Equality Between

More information

Lecture 5: Java Fundamentals III

Lecture 5: Java Fundamentals III Lecture 5: Java Fundamentals III School of Science and Technology The University of New England Trimester 2 2015 Lecture 5: Java Fundamentals III - Operators Reading: Finish reading Chapter 2 of the 2nd

More information

Moving from CS 61A Scheme to CS 61B Java

Moving from CS 61A Scheme to CS 61B Java Moving from CS 61A Scheme to CS 61B Java Introduction Java is an object-oriented language. This document describes some of the differences between object-oriented programming in Scheme (which we hope you

More information