Overview. Why Java? What is Java? Java notes for C++ programmers. First Program. Concurrent Object-Oriented Programming. Java (VRH 7.7,8.

Similar documents
Crash Course in Java

Java Interview Questions and Answers

An Overview of Java. overview-1

Java Programming Fundamentals

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

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

Java Crash Course Part I

Introduction to Java

Fundamentals of Java Programming

Java Cheatsheet. Tim Coppieters Laure Philips Elisa Gonzalez Boix

Java from a C perspective. Plan

Chapter 1 Fundamentals of Java Programming

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

CS 106 Introduction to Computer Science I

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

Habanero Extreme Scale Software Research Project

How To Write A Program In Java (Programming) On A Microsoft Macbook Or Ipad (For Pc) Or Ipa (For Mac) (For Microsoft) (Programmer) (Or Mac) Or Macbook (For

language 1 (source) compiler language 2 (target) Figure 1: Compiling a program

AP Computer Science Java Subset

Tutorial: Getting Started

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

Java Programming. Binnur Kurt Istanbul Technical University Computer Engineering Department. Java Programming. Version 0.0.

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

The C Programming Language course syllabus associate level

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

Java SE 8 Programming

Chapter 1 Java Program Design and Development

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

qwertyuiopasdfghjklzxcvbnmqwerty uiopasdfghjklzxcvbnmqwertyuiopasd fghjklzxcvbnmqwertyuiopasdfghjklzx cvbnmqwertyuiopasdfghjklzxcvbnmq

picojava TM : A Hardware Implementation of the Java Virtual Machine

Web Development in Java

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

The Java Series. Java Essentials I What is Java? Basic Language Constructs. Java Essentials I. What is Java?. Basic Language Constructs Slide 1

CS506 Web Design and Development Solved Online Quiz No. 01

java Features Version April 19, 2013 by Thorsten Kracht

Pemrograman Dasar. Basic Elements Of Java

Getting Started with the Internet Communications Engine

Lecture 1 Introduction to Android

University of Twente. A simulation of the Java Virtual Machine using graph grammars

Chapter 2 Introduction to Java programming

JAVA IN A NUTSHELL O'REILLY. David Flanagan. Fifth Edition. Beijing Cambridge Farnham Köln Sebastopol Tokyo

The Java Virtual Machine and Mobile Devices. John Buford, Ph.D. Oct 2003 Presented to Gordon College CS 311

C# and Other Languages

C++ INTERVIEW QUESTIONS

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

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

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

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

02 B The Java Virtual Machine

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

Compiling Object Oriented Languages. What is an Object-Oriented Programming Language? Implementation: Dynamic Binding

CSE 452: Programming Languages. Acknowledgements. Contents. Java and its Evolution

Object Oriented Software Design

What is Java? Applications and Applets: Result of Sun s efforts to remedy bad software engineering practices

Java Programming Language

Object Oriented Software Design

Java (12 Weeks) Introduction to Java Programming Language

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

Programmation 2. Introduction à la programmation Java

Java CPD (I) Frans Coenen Department of Computer Science

More on Objects and Classes

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

CSC 551: Web Programming. Spring 2004

SE 360 Advances in Software Development Object Oriented Development in Java. Polymorphism. Dr. Senem Kumova Metin

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

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

Java Application Developer Certificate Program Competencies

Characteristics of Java (Optional) Y. Daniel Liang Supplement for Introduction to Java Programming

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

Programming Language Concepts: Lecture Notes

Performance Improvement In Java Application

1. Overview of the Java Language

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

Habanero Extreme Scale Software Research Project

Cloud Computing. Up until now

Implementation Aspects of OO-Languages

The programming language C. sws1 1

Installing Java (Windows) and Writing your First Program

CSE 373: Data Structure & Algorithms Lecture 25: Programming Languages. Nicki Dell Spring 2014

Problem 1. CS 61b Summer 2005 Homework #2 Due July 5th at the beginning of class

Introduction to Java. CS 3: Computer Programming in Java

Fachbereich Informatik und Elektrotechnik SunSPOT. Ubiquitous Computing. Ubiquitous Computing, Helmut Dispert

Lab Experience 17. Programming Language Translation

Lecture 5: Java Fundamentals III

To Java SE 8, and Beyond (Plan B)

DIPLOMADO DE JAVA - OCA

Java and Java Virtual Machine Security

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

CSC 551: Web Programming. Fall 2001

Java SE 7 Programming

Class 16: Function Parameters and Polymorphism

2 Introduction to Java. Introduction to Programming 1 1

Embedded Programming in C/C++: Lesson-1: Programming Elements and Programming in C

Computer Science 483/580 Concurrent Programming Midterm Exam February 23, 2009

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

Introduction to Object-Oriented Programming

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

Moving from CS 61A Scheme to CS 61B Java

Copyright. Restricted Rights Legend. Trademarks or Service Marks. Copyright 2003 BEA Systems, Inc. All Rights Reserved.

Transcription:

Concurrent Object-Oriented Programming Java (VRH 7.7,8.6) Carlos Varela RPI Overview Crash Course in Java Types and Classes Method Overloading; Multimethods Concurrency support Partly adapted with permission from: D. Hollinger, J.J. Johns, RPI C. Varela 1 C. Varela 2 What is Java? A programming language. As defined by Gosling, Joy, and Steele in the Java Language Specification A platform A virtual machine (JVM) definition. Runtime environments in diverse hardware. A class library Standard APIs for GUI, data storage, processing, I/O, and networking. Why Java? Java has substantial differences with C++ error handling (compiler support for exception handling checks) no pointers (garbage collection) threads are part of the language dynamic class loading and secure sandbox execution for remote code source code and bytecode-level portability C. Varela 3 C. Varela 4 Java notes for C++ programmers (Almost) everything is an object. Every object inherits from java.lang.object Primitive data types are similar: boolean is not an int. No code outside of class definitions No global variables Single class inheritance an additional kind of inheritance: multiple interface inheritance All classes are defined in.java files one top level public class per file First Program public class HelloWorld { public static void main(string args[]) { System.out.println("Hello World"); C. Varela 5 C. Varela 6 1

Compiling and Running Java bytecode and interpreter HelloWorld.java source code run java HelloWorld javac HelloWorld.java compile HelloWorld.class Java bytecode is an intermediate representation of the program (stored in.class file) The Java interpreter starts up a new Virtual Machine. The VM starts executing the user s class by running its main() method. bytecode C. Varela 7 C. Varela 8 PATH and CLASSPATH PATH and CLASSPATH are environment variables that tell your operating system where to find programs. The java_home/bin directory should be in your $PATH If you are using any classes outside the java or javax packages, their locations must be included in your $CLASSPATH Data types Operators Control Structures Classes and Objects Packages The Language C. Varela 9 C. Varela 10 Java Primitive Data Types Primitive Data Types: boolean true or false char unicode (16 bits) byte signed 8 bit integer short signed 16 bit integer int signed 32 bit integer long signed 64 bit integer float,double IEEE 754 floating point Other Data Types Reference types (composite) objects arrays strings are supported by a built-in class named String (java.lang.string) string literals are supported by the language (as a special case). C. Varela 11 C. Varela 12 2

Type Conversions Conversion between integer types and floating point types. this includes char No automatic conversion from or to the type boolean. You can force conversions with a cast same syntax as C/C++. int i = (int) 1.345; Operators Assignment: =, +=, -=, *=, Numeric: +, -, *, /, %, ++, --, Relational: ==.!=, <, >, <=, >=, Boolean: &&,,! Bitwise: &,, ^, ~, <<, >>, Just like C/C++! C. Varela 13 C. Varela 14 Conditional statements: if, if else, switch Loop statements: while, for, do Control Structures Exceptions Terminology: throw an exception: signal that some condition (possibly an error) has occurred. catch an exception: deal with the error. In Java, exception handling is necessary (forced by the compiler)! C. Varela 15 C. Varela 16 Try/Catch/Finally try { // code that can throw an exception catch (ExceptionType1 e1) { // code to handle the exception catch (ExceptionType2 e2) { // code to handle the exception catch (Exception e) { // code to handle other exceptions finally { // code to run after try or any catch Exception Handling Exceptions take care of handling errors instead of returning an error, some method calls will throw an exception. Can be dealt with at any point in the method invocation stack. Forces the programmer to be aware of what errors can occur and to deal with them. C. Varela 17 C. Varela 18 3

Classes and Objects All Java statements appear within methods, and all methods are defined within classes. Instead of a standard library, Java provides a set of packages with classes supported in all Java implementations. Defining a Class One top level public class per.java file. typically end up with many.java files for a single program. One (at least) has a static public main() method. Class name must match the file name! compiler/interpreter use class names to figure out what file name is. Package hierarchy should match directory structure. C. Varela 19 C. Varela 20 Sample Class (from Java in a Nutshell) public class Point { public double x,y; public Point(double x, double y) { this.x = x; this.y=y; public double distancefromorigin(){ return Math.sqrt(x*x+y*y); Objects and new You can declare a variable that can hold an object: Point p; but this doesn t create the object! You have to use new: Point p = new Point(3.1,2.4); C. Varela 21 C. Varela 22 Just like C++: object.method() object.field Using objects BUT, never like this (no pointers!) object->method() object->field Strings are special You can initialize Strings like this: String blah = "I am a literal "; Or this ( + String operator): String foo = "I love " + "RPI"; C. Varela 23 C. Varela 24 4

Arrays Arrays are supported as a second kind of reference type (objects are the other reference type). Although the way the language supports arrays is different than with C++, much of the syntax is compatible. however, creating an array requires new Array Examples int x[] = new int[1000]; byte[] buff = new byte[256]; float[][] vals = new float[10][10]; C. Varela 25 C. Varela 26 Notes on Arrays index starts at 0. arrays can t shrink or grow. e.g., use Vector instead. each element is initialized. array bounds checking (no overflow!) ArrayIndexOutOfBoundsException Arrays have a.length int[] values; int total=0; Array Example Code for (int i=0;i<values.length;i++) { total += values[i]; C. Varela 27 C. Varela 28 Array Literals You can use array literals like C/C++: int[] foo = {1,2,3,4,5; String[] names = { Joe, Sam ; Reference Types Objects and Arrays are reference types Primitive types are stored as values. Reference type variables are stored as references (pointers that are not first-class). There are significant differences! C. Varela 29 C. Varela 30 5

Primitive vs. Reference Types int x=3; int y=x; There are two copies of the value 3 in memory Point p = new Point(2.3,4.2); Point t = p; There is only one Point object in memory! Point p = new Point(2.3,4.2); Point t = new Point(2.3,4.2); Passing arguments to methods Primitive types are passed by value: the method gets a copy of the value. Changes won t show up in the caller. Reference types: the method gets a copy of the reference, so the method accesses the same object However, the object reference is passed by value. Changing the reference does not change the outside object! C. Varela 31 C. Varela 32 int sum(int x, int y) { x=x+y; return x; Example void increment(int[] a) { for (int i=0;i<a.length;i++) { a[i]++; Comparing Reference Types Comparison using == means: are the references the same? (do they refer to the same object?) Sometimes you just want to know if two objects/arrays are identical copies. use the.equals() method you need to write this for your own classes! C. Varela 33 C. Varela 34 Packages You can organize a bunch of classes and interfaces into a package. defines a namespace that contains all the classes. You need to use some java packages in your programs, e.g. java.lang java.io, java.util Importing classes and packages Instead of #include, you use import You don t have to import anything, but then you need to know the complete name (not just the class, the package). if you import java.io.file you can use File objects. If not you need to use java.io.file inside the program. You need not import java.lang (imported by default). C. Varela 35 C. Varela 36 6

Compiling Multiple Public classes: need a file for each class. Telling the compiler to compile the class with main(). automatically finds and compiles needed classes. Access Control Public everyone has access Private no one outside this class has access Protected subclasses have access Default package-access C. Varela 37 C. Varela 38 Final Modifier final class cannot be subclassed final method cannot be overriden final field cannot have its value changed. Static final fields are compile time constants. final variable cannot have its value changed Static Modifier static method a class method that can only be accessed through the class name, and does not have an implicit this reference. static field A field that can only be accessed through the class name. There is only 1 field no matter how many instances of the class there are. C. Varela 39 C. Varela 40 Classes vs Types Every object o has a class c. Is c the type of the object? Suppose d < c (d is a subclass of c) then an object o2 of class d can be used anywhere an object of class c is used (called subclass polymorphism). Therefore, an object o is of type c if and only if o s class d is either: 1. = c, or 2. < c instanceof operator Dynamically checks for an object s type. o instanceof t tests whether the value of o has type t (whether the class of o is assignment compatible with reference type t). C. Varela 41 C. Varela 42 7

Interfaces A Java interface lists a number of method signatures for methods that need to be implemented by any class that implements the interface. E.g.: Interfaces A Java class that implements an interface must provide an implementation for all the methods in the interface. E.g.: public interface Figure { public double getarea() { public class Point implements Figure {... public double getarea() { return 0.0 C. Varela 43 C. Varela 44 Multiple Interface Inheritance A Java class may implement more than one interface E.g.: public class Circle implements Figure, Fillable {... public double getarea() { return Math.PI * radius * radius; public void fill(color c) { Using Interfaces as Types The Java language allows the usage of interfaces as types for polymorphism. E.g., it knows that any object of a class that implements the Figure interface will have a getarea() method: public double totalarea(figure[] figures) { // sum everything up double total=0.0; for (int i=0;i<figures.length;i++) { total += figures[i].getarea(); return total; C. Varela 45 C. Varela 46 Method Overloading In a statically typed language, a method can be overloaded by taking arguments of different types. E.g.: public int m(circle c){ return 1; public int m(string s){ return 2; The return type cannot be overloaded. The types can be related, e.g: public int m(object o){ return 1; public int m(string s){ return 2; C. Varela 47 Method Dispatching and Multimethods Which method gets dispatched can be decided at compiletime based on declared argument types information (Java), or at run-time with multi-methods (Smalltalk, SALSA). public int m(object o){ return 1; public int m(string s){ return 2; Object o = new Object(); String s = new String( hi ); Object os = new String( foo ); m(o); // returns 1 m(s); // returns 2 m(os); // Static dispatch // returns 1; (Java) // Dynamic dispatch // returns 2. (SALSA) C. Varela 48 8

Concurrent Programming in Java Java is multi-threaded. Two ways to create new threads: Extend java.lang.thread Overwrite run() method. Implement Runnable interface Include a run() method in your class. Starting a thread new MyThread().start(); new Thread(runnable).start(); The synchronized Statement To ensure only one thread can run a block of code, use synchronized: synchronized ( object ) { // critical code here Every object contains an internal lock for synchronization. C. Varela 49 C. Varela 50 synchronized as a modifier You can also declare a method as synchronized: synchronized int blah(string x) { // blah blah blah equivalent to: int blah(string x) { synchronized (this) { // blah blah blah C. Varela 51 Concurrency and state are tough when used together Execution consists of multiple threads, all executing independently and all using shared memory Because of interleaving semantics, execution happens as if there was one global order of operations Assume two threads and each thread does k operations. Then the total number of possible interleavings is 2k This is exponential in k. ( k ) One can program by reasoning on all possible interleavings, but this is extremely hard. What do we do? C. Varela 52 Exercises 56. Do Java and C++ object abstractions completely encapsulate internal state? If so, how? If not, why? 57. Do Java and C++ enable static access to methods defined in classes arbitrarily high in the inheritance hierarchy? If so, how? If not, why? 58. Do Java and C++ allow multiple inheritance? If so, how? If not, why? 59. *Write, compile and execute a Java program in your laptop. C. Varela 53 9