wwwcsif.cs.ucdavis.edu/~jacksoni

Slides:



Advertisements
Similar presentations
What is a Computer Program? For a computer to be able to do anything (multiply, play a song, run a word processor), it must be given the instructions.
Advertisements

Basic Java Constructs and Data Types – Nuts and Bolts
1 Multithreaded Programming in Java. 2 Agenda Introduction Thread Applications Defining Threads Java Threads and States Examples.
A Programmer's Introduction to Java - from a S/370 user (c) IDMS/SQL News
3 Copyright © 2005, Oracle. All rights reserved. Basic Java Syntax and Coding Conventions.
1 G54PRG Programming Lecture 1 Amadeo Ascó Adam Moore G54PRG Programming Lecture 1 Amadeo Ascó 3 Java Programming Language.
Operating Systems: Monitors 1 Monitors (C.A.R. Hoare) higher level construct than semaphores a package of grouped procedures, variables and data i.e. object.
Introduction to Programming G51PRG University of Nottingham Revision 1
An Introduction to Java Programming Language Vishnuvardhan.M.
1 pritisajja.info Unlocking the World of Java Programming….. Priti Srinivas Sajja February, 2014 Visit pritisajja.info for detail Future Technology for.
Ade Azurat, Advanced Programming 2004 (Based on LYS Stefanus’s slides) Advanced Programming 2004, Based on LYS Stefanus’s slides Slide 2.1 Multithreading.
Date: Subject:Distributed Data Processing Name:Maria Br ü ckner.
Introduction to JAVA Vijayan Sugumaran School of Business Administration Oakland University Rochester, MI
Lab#1 (14/3/1431h) Introduction To java programming cs425
Client Side Programming Using Java Applet Outcomes: You will be expected to know: – Java Applets and HTML file; –bytecode and platform independent programs;
IC211 Object Oriented Programming Overview of Java.
Java: History and Introduction (Lecture # 1). History… Java – Based on C and C++ – Developed in 1991 for intelligent consumer electronic devices – Green.
Principles of Object-Oriented Software Development The language Java.
Introduction to Java CS 331. Introduction Present the syntax of Java Introduce the Java API Demonstrate how to build –stand-alone Java programs –Java.
Multithreading in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Introduction to Java Programming Language Junji Zhi University of Toronto 1.
L EC. 01: J AVA FUNDAMENTALS Fall Java Programming.
Programming in Java; Instructor:Moorthy Introduction, Objects, Classes, Libraries1 Programming in Java Introduction.
Java Introduction Lecture 1. Java Powerful, object-oriented language Free SDK and many resources at
Introduction to Java CSIS 3701: Advanced Object Oriented Programming.
1 Module Objective & Outline Module Objective: After completing this Module, you will be able to, appreciate java as a programming language, write java.
The Java Programming Language
CS 11 java track: lecture 1 Administrivia need a CS cluster account cgi-bin/sysadmin/account_request.cgi need to know UNIX
© 2012 Pearson Education, Inc. All rights reserved. 1-1 Why Java? Needed program portability – Program written in a language that would run on various.
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
Introduction to java Prepared By:-Pragnesh Patel Lect. In Computer Dept. NSIT,Jetalpur 1.
Netprog: Java Intro1 Crash Course in Java. Netprog: Java Intro2 Why Java? Network Programming in Java is very different than in C/C++ –much more language.
Applied Computing Technology Laboratory QuickStart C# Learning to Program in C# Amy Roberge & John Linehan November 7, 2005.
1 Web Based Programming Section 8 James King 12 August 2003.
1 Introduction to Java. 2 What is Java? A programming language. A platform –A virtual machine (JVM) definition. –Runtime environments in diverse hardware.
What Is Java? According to Sun in a white paper: Java: A simple, object-oriented, network-savvy, interpreted, robust, secure, architecture-neutral, portable,
CSE S. Tanimoto Java Introduction 1 Java A Programming Language for Web-based Computing with Graphics.
Computer Programming 2 Why do we study Java….. Java is Simple It has none of the following: operator overloading, header files, pre- processor, pointer.
We will talking about story of JAVA language. By Kristsada Songpartom.
Multithreading in Java Sameer Singh Chauhan Lecturer, I. T. Dept., SVIT, Vasad.
Concurrency Control 1 Fall 2014 CS7020: Game Design and Development.
Core Java Introduction Byju Veedu Ness Technologies httpdownload.oracle.com/javase/tutorial/getStarted/intro/definition.html.
Duke CPS From C++ to Java l Java history: Oak, toaster-ovens, internet language, panacea l What it is ä O-O language, not a hybrid (cf. C++)
Introduction to Java John Lewis. Course Overview Introduction Object Orientated Programming Java Structure and Syntax Using the Java Platform Advanced.
Concurrency in Java MD. ANISUR RAHMAN. slide 2 Concurrency  Multiprogramming  Single processor runs several programs at the same time  Each program.
Java and C# - Some Commonalities Compile into machine-independent, language- independent code which runs in a managed execution environment Garbage Collection.
SESSION 1 Introduction in Java. Objectives Introduce classes and objects Starting with Java Introduce JDK Writing a simple Java program Using comments.
CSE S. Tanimoto Java Introduction 1 Java A Programming Language for Web-based Computing.
 It is a pure oops language and a high level language.  It was developed at sun microsystems by James Gosling.
Sung-Dong Kim, Dept. of Computer Engineering, Hansung University Java - Introduction.
Fundamental of Java Programming (630002) Unit – 1 Introduction to Java.
Object Oriented Programming in
JAVA MULTIPLE CHOICE QUESTION.
Chapter No. : 1 Introduction to Java.
Internet and Java Foundations, Programming and Practice
Introduction Enosis Learning.
Introduction Enosis Learning.
Unit 41 – Programing in Java
CS-0401 INTERMEDIATE PROGRAMMING USING JAVA
Object Oriented Programming
Units with – James tedder
Units with – James tedder
From C++ to Java Java history: Oak, toaster-ovens, internet language, panacea What it is O-O language, not a hybrid (cf. C++) compiled to byte-code, executed.
A Programming Language for
CSC 551: Web Programming Spring 2004
(Computer fundamental Lab)
CSC 551: Web Programming Spring 2004
Java History, Editions, Version Features
Chap 1. Getting Started Objectives
A Programming Language for
Presentation transcript:

wwwcsif.cs.ucdavis.edu/~jacksoni Intro to Java for ECS 160 Stoney Jackson jacksoni@cs.ucdavis.edu wwwcsif.cs.ucdavis.edu/~jacksoni What’s the first question you’ve got to ask about a language named Java?

Can you make coffee with it?

A programming language for appliances! It was meant to!! A programming language for appliances!

Must Run on Any Architecture debug “WRITE ONCE, RUN ANYWHERE!” pretty portable Program in Java Java Compiler Java Bytecode Java Virtual Machine Java Virtual Machine

Doesn’t Make Coffee Yet

So What’s Java Good For? Web applications! Java Applet Java Applet Server

Java on the Web: Java Applets Clients download applets via Web browser Browser runs applet in a Java Virtual Machine (JVM) Interactive web, security, and client consistency Slow to download, inconsistent VMs (besides, flash won this war) Applet Client Server

Java on the Web: J2EE Thin clients (minimize download) Java all “server side” THIS IS WHAT YOU’LL BE DOING!! JSPs Servlets EJB Client Server JDBC

The Java programming environment Compared to C++: no header files, macros, pointers and references, unions, operator overloading, templates, etc. Object-orientation: Classes + Inheritance Distributed: RMI, Servlet, Distributed object programming. Robust: Strong typing + no pointer + garbage collection Secure: Type-safety + access control Architecture neutral: architecture neutral representation Portable Interpreted High performance through Just in time compilation + runtime modification of code Multi-threaded

Java Features Well defined primitive data types: int, float, double, char, etc. int 4 bytes [–2,147,648, 2,147,483,647] Control statements similar to C++: if-then-else, switch, while, for Interfaces Exceptions Concurrency Packages Name spaces Reflection Applet model

The Java programming environment Java programming language specification Syntax of Java programs Defines different constructs and their semantics Java byte code: Intermediate representation for Java programs Java compiler: Transform Java programs into Java byte code Java interpreter: Read programs written in Java byte code and execute them Java virtual machine: Runtime system that provides various services to running programs Java programming environment: Set of libraries that provide services such as GUI, data structures,etc. Java enabled browsers: Browsers that include a JVM + ability to load programs from remote hosts

Java: A tiny intro How are Java programs written? How are variables declared? How are expressions specified? How are control structures defined? How to define simple methods? What are classes and objects? What about exceptions?

How are Java programs written? Define a class HelloWorld and store it into a file: HelloWorld.java: public class HelloWorld { public static void main (String[] args) { System.out.println(“Hello, World”); } Compile HelloWorld.java javac HelloWorld.java Output: HelloWorld.class Run java HelloWorld Output: Hello, World

How are variables declared? Fibonacci: class Fibonacci { public static void main(String[] arg) { int lo = 1; int hi = 1; System.out.println(lo); while (hi < 50) { System.out.println(hi); hi = lo + hi; lo = hi – lo; }

How to define expressions? Arithmetic: +, -, *,/, %, = 8 + 3 * 2 /4 Use standard precedence and associativity rules Predicates: ==, !=, >, <, >=, <= public class Demo { public static void main (String[] argv) { boolean b; b = (2 + 2 == 4); System.out.println(b); }

How are simple methods defined? Every method is defined inside a Java class definition public class Movie { public static int movieRating(int s, int a, int d) { return s+a+d; } public class Demo { public static void main (String argv[]) { int script = 6, acting = 9, directing = 8; displayRating(script, acting, directing); public static void displayRating(int s, int a, int d){ System.out.print(“The rating of this movie is”); System.out.println(Movie.movieRating(s, a, d));

How are control structures specified? Typical flow of control statements: if-then-else, while, switch, do-while, and blocks class ImprovedFibo { static final int MAX_INDEX = 10; public static void main (String[] args) { int lo = 1; int hi = 1; String mark = null; for (int i = 2; i < MAX_INDEX; i++) { if ((i % 2) == 0) mark = " *"; else mark = ""; System.out.println(i+ ": " + hi + mark); hi = lo + hi; lo = hi - lo; }}}

What are classes and objects? Classes: templates for constructing instances Fields Instance variables Static variables Methods Instance Static class Point { public double x, y; } Point lowerleft = new Point(); Point upperRight = new Point(); Point middlePoint = new Point(); lowerLeft.x = 0.0; lowerLeft.y = 0.0; upperRight.x = 1280.0; upperRight.y = 1024.0 middlePoint.x = 640.0; middlePoint.y = 512.0

How are instance methods defined? Instance methods take an implicit parameter: instance on which method is invoked public class Movie { public int script, acting, directing; public int rating() { return script + acting + directing; } public class Demo { public static void main (String argv[]) { Movie m = new Movie(); m.script = 6; m.acting = 9; m.directing = 8; System.out.print(“The rating of this movie is”); System.out.println(m.rating());

How to extend classes? Inheritance: mechanism for extending behavior of classes; leads to construction of hierarchy of classes [Note: no multiple inheritance] What happens when class C extends class D: Inherits instance variables Inherits static variables Inherits instance methods Inherits static methods C can: Add new instance variables Add new methods (static and dynamic) Modify methods (only implementation) Cannot delete anything

How to extend classes? public class Attraction { public int minutes; public Attraction() {minutes = 75;} public int getMinutes() {return minutes;} public void setMinutes(int d) {minutes = d;} } public class Movie extends Attraction { public int script, acting, directing; public Movie() {script = 5; acting = 5; directing = 5;} public Movie(int s, int a, int d) { script = s; acting = a; directing = d; public int rating() {return script + acting + directing;} public class Symphony extends Attraction { public int playing, music, conducting; public Symphony() {playing = music = conducting = 5;} public Symphony(int p, int m, int c) { playing = p; music = m; conducting = c; public int rating() {return playing + music + conducting;}

What are abstract classes? Abstract class: Merely a place holder for class definitions; cannot be used to create instances.; public abstract class Attraction { public int minutes; public Attraction() {minutes = 75;} public int getMinutes() {return minutes;} public void setMinutes(int d) {minutes = d;} public abstract void m(); } Following is an error: Attraction x; x = new Attraction(); Following is not an error: public class Movie extends Attraction { … } public class Symphony extends Attraction { … } Attraction x; x = new Movie (); x = new Symphony();

Packages Object Attraction Auxiliaries Demonstration Movie Symphony extends How do we organize above classes into a single unit? Put them in file? However, only one public class per file (whose name is same as file’s) Solution: Place several files (compilation units) into a package

Packages – cont’d. units of organizing related Classes, Interfaces, Sub packages Why? Reduce name clashing Limit visibility of names Java programs typically organized in terms of packages and subpackages Each package may then be divided into several packages, subpackages, and classes Each class can then be stored in a separate file Each source file starts with something like: package mypackage; Code in source file is now part of mypackage

Packages – cont’d. Where to store packages? package onto.java.entertainment; public abstract class Attraction { … } package onto.java.entertainment; public class Movie extends class Attraction {…} package onto.java.entertainment; import java.io.*; import java.util.*; public class Auxiliaries { … } Where to store packages? How does Java find packages? Export and Import Access control

Exceptions public class A { public void foo() throws MyException { if(aBadThingHappened()) { throw new MyException(); } public void bar() { try { this.foo(); } catch (MyException e) { e.printStackTrace(); public class MyException extends Exception { public MyException() {} public MyException(String message) { super(String message);

Finally public class A { public void foo() throws MyException { throw new MyException(); } public void bar() { try { this.foo(); } catch (MyException e) { e.printStackTrace(); } catch (YourException e) { } finally { ... // always executed before leaving the try/catch

Resources http://java.sun.com/ http://www.eclipse.org/ Java[tm] 2 Platform, Standard Edition v1.4.1 java, javac, jar, jre, etc. Any platform... FREE! Online documentation and tutorials http://www.eclipse.org/ Integrated development environment (IDE) for nothing in particular Java[tm] development tools (JDT) (comes with Eclips) Project management Editor Incremental compiler CVS support C/C++ extension in progress AspectJ support Windows, Linux, and Mac.... FREE!

Qualifiers public – any class* may access (no qualifier) “package protected” – only the class* and classes* in the same package may access protected – only the class* and decendent classes* may access private – only the class* may access The class or instances of the class (an object of the class)

Package Protected package edu.ucdavis; public class A { int x; } public class B { void foo(A a) { a.x; } // OK, same package } package org.omg; public class B { void foo(A a) { a.x; } // Not OK, different package } package edu.ucdavis.cs; public class B { void foo(A a) { a.x; } // Not OK, different package } package edu.ucdavis.cs; public class B { void foo(A a) { a.x; } // Not OK, different package } package edu; public class B { void foo(A a) { a.x; } // Not OK, different package }

Protected public class A { protected int x; } public class B extends A { void foo(A a) { this.x; a.x; } // OK, B is a decendent of A } public class C extends B { void foo(A a) { this.x; a.x; } // OK, C is a decendent of A through B } package edu; // Uh oh! public class D extends C { void foo(A a) { this.x; a.x; } // OK, D is a decendent of A } public class E { void foo(A a) { this.x; a.x; } // NOT OK, E is NOT a decendent of A }

Threads Multiple “threads” of execution within the same program, share the same memory space -> “lightweight”. Perform multiple tasks at the same time. Work on the same task in parallel. Heavily used in user interfaces. Web browsers: load web pages while the user can still scroll, go back, open a new window, etc. Web servers: serve multiple requests in parallel. Can take advantage of multiple processors. Threads in Java Java manages and schedules threads Java provides “synchronize” to help coordinate multiple threads

Creating a Thread in Java public class MyThread extends Thread { public MyThread(String threadName) { super(threadName); } public void run() { for(int i = 0; i < 10; i++) { System.out.println(i + “ “ + getName()); try { sleep((long)(Math.random() * 1000)); } catch(InterruptedException e) {}

Creating a Thread in Java public class ThreadTest { public static void main(String[] args) { for(int i = 0; i < args.length; i++) { MyThread t = new MyThread(args[i]); t.start(); } > java ThreadTest Bob Frank 0 Bob 0 Frank 1 Bob 2 Bob 1 Frank 3 Bob 2 Frank 3 Frank 4 Frank ...

Creating a Thread in Java via Interface public class MyRunnable implements Runnable { String name; public MyRunnable(String name) { this.name = name; } public void run() { for(int i; i < 10; i++) { System.out.println(i + “ “ + name()); try { sleep((long)(Math.random() * 1000)); } catch(InterruptedException e) {} public class ThreadTest { public static void main(String[] args) { for(int i = 0; i < args.length; i++) { Thread t = new Thread(new MyRunnable(args[i]), args[i]); t.start();

Producer Consumer Problem public class Producer extends Thread { private Share shared; public Producer(Share s) { shared = s; } public void run() { for(int i = 0; i < 10; i++){ shared.put(i); shared.put(0) shared.get() // 0 gotten shared.get() // 0 gotten again!! shared.put(1) shared.get() // 0 never gotten!! public class Consumer extends Thread { private Share shared; public Consumer(Share s) { shared = s; } public void run() { int value; for(int i = 0; i < 10; i++) { value = shared.get(); // what about simultaneous // access?! shared.put(0) shared.get() RACE CONDITIONS!

Synchronized Synchronized provides mutual exclusion on an object public class Share { private int s; public synchronized int get() { ... } public synchronized void put(int s) { ... } } Synchronized provides mutual exclusion on an object For any object, only one thread may execute inside any of that object’s synchronized methods Share s1 = new Share(); Share s2 = new Share(); Thread t1 = ...; Thread t2 = ...; t1 -> s1.get() // gets in t2 -> s1.put(32) // blocks t2 -> s2.put(4) // gets in

Producer Consumer Coordination public class Share { private int s; private boolean empty = true; public synchronized int get() { while (empty == true) { try { wait(); // nothing to get, wait } catch (InterruptedException e) {} } empty = true; notifyAll(); // wakeup waiting Consumers/Producers return s; public synchronized void put(int s) { while (empty == false) { wait(); // no room this.s = s; empty = false;