Game Scripting. Overview. Scripting Concepts. Script Interpreters ( Engines ) Scripting Languages

Size: px
Start display at page:

Download "Game Scripting. Overview. Scripting Concepts. Script Interpreters ( Engines ) Scripting Languages"

Transcription

1 Dr. Computer Science Dept. CSUS Overview Scripting Concepts Script Interpreters ( Engines ) Scripting Languages o JavaScript Basics Communicating with Scripts Using Scripts in Games Additional Scripting Engines 2

2 Scripting Using external code to alter game world structure or game play Common scripting languages : o JavaScript, Python, Lua o Others (Tcl, Scheme, Ruby, SmallTalk, VB ) Scripts must have access to game objects o Or at least, to a API Requires embedding an interpreter in game/game engine 3 Script Interpreters Game Engine Game Structures Internal Script Text Script Interpreter* Rhino (JavaScript) Jython (Python) LuaJ (Lua) External Script Files Queries & Modifications *Also known as a Script Engine 4

3 Using Script Engines import javax.script.scriptengine; import javax.script.scriptenginefactory; import javax.script.scriptenginemanager; import javax.script.scriptexception; /** This program lists installed the script engines, then fetches the JavaScript * engine and uses it to execute ( evaluate ) a simple one-line JavaScript program.*/ public class EnumerateScriptingEngines { public static void main(string[] args) { //get the Java script engine manager ScriptEngineManager factory = new ScriptEngineManager(); //get a list of the script engines on this platform List<ScriptEngineFactory> list = factory.getenginefactories(); System.out.println("Script Engine Factories found:"); for (ScriptEngineFactory f : list) { System.out.println(" Name = " + f.getenginename() + " language = " + f.getlanguagename() + " extensions = " + f.getextensions()); //get the JavaScript engine ScriptEngine jsengine = factory.getenginebyname("js"); //run a JavaScript program jsengine.eval("println ('Hello javascript') "); catch (ScriptException e) { System.out.println(e); 5 Executing Script Files // This code snippet gets a JavaScript engine and uses it to execute an external script ScriptEngineManager factory = new ScriptEngineManager(); ScriptEngine jsengine = factory.getenginebyname("js"); String scriptfilename = hello.js ; executescript(jsengine, scriptfilename);... //this method executes a JavaScript program from a file private void executescript(scriptengine engine, String scriptfilename) { FileReader filereader = new FileReader(scriptFileName) ; engine.eval(filereader); //execute all the script statements in the file filereader.close(); catch (FileNotFoundException e1) { System.out.println(scriptFileName + not found + e1); catch (IOException e2) { System.out.println( IO problem with + scriptfilename + e2); catch (ScriptException e3) { System.out.println( ScriptException in + scriptfilename + e3); catch (NullPointerException e4) { System.out.println ( Null ptr exception reading + scriptfilename + e4); ======================================== Contents of file hello.js : println( hello world ); 6

4 Comments JavaScript Basics Same as Java: // or /* */ (no JavaDoc /** */ form) Variables Declared with var (optional) Either global or local (inside a function) no class scope Syntax: same as Java (e.g. start with letter or _ ) o Cannot use reserved words (most Java reserved words, plus others) Typeless type determined by assigned value var i = 8; //i is an int var pi = ; //pi is a real var j = Hello ; //j is a string var k = 42 + is the answer ; //k is also a string var m = i < 10; //m is a Boolean = true 7 JavaScript Basics (cont.) Operators: same as Java (+, -, *, /, %, ==,!=, <, >, <=, >=, &&,,!, =) Control statements: if (cond) {... else {... for (var i=0; i<3; i++) {... while (cond) { catch(e){... // same as Java // almost Java // same as Java // same as Java Functions Global scope by default Defined with keyword function 8

5 Communicating With Scripts The Java Scripting API: javax.script.* Allows Java to: Pass data into a script: engine.put() Get data back from a script: engine.get() o Scripts can assign values to vars accessible by Java o Scripts also have a return value Allows scripts to: Get data from Java Pass data to Java Invoke methods in Java objects 9 Java/Script Communication Java code: 1 Script Engine int count=3; engine.put( count,count); int [] vals = {10,20,30; engine.put( vals, vals); Name Value count 3 vals ref FileReader fr = new FileReader( sums.js ); boolean result = (Boolean)engine.eval(fr); 2 sum double sum = (Double) engine.get( sum ); System.out.println( Java + sum = + sum ) ; 3 6 JavaScript in file sums.js : println( count = ' + count); var sum = 0; for (var i=0; i<count; i++) { sum += vals[i]; println( JS sum = " + sum); sum > 50 ; //script return value 10

6 Gameworld Creation Script // CreateWorld.js -- a JavaScript file to create a game world scenegraph and // return it to the Java code //provide the script with access to Java & Sage classes importclass(packages.java.awt.color); importclass(packages.sage.scene.group); importclass(packages.sage.scene.shape.teapot); importclass(packages.sage.scene.shape.pyramid); importclass(packages.sage.scene.shape.line); importclass(packages.graphicslib3d.point3d); var rootnode = new Group(); //construct an (empty) scenegraph named rootnode var t1 = new Teapot(); //create a teapot and add it to the scenegraph t1.setcolor(java.awt.color.green); rootnode.addchild(t1); var p1 = new Pyramid(); //create a pyramid and add it to the scenegraph p1.translate(3,0,0); rootnode.addchild(p1); var origin = new Point3D(0,0,0); //define and add axes to the world var xend = new Point3D(20,0,0); var yend = new Point3D(0,20,0); var zend = new Point3D(0,0,20); var xaxis = new Line(origin, xend, Color.red, 3); rootnode.addchild(xaxis); var yaxis = new Line(origin, yend, Color.green, 3); rootnode.addchild(yaxis); var zaxis = new Line(origin, zend, Color.blue, 3); rootnode.addchild(zaxis); 11 Using the CreateWorld Script /** This demonstrates how to invoke an external JavaScript to construct a Game World. */ public class DemoInitWorld extends BaseGame { private SceneNode rootnode; // the root of the game world private String scriptname = "CreateWorld.js"; //the script to create the gameworld private File scriptfile; //the script file object public void initgame() { //...code here to create a script engine as before... scriptfile = new File(scriptName); // use the engine to execute the script FileReader fr = new FileReader(scriptFile); engine.eval(fr); fr.close(); catch (...) {... // get the scenegraph created by the script from the engine rootnode = (SceneNode) engine.get("rootnode"); addgameworldobject(rootnode); //...code here for other initialization, e.g. camera position, input hndlrs, etc. //other methods (e.g. update()) here 12

7 Dynamic Script Updating protected void update(float time) { // check if the script has been modified long modtime = scriptfile.lastmodified(); if (modtime > filelastmodifiedtime) { // yes it's been modified; re-read it filelastmodifiedtime = modtime; fr = new FileReader(scriptName); engine.eval(fr); fr.close(); catch (...) {... //replace the current scenegraph with the new one from the engine removegameworldobject(rootnode); rootnode = (SceneNode) engine.get("rootnode"); addgameworldobject(rootnode); //other update() steps here as usual, including the following: rootnode.updategeometricstate(time,true); // = super.update(time); 13 /** This demonstrates how game code can instantly respond to dynamic updates to scripts */ public class DemoInitWorld extends BaseGame { private SceneNode rootnode; // the root of the game world private String scriptname = "CreateWorld.js"; // the script to create the gameworld private File scriptfile; //the script file object private long filelastmodifiedtime = 0 ; //new protected void initgame() { //code here to read the script and save the rootnode it creates, as before Invoking Script Functions Define script function Load function into engine (using eval()) Cast engine as an Invocable object Use invokefunction() to call function Java code: FileReader fr = new FileReader( sayhello.js ); engine.eval(fr); //load script function //make the engine invocable Invocable invocableengine = (Invocable) engine ; //define argument to be passed to the function Object [] arg = { Rufus ; //invoke the function in the engine invocableengine.invokefunction( sayhello,arg); catch (NoSuchMethodException e1) {... catch (ScriptException e2) { JavaScript in file sayhello.js : function sayhello(name){ println("hello " + name); ScriptEngine f1( ) { f2( ) {

8 Example: Character Updating //File UpdateCharacter.js: a JavaScript function to apply updates to a game character function updatecharacter(character) { character.setcolor(java.awt.color.green); /** This class demonstrates how to use JavaScript functions to apply changes to * GameWorld nodes. It attaches a JavaScript function to a keyboard action; * hitting the SPACE key invokes the corresponding JavaScript function. */ public class DemoNodeChangingFunctions extends BaseGame { private SceneNode rootnode; // the root of the game world, defined by script private ScriptEngine engine; protected void initgame() { //code here to create a ScriptEngine, load script files, register them // (i.e., execute them using eval()), save the script names, and initialize // the script-created rootnode... initgameactions(); //other game-specific initialization here as necessary... protected void update(float time) { // code here to check each script by name to see if it has been modified, // reexecute it if so, and reinitialize the rootnode if needed (i.e., if the // CreateWorld.js script was one of the ones that was modified)... // code here for other updates as needed... rootnode.updategeometricstate(time,true); //continued // = super.update(time); Character Updating Ex. (cont.) //continued... private void initgameactions() { IInputManager im = getinputmanager(); //get InputMgr from parent class String kbname = im.getkeyboardname(); //build an action for updating a character IAction updatecharacter = new UpdateCharacterAction(); im.associateaction(kbname, Identifier.Key.SPACE, updatecharacter, pressonly); //an Action which invokes a script function private class UpdateCharacterAction extends AbstractInputAction { public void performaction(float time, Event e) { //cast the engine so it supports invoking functions Invocable invocableengine = (Invocable) engine ; //get the node which is to be updated SceneNode player = ((Group) rootnode).getchild("player1"); //invoke the updatecharacter script function on the player invocableengine.invokefunction("updatecharacter", player); catch (...) {... //end class 16

9 Using Other Script Engines //get the Lua engine ScriptEngine luaengine = factory.getenginebyextension(".lua"); //insert variable x with value 25 luaengine.put("x", 25); //run a Lua script to compute a function of x luaengine.eval("y = math.sqrt(x)"); catch (ScriptException e) { System.out.println(e); System.out.println("Hello Lua: " + "y=" + luaengine.get("y")); // construct a Python script String lsep = System.getProperty("line.separator"); String a = "import sys" + lsep; a += "import java.io as javaio" + lsep; a += "currentdir = javaio.file (\".\")" + lsep; a += "print \"Hello Python: Current directory : \" + currentdir.getcanonicalpath()" + lsep; //get the Python engine (Jython) ScriptEngine pythonengine = factory.getenginebyextension("py"); //run the Python script pythonengine.eval(a); catch (ScriptException e) { System.out.println(e); 17 Add l JavaScript Features Arrays Size defined by parentheses at declaration var foo = new Array(10); var bar = new Array(5); Indexing from zero and using brackets (like Java) foo[0] = 42; bar[4] = 99.9; Mixed element types allowed var stuff = new Array ( a string, 12, 98.6, true); Dynamically resizeable var colors = new Array(); colors[2] = red ; //colors has no elements //colors now has 3 elements // ( [0] and [1] == null ) Properties and methods length, indexof(), concat(), tostring(),... 18

10 Add l JavaScript Features (cont.) Built-in Objects : var currenttime = new Date(); var month = currenttime.getmonth() + 1; var day = currenttime.getdate(); var year = currenttime.getfullyear(); User-created Objects : var personobj=new Object(); personobj.firstname="john"; personobj.lastname="doe"; personobj.age=50; personobj.eyecolor="blue"; //properties ( fields ) are // created when defined 19 Add l JavaScript Features (cont.) User-defined Object Constructors: function person(firstname,lastname,age,eyecolor){ this.firstname = firstname; this.lastname = lastname; this.age = age; this.eyecolor = eyecolor; this.newlastname = newlastname; //method invocation function newlastname(new_lastname){ this.lastname = new_lastname; var myfather = new person("john","doe",50,"blue"); var mymother = new person("sally","rally",48,"green"); mymother.newlastname( Doe ); 20

11 Add l JavaScript Features (cont.) User-defined Object Constructors (another example): //object creation function function circle(r) { this.radius = r; //radius property this.area = getarea; //function invocation this.diameter = getdiameter; //function invocation function getarea() { var area = this.radius*this.radius*3.14; return area; function getdiameter() { var d = this.radius*2; return d; //function definition //function definition var mycircle = new circle(20); println("area = " + mycircle.area()); //println is a Rhino method println("diameter = " + mycircle.diameter()); 21

Scripting for the Java Platform. Christopher M. Judd. Judd Solutions, LLC. President/Consultant

Scripting for the Java Platform. Christopher M. Judd. Judd Solutions, LLC. President/Consultant Scripting for the Java Platform Christopher M. Judd President/Consultant Judd Solutions, LLC Christopher M. Judd President/Consultant of Judd Solutions Central Ohio Java User Group (COJUG) coordinator

More information

Introduction to Web Tech and Programming

Introduction to Web Tech and Programming Introduction to Web Tech and Programming Objects Objects Arrays JavaScript Objects Objects are an unordered collection of properties. Basically variables holding variables. Have the form name : value name

More information

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

Lecture Notes CPSC 224 (Spring 2012) Today... Java basics. S. Bowers 1 of 8 Today... Java basics S. Bowers 1 of 8 Java main method (cont.) In Java, main looks like this: public class HelloWorld { public static void main(string[] args) { System.out.println("Hello World!"); Q: How

More information

TypeScript. Types. CS144: Web Applications

TypeScript. Types. CS144: Web Applications TypeScript Superset of JavaScript (a.k.a. JavaScript++) to make it easier to program for largescale JavaScript projects New features: types, interfaces, decorators,... All additional TypeScript features

More information

What is Groovy? Almost as cool as me!

What is Groovy? Almost as cool as me! What is Groovy? Groovy is like a super version of Java. It can leverage Java's enterprise capabilities but also has cool productivity features like closures, builders and dynamic typing. From http://groovy.codehaus.org/

More information

Object-oriented programming

Object-oriented programming Object-oriented programming HelloWorld The following code print Hello World on the console object HelloWorld { def main(args: Array[String]): Unit = { println("hello World") 2 1 object The keyword object

More information

XML JavaScript Object Notation JSON Cookies Miscellaneous What Javascript can t do. OOP Concepts of JS

XML JavaScript Object Notation JSON Cookies Miscellaneous What Javascript can t do. OOP Concepts of JS LECTURE-4 XML JavaScript Object Notation JSON Cookies Miscellaneous What Javascript can t do. OOP Concepts of JS 1 XML EXTENDED MARKUP LANGUAGE XML is a markup language, like HTML Designed to carry data

More information

Engineering Abstractions in Model Checking and Testing. Michael Achenbach Klaus Ostermann

Engineering Abstractions in Model Checking and Testing. Michael Achenbach Klaus Ostermann Engineering Abstractions in Model Checking and Testing Michael Achenbach Klaus Ostermann 1 This Talk What is abstraction engineering? How can we integrate abstractions with current tools? What more is

More information

CSCI 135 Exam #2 Fundamentals of Computer Science I Fall 2013

CSCI 135 Exam #2 Fundamentals of Computer Science I Fall 2013 CSCI 135 Exam #2 Fundamentals of Computer Science I Fall 2013 Name: This exam consists of 6 problems on the following 6 pages. You may use your two-sided hand-written 8 ½ x 11 note sheet during the exam.

More information

Xtend Programming Language

Xtend Programming Language Xtend Programming Language Produced by: Eamonn de Leastar (edeleastar@wit.ie) Department of Computing and Mathematics http://www.wit.ie/ Agenda Subtitle Excellent Xtend User Guide (Version 2.6) API Docs

More information

INDEX. A SIMPLE JAVA PROGRAM Class Declaration The Main Line. The Line Contains Three Keywords The Output Line

INDEX. A SIMPLE JAVA PROGRAM Class Declaration The Main Line. The Line Contains Three Keywords The Output Line A SIMPLE JAVA PROGRAM Class Declaration The Main Line INDEX The Line Contains Three Keywords The Output Line COMMENTS Single Line Comment Multiline Comment Documentation Comment TYPE CASTING Implicit Type

More information

Objects and Classes. 1 Creating Classes and Objects. CSCI-UA 101 Objects and Classes

Objects and Classes. 1 Creating Classes and Objects. CSCI-UA 101 Objects and Classes Based on Introduction to Java Programming, Y. Daniel Liang, Brief Version, 10/E 1 Creating Classes and Objects Classes give us a way of defining custom data types and associating data with operations on

More information

Midterm I - CSE11 Fall 2013 CLOSED BOOK, CLOSED NOTES 50 minutes, 100 points Total.

Midterm I - CSE11 Fall 2013 CLOSED BOOK, CLOSED NOTES 50 minutes, 100 points Total. Midterm I - CSE11 Fall 2013 CLOSED BOOK, CLOSED NOTES 50 minutes, 100 points Total. Name: ID: Problem 1) (8 points) For the following code segment, what are the values of i, j, k, and d, after the segment

More information

Pace University. Fundamental Concepts of CS121 1

Pace University. Fundamental Concepts of CS121 1 Pace University Fundamental Concepts of CS121 1 Dr. Lixin Tao http://csis.pace.edu/~lixin Computer Science Department Pace University October 12, 2005 This document complements my tutorial Introduction

More information

SSE3052: Embedded Systems Practice

SSE3052: Embedded Systems Practice SSE3052: Embedded Systems Practice Minwoo Ahn minwoo.ahn@csl.skku.edu Computer Systems Laboratory Sungkyunkwan University http://csl.skku.edu SSE3052: Embedded Systems Practice, Spring 2018, Jinkyu Jeong

More information

ECOM 2324 COMPUTER PROGRAMMING II

ECOM 2324 COMPUTER PROGRAMMING II ECOM 2324 COMPUTER PROGRAMMING II Object Oriented Programming with JAVA Instructor: Ruba A. Salamh Islamic University of Gaza 2 CHAPTER 9 OBJECTS AND CLASSES Motivations 3 After learning the preceding

More information

JAVASCRIPT. JavaScript is the programming language of HTML and the Web. JavaScript Java. JavaScript is interpreted by the browser.

JAVASCRIPT. JavaScript is the programming language of HTML and the Web. JavaScript Java. JavaScript is interpreted by the browser. JAVASCRIPT JavaScript is the programming language of HTML and the Web. JavaScript Java JavaScript is interpreted by the browser JavaScript 1/15 JS WHERE TO

More information

Chapter 4 Defining Classes I

Chapter 4 Defining Classes I Chapter 4 Defining Classes I This chapter introduces the idea that students can create their own classes and therefore their own objects. Introduced is the idea of methods and instance variables as the

More information

Computer Science II (20082) Week 1: Review and Inheritance

Computer Science II (20082) Week 1: Review and Inheritance Computer Science II 4003-232-08 (20082) Week 1: Review and Inheritance Richard Zanibbi Rochester Institute of Technology Review of CS-I Syntax and Semantics of Formal (e.g. Programming) Languages Syntax

More information

CSC System Development with Java. Exception Handling. Department of Statistics and Computer Science. Budditha Hettige

CSC System Development with Java. Exception Handling. Department of Statistics and Computer Science. Budditha Hettige CSC 308 2.0 System Development with Java Exception Handling Department of Statistics and Computer Science 1 2 Errors Errors can be categorized as several ways; Syntax Errors Logical Errors Runtime Errors

More information

Object Oriented Programming

Object Oriented Programming Object Oriented Programming Objectives To review the concepts and terminology of object-oriented programming To discuss some features of objectoriented design 1-2 Review: Objects In Java and other Object-Oriented

More information

CS 201, Fall 2016 Sep 28th Exam 1

CS 201, Fall 2016 Sep 28th Exam 1 CS 201, Fall 2016 Sep 28th Exam 1 Name: Question 1. [5 points] Write code to prompt the user to enter her age, and then based on the age entered, print one of the following messages. If the age is greater

More information

CSCI 135 Exam #1 Fundamentals of Computer Science I Fall 2014

CSCI 135 Exam #1 Fundamentals of Computer Science I Fall 2014 CSCI 135 Exam #1 Fundamentals of Computer Science I Fall 2014 Name: This exam consists of 8 problems on the following 8 pages. You may use your two- sided hand- written 8 ½ x 11 note sheet during the exam.

More information

CS 231 Data Structures and Algorithms, Fall 2016

CS 231 Data Structures and Algorithms, Fall 2016 CS 231 Data Structures and Algorithms, Fall 2016 Dr. Bruce A. Maxwell Department of Computer Science Colby College Course Description Focuses on the common structures used to store data and the standard

More information

CSCI 135 Exam #2 Fundamentals of Computer Science I Fall 2013

CSCI 135 Exam #2 Fundamentals of Computer Science I Fall 2013 CSCI 135 Exam #2 Fundamentals of Computer Science I Fall 2013 Name: This exam consists of 6 problems on the following 6 pages. You may use your two-sided hand-written 8 ½ x 11 note sheet during the exam.

More information

CLASS DESIGN. Objectives MODULE 4

CLASS DESIGN. Objectives MODULE 4 MODULE 4 CLASS DESIGN Objectives > After completing this lesson, you should be able to do the following: Use access levels: private, protected, default, and public. Override methods Overload constructors

More information

Computer Programming, I. Laboratory Manual. Final Exam Solution

Computer Programming, I. Laboratory Manual. Final Exam Solution Think Twice Code Once The Islamic University of Gaza Engineering Faculty Department of Computer Engineering Fall 2017 ECOM 2005 Khaleel I. Shaheen Computer Programming, I Laboratory Manual Final Exam Solution

More information

CS 251 Intermediate Programming Methods and Classes

CS 251 Intermediate Programming Methods and Classes CS 251 Intermediate Programming Methods and Classes Brooke Chenoweth University of New Mexico Fall 2018 Methods An operation that can be performed on an object Has return type and parameters Method with

More information

CS 251 Intermediate Programming Methods and More

CS 251 Intermediate Programming Methods and More CS 251 Intermediate Programming Methods and More Brooke Chenoweth University of New Mexico Spring 2018 Methods An operation that can be performed on an object Has return type and parameters Method with

More information

COMP-202 Unit 9: Exceptions

COMP-202 Unit 9: Exceptions COMP-202 Unit 9: Exceptions Course Evaluations Please do these. -Fast to do -Used to improve course for future. (Winter 2011 had 6 assignments reduced to 4 based on feedback!) 2 Avoiding errors So far,

More information

JavaScript: Sort of a Big Deal,

JavaScript: Sort of a Big Deal, : Sort of a Big Deal, But Sort of Quirky... March 20, 2017 Lisp in C s Clothing (Crockford, 2001) Dynamically Typed: no static type annotations or type checks. C-Like Syntax: curly-braces, for, semicolons,

More information

Inf1-OOP. Data Types. Defining Data Types in Java. type value set operations. Overview. Circle Class. Creating Data Types 1.

Inf1-OOP. Data Types. Defining Data Types in Java. type value set operations. Overview. Circle Class. Creating Data Types 1. Overview Inf1-OOP Creating Data Types 1 Circle Class Object Default Perdita Stevens, adapting earlier version by Ewan Klein Format Strings School of Informatics January 11, 2015 HotelRoom Class More on

More information

CS111: PROGRAMMING LANGUAGE II

CS111: PROGRAMMING LANGUAGE II CS111: PROGRAMMING LANGUAGE II Computer Science Department Lecture 1(c): Java Basics (II) Lecture Contents Java basics (part II) Conditions Loops Methods Conditions & Branching Conditional Statements A

More information

Binghamton University. CS-140 Fall Problem Solving. Creating a class from scratch

Binghamton University. CS-140 Fall Problem Solving. Creating a class from scratch Problem Solving Creating a class from scratch 1 Recipe for Writing a Class 1. Write the class boilerplate stuff 2. Declare Fields 3. Write Creator(s) 4. Write accessor methods 5. Write mutator methods

More information

CIS3023: Programming Fundamentals for CIS Majors II Summer 2010

CIS3023: Programming Fundamentals for CIS Majors II Summer 2010 CIS3023: Programming Fundamentals for CIS Majors II Summer 2010 Objects and Classes (contd.) Course Lecture Slides 19 May 2010 Ganesh Viswanathan Objects and Classes Credits: Adapted from CIS3023 lecture

More information

Produced by. Agile Software Development. Eamonn de Leastar

Produced by. Agile Software Development. Eamonn de Leastar Agile Software Development Produced by Eamonn de Leastar (edeleastar@wit.ie) Department of Computing, Maths & Physics Waterford Institute of Technology http://www.wit.ie http://elearning.wit.ie Xtend Programming

More information

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

Today. Book-keeping. File I/O. Subscribe to sipb-iap-java-students. Inner classes.  Debugging tools Today Book-keeping File I/O Subscribe to sipb-iap-java-students Inner classes http://sipb.mit.edu/iap/java/ Debugging tools Problem set 1 questions? Problem set 2 released tomorrow 1 2 So far... Reading

More information

Text User Interfaces. Keyboard IO plus

Text User Interfaces. Keyboard IO plus Text User Interfaces Keyboard IO plus User Interface and Model Model: objects that solve problem at hand. User interface: interacts with user getting input from user giving output to user reporting on

More information

Chapter 8 Objects and Classes Dr. Essam Halim Date: Page 1

Chapter 8 Objects and Classes Dr. Essam Halim Date: Page 1 Assignment (1) Chapter 8 Objects and Classes Dr. Essam Halim Date: 18-3-2014 Page 1 Section 8.2 Defining Classes for Objects 1 represents an entity in the real world that can be distinctly identified.

More information

CS1150 Principles of Computer Science Objects and Classes

CS1150 Principles of Computer Science Objects and Classes CS1150 Principles of Computer Science Objects and Classes Yanyan Zhuang Department of Computer Science http://www.cs.uccs.edu/~yzhuang CS1150 UC. Colorado Springs Object-Oriented Thinking Chapters 1-8

More information

Lecture 05: Methods. AITI Nigeria Summer 2012 University of Lagos.

Lecture 05: Methods. AITI Nigeria Summer 2012 University of Lagos. Lecture 05: Methods AITI Nigeria Summer 2012 University of Lagos. Agenda What a method is Why we use methods How to declare a method The four parts of a method How to use (invoke) a method The purpose

More information

Object Oriented Programming

Object Oriented Programming Object Oriented Programming Objectives To review the concepts and terminology of object-oriented programming To discuss some features of objectoriented design 1-2 Review: Objects In Java and other Object-Oriented

More information

CS115. Chapter 17 Exception Handling. Prof. Joe X. Zhou Department of Computer Science. To know what is exception and what is exception handling

CS115. Chapter 17 Exception Handling. Prof. Joe X. Zhou Department of Computer Science. To know what is exception and what is exception handling CS115 Pi Principles i of fcomputer Science Chapter 17 Exception Handling Prof. Joe X. Zhou Department of Computer Science CS115 ExceptionHandling.1 Objectives in Exception Handling To know what is exception

More information

CS1083 Week 2: Arrays, ArrayList

CS1083 Week 2: Arrays, ArrayList CS1083 Week 2: Arrays, ArrayList mostly review David Bremner 2018-01-08 Arrays (1D) Declaring and using 2D Arrays 2D Array Example ArrayList and Generics Multiple references to an array d o u b l e prices

More information

Chapter 9 Objects and Classes. Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All rights reserved.

Chapter 9 Objects and Classes. Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All rights reserved. Chapter 9 Objects and Classes 1 Motivations After learning the preceding chapters, you are capable of solving many programming problems using selections, loops, methods, and arrays. However, these Java

More information

6. Java Errors and Exceptions

6. Java Errors and Exceptions Errors and Exceptions in Java 6. Java Errors and Exceptions Errors and exceptions interrupt the normal execution of the program abruptly and represent an unplanned event. Exceptions are bad, or not? Errors,

More information

Exceptions, try - catch - finally, throws keyword. JAVA Standard Edition

Exceptions, try - catch - finally, throws keyword. JAVA Standard Edition Exceptions, try - catch - finally, throws keyword JAVA Standard Edition Java - Exceptions An exception (or exceptional event) is a problem that arises during the execution of a program. When an Exception

More information

Birkbeck (University of London) Software and Programming 1 In-class Test Mar 2018

Birkbeck (University of London) Software and Programming 1 In-class Test Mar 2018 Birkbeck (University of London) Software and Programming 1 In-class Test 2.1 22 Mar 2018 Student Name Student Number Answer ALL Questions 1. What output is produced when the following Java program fragment

More information

Proctors are unable to respond to queries about the interpretation of exam questions. Do your best to answer exam questions as written.

Proctors are unable to respond to queries about the interpretation of exam questions. Do your best to answer exam questions as written. HAND IN Answers Are Recorded on Question Paper QUEEN'S UNIVERSITY SCHOOL OF COMPUTING CISC212, FALL TERM, 2006 FINAL EXAMINATION 7pm to 10pm, 19 DECEMBER 2006, Jeffrey Hall 1 st Floor Instructor: Alan

More information

Java Fundamentals (II)

Java Fundamentals (II) Chair of Software Engineering Languages in Depth Series: Java Programming Prof. Dr. Bertrand Meyer Java Fundamentals (II) Marco Piccioni static imports Introduced in 5.0 Imported static members of a class

More information

Computer Science II (20073) Week 1: Review and Inheritance

Computer Science II (20073) Week 1: Review and Inheritance Computer Science II 4003-232-01 (20073) Week 1: Review and Inheritance Richard Zanibbi Rochester Institute of Technology Review of CS-I Hardware and Software Hardware Physical devices in a computer system

More information

Produced by. Agile Software Development. Eamonn de Leastar

Produced by. Agile Software Development. Eamonn de Leastar Agile Software Development Produced by Eamonn de Leastar (edeleastar@wit.ie) Department of Computing, Maths & Physics Waterford Institute of Technology http://www.wit.ie http://elearning.wit.ie Xtend Programming

More information

University of Palestine. Mid Exam Total Grade: 100

University of Palestine. Mid Exam Total Grade: 100 First Question No. of Branches (5) A) Choose the correct answer: 1. If we type: system.out.println( a ); in the main() method, what will be the result? int a=12; //in the global space... void f() { int

More information

Input from Files. Buffered Reader

Input from Files. Buffered Reader Input from Files Buffered Reader Input from files is always text. You can convert it to ints using Integer.parseInt() We use BufferedReaders to minimize the number of reads to the file. The Buffer reads

More information

CS/ENGRD 2110 FALL Lecture 5: Local vars; Inside-out rule; constructors

CS/ENGRD 2110 FALL Lecture 5: Local vars; Inside-out rule; constructors 1 CS/ENGRD 2110 FALL 2018 Lecture 5: Local vars; Inside-out rule; constructors http://courses.cs.cornell.edu/cs2110 Announcements 2 A1 is due tomorrow If you are working with a partner: form a group on

More information

6. Java Errors and Exceptions. Errors, runtime-exceptions, checked-exceptions, exception handling, special case: resources

6. Java Errors and Exceptions. Errors, runtime-exceptions, checked-exceptions, exception handling, special case: resources 129 6. Java Errors and Exceptions Errors, runtime-exceptions, checked-exceptions, exception handling, special case: resources Errors and Exceptions in Java 130 Errors and exceptions interrupt the normal

More information

Java Bytecode (binary file)

Java Bytecode (binary file) Java is Compiled Unlike Python, which is an interpreted langauge, Java code is compiled. In Java, a compiler reads in a Java source file (the code that we write), and it translates that code into bytecode.

More information

Selected Questions from by Nageshwara Rao

Selected Questions from  by Nageshwara Rao Selected Questions from http://way2java.com by Nageshwara Rao Swaminathan J Amrita University swaminathanj@am.amrita.edu November 24, 2016 Swaminathan J (Amrita University) way2java.com (Nageshwara Rao)

More information

Program Fundamentals

Program Fundamentals Program Fundamentals /* HelloWorld.java * The classic Hello, world! program */ class HelloWorld { public static void main (String[ ] args) { System.out.println( Hello, world! ); } } /* HelloWorld.java

More information

CSC Web Programming. Introduction to JavaScript

CSC Web Programming. Introduction to JavaScript CSC 242 - Web Programming Introduction to JavaScript JavaScript JavaScript is a client-side scripting language the code is executed by the web browser JavaScript is an embedded language it relies on its

More information

McGill University School of Computer Science COMP-202A Introduction to Computing 1

McGill University School of Computer Science COMP-202A Introduction to Computing 1 McGill University School of Computer Science COMP-202A Introduction to Computing 1 Midterm Exam Thursday, October 26, 2006, 18:00-20:00 (6:00 8:00 PM) Instructors: Mathieu Petitpas, Shah Asaduzzaman, Sherif

More information

UMBC CMSC 331 Final Exam

UMBC CMSC 331 Final Exam UMBC CMSC 331 Final Exam Name: UMBC Username: You have two hours to complete this closed book exam. We reserve the right to assign partial credit, and to deduct points for answers that are needlessly wordy

More information

Simple Java Reference

Simple Java Reference Simple Java Reference This document provides a reference to all the Java syntax used in the Computational Methods course. 1 Compiling and running... 2 2 The main() method... 3 3 Primitive variable types...

More information

CSCI 261 Computer Science II

CSCI 261 Computer Science II CSCI 261 Computer Science II Department of Mathematics and Computer Science Lecture 2 Exception Handling New Topic: Exceptions in Java You should now be familiar with: Advanced object-oriented design -

More information

Assumptions. History

Assumptions. History Assumptions A Brief Introduction to Java for C++ Programmers: Part 1 ENGI 5895: Software Design Faculty of Engineering & Applied Science Memorial University of Newfoundland You already know C++ You understand

More information

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

I/O in Java I/O streams vs. Reader/Writer. HW#3 due today Reading Assignment: Java tutorial on Basic I/O I/O 10-7-2013 I/O in Java I/O streams vs. Reader/Writer HW#3 due today Reading Assignment: Java tutorial on Basic I/O public class Swimmer implements Cloneable { public Date geteventdate() { return (Date)

More information

Getting started with Java

Getting started with Java Getting started with Java by Vlad Costel Ungureanu for Learn Stuff Programming Languages A programming language is a formal constructed language designed to communicate instructions to a machine, particularly

More information

Practice Questions for Chapter 9

Practice Questions for Chapter 9 Practice Questions for Chapter 9 MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question. 1) An object is an instance of a. 1) A) program B) method C) class

More information

Data Abstraction. Hwansoo Han

Data Abstraction. Hwansoo Han Data Abstraction Hwansoo Han Data Abstraction Data abstraction s roots can be found in Simula67 An abstract data type (ADT) is defined In terms of the operations that it supports (i.e., that can be performed

More information

Object Class. EX: LightSwitch Class. Basic Class Concepts: Parts. CS257 Computer Science II Kevin Sahr, PhD. Lecture 5: Writing Object Classes

Object Class. EX: LightSwitch Class. Basic Class Concepts: Parts. CS257 Computer Science II Kevin Sahr, PhD. Lecture 5: Writing Object Classes 1 CS257 Computer Science II Kevin Sahr, PhD Lecture 5: Writing Object Classes Object Class 2 objects are the basic building blocks of programs in Object Oriented Programming (OOP) languages objects consist

More information

13 th Windsor Regional Secondary School Computer Programming Competition

13 th Windsor Regional Secondary School Computer Programming Competition SCHOOL OF COMPUTER SCIENCE 13 th Windsor Regional Secondary School Computer Programming Competition Hosted by The School of Computer Science, University of Windsor WORKSHOP I [ Overview of the Java/Eclipse

More information

Programming - 2. Common Errors

Programming - 2. Common Errors Common Errors There are certain common errors and exceptions which beginners come across and find them very annoying. Here we will discuss these and give a little explanation of what s going wrong and

More information

OO Programming Concepts. Classes. Objects. Chapter 8 User-Defined Classes and ADTs

OO Programming Concepts. Classes. Objects. Chapter 8 User-Defined Classes and ADTs Chapter 8 User-Defined Classes and ADTs Objectives To understand objects and classes and use classes to model objects To learn how to declare a class and how to create an object of a class To understand

More information

Ruby: Introduction, Basics

Ruby: Introduction, Basics Ruby: Introduction, Basics Computer Science and Engineering College of Engineering The Ohio State University Lecture 3 Ruby vs Java: Similarities Imperative and object-oriented Classes and instances (ie

More information

class objects instances Fields Constructors Methods static

class objects instances Fields Constructors Methods static Class Structure Classes A class describes a set of objects The objects are called instances of the class A class describes: Fields (instance variables)that hold the data for each object Constructors that

More information

Chapter 10 Inheritance and Polymorphism. Dr. Hikmat Jaber

Chapter 10 Inheritance and Polymorphism. Dr. Hikmat Jaber Chapter 10 Inheritance and Polymorphism Dr. Hikmat Jaber 1 Motivations Suppose you will define classes to model circles, rectangles, and triangles. These classes have many common features. What is the

More information

Exceptions Handling Errors using Exceptions

Exceptions Handling Errors using Exceptions Java Programming in Java Exceptions Handling Errors using Exceptions Exceptions Exception = Exceptional Event Exceptions are: objects, derived from java.lang.throwable. Throwable Objects: Errors (Java

More information

Object Oriented Programming. Week 1 Part 1 An introduction to Java, Objects and JUnit

Object Oriented Programming. Week 1 Part 1 An introduction to Java, Objects and JUnit Object Oriented Programming Part 1 An introduction to Java, Objects and JUnit Object Oriented Programming with Java 2 Syllabus This class teaches Object Oriented Programming using Java We will focus on

More information

Introduction to Programming Using Java (98-388)

Introduction to Programming Using Java (98-388) Introduction to Programming Using Java (98-388) Understand Java fundamentals Describe the use of main in a Java application Signature of main, why it is static; how to consume an instance of your own class;

More information

Chapter 12: Inheritance

Chapter 12: Inheritance Chapter 12: Inheritance Objectives Students should Understand the concept and role of inheritance. Be able to design appropriate class inheritance hierarchies. Be able to make use of inheritance to create

More information

Java Platform, Standard Edition Java Scripting Programmer's Guide. Release 10

Java Platform, Standard Edition Java Scripting Programmer's Guide. Release 10 Java Platform, Standard Edition Java Scripting Programmer's Guide Release 10 E91079-01 March 2018 Java Platform, Standard Edition Java Scripting Programmer's Guide, Release 10 E91079-01 Copyright 2015,

More information

CONSTRUCTOR & Description. String() This initializes a newly created String object so that it represents an empty character sequence.

CONSTRUCTOR & Description. String() This initializes a newly created String object so that it represents an empty character sequence. Constructor in Java 1. What are CONSTRUCTORs? Constructor in java is a special type of method that is used to initialize the object. Java constructor is invoked at the time of object creation. It constructs

More information

Java Object Oriented Design. CSC207 Fall 2014

Java Object Oriented Design. CSC207 Fall 2014 Java Object Oriented Design CSC207 Fall 2014 Design Problem Design an application where the user can draw different shapes Lines Circles Rectangles Just high level design, don t write any detailed code

More information

Objectives. Inheritance. Inheritance is an ability to derive a new class from an existing class. Creating Subclasses from Superclasses

Objectives. Inheritance. Inheritance is an ability to derive a new class from an existing class. Creating Subclasses from Superclasses Objectives Inheritance Students should: Understand the concept and role of inheritance. Be able to design appropriate class inheritance hierarchies. Be able to make use of inheritance to create new Java

More information

Chapter 6 Introduction to Defining Classes

Chapter 6 Introduction to Defining Classes Introduction to Defining Classes Fundamentals of Java: AP Computer Science Essentials, 4th Edition 1 Objectives Design and implement a simple class from user requirements. Organize a program in terms of

More information

CLASSES AND OBJECTS. Fundamentals of Computer Science I

CLASSES AND OBJECTS. Fundamentals of Computer Science I CLASSES AND OBJECTS Fundamentals of Computer Science I Outline Primitive types Creating your own data types Classes Objects Instance variables Instance methods Constructors Arrays of objects A Foundation

More information

Name:... ID:... class A { public A() { System.out.println( "The default constructor of A is invoked"); } }

Name:... ID:... class A { public A() { System.out.println( The default constructor of A is invoked); } } KSU/CCIS/CS CSC 113 Final exam - Fall 12-13 Time allowed: 3:00 Name:... ID:... EXECRICE 1 (15 marks) 1.1 Write the output of the following program. Output (6 Marks): class A public A() System.out.println(

More information

A foundation for programming. Classes and objects. Overview. Java primitive types. Primitive types Creating your own data types

A foundation for programming. Classes and objects. Overview. Java primitive types. Primitive types Creating your own data types Classes and objects A foundation for programming any program you might want to write objects functions and modules build even bigger programs and reuse code http://www.flickr.com/photos/vermegrigio/5923415248/

More information

Proctors are unable to respond to queries about the interpretation of exam questions. Do your best to answer exam questions as written.

Proctors are unable to respond to queries about the interpretation of exam questions. Do your best to answer exam questions as written. SOLUTION HAND IN Answers Are Recorded on Question Paper QUEEN'S UNIVERSITY SCHOOL OF COMPUTING CISC212, FALL TERM, 2006 FINAL EXAMINATION 7pm to 10pm, 19 DECEMBER 2006, Jeffrey Hall 1 st Floor Instructor:

More information

First Java Program - Output to the Screen

First Java Program - Output to the Screen First Java Program - Output to the Screen These notes are written assuming that the reader has never programmed in Java, but has programmed in another language in the past. In any language, one of the

More information

CS18000: Problem Solving And Object-Oriented Programming

CS18000: Problem Solving And Object-Oriented Programming CS18000: Problem Solving And Object-Oriented Programming Class (and Program) Structure 31 January 2011 Prof. Chris Clifton Classes and Objects Set of real or virtual objects Represent Template in Java

More information

Inheritance and Polymorphism

Inheritance and Polymorphism Inheritance and Polymorphism Dr. M. G. Abbas Malik Assistant Professor Faculty of Computing and IT (North Jeddah Branch) King Abdulaziz University, Jeddah, KSA mgmalik@kau.edu.sa www.sanlp.org/malik/cpit305/ap.html

More information

Classes Basic Overview

Classes Basic Overview Final Review!!! Classes and Objects Program Statements (Arithmetic Operations) Program Flow String In-depth java.io (Input/Output) java.util (Utilities) Exceptions Classes Basic Overview A class is a container

More information

CIS 110: Introduction to Computer Programming

CIS 110: Introduction to Computer Programming CIS 110: Introduction to Computer Programming Lecture 22 and 23 Objects, objects, objects ( 8.1-8.4) 11/28/2011 CIS 110 (11fa) - University of Pennsylvania 1 Outline Object-oriented programming. What is

More information

Outline. CIS 110: Introduction to Computer Programming. Any questions? My life story. A horrible incident. The awful truth

Outline. CIS 110: Introduction to Computer Programming. Any questions? My life story. A horrible incident. The awful truth Outline CIS 110: Introduction to Computer Programming Lecture 22 and 23 Objects, objects, objects ( 8.1-8.4) Object-oriented programming. What is an object? Classes as blueprints for objects. Encapsulation

More information

UFCE3T-15-M Object-oriented Design and Programming

UFCE3T-15-M Object-oriented Design and Programming UFCE3T-15-M Object-oriented Design and Programming Block1: Objects and Classes Jin Sa 27-Sep-05 UFCE3T-15-M Programming part 1 Objectives To understand objects and classes and use classes to model objects.

More information

Interpreted vs Compiled. Java Compile. Classes, Objects, and Methods. Hello World 10/6/2016. Python Interpreted. Java Compiled

Interpreted vs Compiled. Java Compile. Classes, Objects, and Methods. Hello World 10/6/2016. Python Interpreted. Java Compiled Interpreted vs Compiled Python 1 Java Interpreted Easy to run and test Quicker prototyping Program runs slower Compiled Execution time faster Virtual Machine compiled code portable Java Compile > javac

More information

Here is a hierarchy of classes to deal with Input and Output streams.

Here is a hierarchy of classes to deal with Input and Output streams. PART 15 15. Files and I/O 15.1 Reading and Writing Files A stream can be defined as a sequence of data. The InputStream is used to read data from a source and the OutputStream is used for writing data

More information

Introduction to Java https://tinyurl.com/y7bvpa9z

Introduction to Java https://tinyurl.com/y7bvpa9z Introduction to Java https://tinyurl.com/y7bvpa9z Eric Newhall - Laurence Meyers Team 2849 Alumni Java Object-Oriented Compiled Garbage-Collected WORA - Write Once, Run Anywhere IDE Integrated Development

More information

CH. 2 OBJECT-ORIENTED PROGRAMMING

CH. 2 OBJECT-ORIENTED PROGRAMMING CH. 2 OBJECT-ORIENTED PROGRAMMING ACKNOWLEDGEMENT: THESE SLIDES ARE ADAPTED FROM SLIDES PROVIDED WITH DATA STRUCTURES AND ALGORITHMS IN JAVA, GOODRICH, TAMASSIA AND GOLDWASSER (WILEY 2016) OBJECT-ORIENTED

More information