CSC 551: Web Programming. Fall 2001



Similar documents
CSC 551: Web Programming. Spring 2004

An Overview of Java. overview-1

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

Fundamentals of Java Programming

Java in Education. Choosing appropriate tool for creating multimedia is the first step in multimedia design

Crash Course in Java

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

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

Java Programming Fundamentals

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

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

1. Overview of the Java Language

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

CS506 Web Design and Development Solved Online Quiz No. 01

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

Contents. Java - An Introduction. Java Milestones. Java and its Evolution

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

Evolution of the Major Programming Languages

Introduction to Java

Chapter 1 Java Program Design and Development

Java Crash Course Part I

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

Java Interview Questions and Answers

Software Engineering Techniques

qwertyuiopasdfghjklzxcvbnmqwerty uiopasdfghjklzxcvbnmqwertyuiopasd fghjklzxcvbnmqwertyuiopasdfghjklzx cvbnmqwertyuiopasdfghjklzxcvbnmq

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

Java Application Developer Certificate Program Competencies

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

AP Computer Science Java Subset

Moving from CS 61A Scheme to CS 61B Java

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

Lecture 5: Java Fundamentals III

To Java SE 8, and Beyond (Plan B)

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

CS 106 Introduction to Computer Science I

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

7.1 Our Current Model

02 B The Java Virtual Machine

Java applets. SwIG Jing He

java Features Version April 19, 2013 by Thorsten Kracht

Syllabus for CS 134 Java Programming

Web Development in Java

Java CPD (I) Frans Coenen Department of Computer Science

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

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

Chapter 2: Elements of Java

Java from a C perspective. Plan

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

Java (12 Weeks) Introduction to Java Programming Language

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

Java Coding Practices for Improved Application Performance

INTRODUCTION TO JAVA PROGRAMMING LANGUAGE

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

Developing Embedded Software in Java Part 1: Technology and Architecture

Chapter 7D The Java Virtual Machine

C# and Other Languages

CS170 Lab 11 Abstract Data Types & Objects

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

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

What Perl Programmers Should Know About Java

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

Computer Programming I

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

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

Mobile Application Languages XML, Java, J2ME and JavaCard Lesson 04 Java

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

CS 209 Programming in Java #1

Programmierpraktikum

Glassfish, JAVA EE, Servlets, JSP, EJB

Web Programming Step by Step

Java and Java Virtual Machine Security

Programming Languages

1001ICT Introduction To Programming Lecture Notes

Programmation 2. Introduction à la programmation Java

Storage Classes CS 110B - Rule Storage Classes Page 18-1 \handouts\storclas

Introduction to Java Lecture Notes. Ryan Dougherty

Object Oriented Software Design II

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

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

Chapter 1 Programming Languages for Web Applications

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

Glossary of Object Oriented Terms

CMSC 202H. ArrayList, Multidimensional Arrays

Government Girls Polytechnic, Bilaspur

Lecture 1 Introduction to Android

Specialized Android APP Development Program with Java (SAADPJ) Duration 2 months

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

Last Class: OS and Computer Architecture. Last Class: OS and Computer Architecture

Habanero Extreme Scale Software Research Project

Introduction to Object-Oriented Programming

Introduction to Object-Oriented Programming

Online Recruitment System 1. INTRODUCTION

Building a Multi-Threaded Web Server

Quick Introduction to Java

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

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

C++ Programming Language

C++ INTERVIEW QUESTIONS

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

Transcription:

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 variables/methods vs. class variables/methods "primitive vs. reference types "libraries, APIs "class definitions, inheritance, wrapper classes "linked structures Java Java was developed at Sun Microsystems, 1995! originally designed for small, embedded systems in electronic appliances! initial attempts used C++, but frustration at limitations/pitfalls recall: C++ = C + OOP features the desire for backward compatibility led to the retention of many bad features desired features (from the Java white paper): simple object-oriented robust platform independent architecture neutral portable dynamic interpreted high-performance distributed multi-threaded secure note: these are desirable features for any modern language thus, Java has become very popular, especially when Internet related also, Sun distributes free compilers (JDK) and open source 1

Language features simple! syntax is based on C++ (familiarity # easier transition for programmers)! removed many confusing and/or rarely-used features e.g., explicit pointers, operator overloading, automatic coercions! added memory management (reference count/garbage collection hybrid) object-oriented! OOP facilities similar C++, all methods are dynamically bound! pure OOP everything is a class, no independent functions* robust! lack of pointers and memory management avoids many headaches/errors! libraries of useful, tested classes increases level of abstraction " arrays & strings are ADTs, well-defined interfaces Language features (cont.) platform independence! want to be able to run Java code on multiple platforms! neutrality is achieved by mixing compilation & interpretation 1. Java programs are translated into byte code by a Java compiler " byte code is a generic machine code 2. byte code is then executed by an interpreter (Java Virtual Machine) " must have a byte code interpreter for each hardware platform! an Applet is a special form of Java application " byte code is downloaded with page, JVM is embedded in browser architecture-neutral! no implementation dependent features " e.g., sizes of primitive types is set (unlike C++) portable! byte code will run on any version of the Java Virtual Machine (JVM) 2

Language features (cont.) dynamic! JVM links classes at run-time as they are needed! if supporting class is recompiled, don t have to recompile entire project interpreted! needed for platform independence! interpreted # faster code-test-debug cycle, better run-time error checking high-performance! faster than traditional interpretation since byte code is "close" to native code! still somewhat slower than a compiled language (e.g., C++) Language features (cont.) distributed! extensive libraries for coping with TCP/IP protocols like HTTP & FTP! Java applications can access remote URL's the same as local files multi-threaded! a thread is like a separate program, executing concurrently! can write Java programs that deal with many tasks at once by defining multiple threads (same shared memory, but semi-independent execution)! threads are important for multi-media, Web applications secure! Java applications do not have direct access to memory locations " memory accesses are virtual, mapped by JVM to physical locations " downloaded applets cannot open, read, or write local files! JVM also verifies authenticity of classes as they are loaded! Sun claim: execution model enables virus-free*, tamper-free* systems 3

Java for the Web Java applets provide for client-side programming! unlike JavaScript, Java is full-featured with extensive library support! Java and its APIs have become industry standards "the language definition is controlled by Sun, ensures compatibility "Applications Programming Interfaces standardize the behavior of useful classes and libraries of routines! support for applets is provided by both IE and Netscape Java servlets provide similar capabilities on the server-side! alternative to CGI programs, more fully integrated into Web server First Java program /** * Hello World Application: prints "Hello world!" message on the screen. * @author Dave Reed * @version 10/10/01 */ public class HelloWorld System.out.println("Hello world!"); // prints message comments in Java // and /*... */ work the same as in C++ /**... */ designate documentation comments! Visual J++ displays documentation comments in side window for quick reference! can be used to automatically generate HTML documentation (javadoc) 4

First Java program (cont.) public class HelloWorld System.out.println("Hello world!"); // prints message class definitions in Java! similar to C++ (but no semi-colon at end) can contain data fields (instance variables) & member functions (methods) precede class definition with public to make available to all programs! there are no stand-alone functions in Java but can have a class with a static main method, automatically called! must be stored in a file of same name with.java extension e.g., HelloWorld.java First Java program (cont.) public class HelloWorld System.out.println("Hello world!"); // prints message accessibility in Java! public same as C++, accessible to all! protected accessible to class, derived classes, & classes in same package! package-only accessible to class and all classes in same package DEFAULT! private same as C++, accessible only to methods in the class main must be public to be executed 5

First Java program (cont.) public class HelloWorld System.out.println("Hello world!"); // prints message class vs. instance variables! as in C++, by default each object has its own copies of data fields thus, known as instance variables! as in C++, a variables declared static are shared by all class objects thus, known as class variables! similarly, can have a static method (class method) can only operate on class variables, accessible from the class itself class Math public static final double PI = 3.14159; public static double sqrt(double num)...... // access as Math.PI // access as in Math.sqrt(9.0) First Java program (cont.) public class HelloWorld System.out.println("Hello world!"); // prints message command line arguments! main has a parameter (an array) for accessing the command line System.out.println("Hello " + args[0]); output! System class that contains various system routines/classes! out class that contains output routines! println method for displaying text to the screen 6

Example: character input public class Count throws java.io.ioexception int count = 0; while (System.in.read()!= -1) count++; System.out.println("Input has " + count + " chars."); text input is awkward in Java System.in.read() reads a character (more general console I/O libraries exist) primitive types: same as C++, but sizes are set byte (8 bits) char (16 bits) short (16 bits) int (32 bits) long (64 bits) float (32 bits) double (64 bits) boolean arithmetic & relational operators: same as C++ control structures: same as C++, but no goto Example: arithmetic & control /** * Simple program that prints a table of temperatures * * @author Dave Reed * @version 10/10/01 */ note similarities to C++ code public class FahrToCelsius double lower = 0.0, upper = 300.0, step = 20.0; System.out.println("Fahr\t\tCelsius"); System.out.println("----\t\t-------"); for (double fahr = lower; fahr <= upper; fahr += step) double celsius = (5.0/9.0) * (fahr-32.0); System.out.println(fahr + "\t\t" + celsius); 7

Example: arrays and math import java.util.*; import java.lang.math; public class RandomTest private static final int NUM_REPS = 10000; private static final int MAX_RANGE = 10; final is the same as const in C++ int[] nums = new int[max_range]; for (int i = 0; i < nums.length; i++) nums[i] = 0; Random randy = new Random(); for (int i = 0; i < NUM_REPS; i++) int index = Math.abs(randy.nextInt()) % nums.length; nums[index]++; for (int i = 0; i < nums.length; i++) System.out.println(i + ": " + (nums[i]*100.0/num_reps) + "%"); primitive types (int, double, char, ) behave the same as in C++ space is allocated when declaration is reached, automatically deallocated user-defined & library types are known as reference types must explicitly allocate using new, but don t need to deallocate Primitive vs. reference types the distinction between primitive & reference types is important! space for a primitive object is implicitly allocated # variable refers to the actual data (stored on the stack)! space for a reference object must be explicitly allocated in the program # variable refers to a pointer to the data (which is stored in the heap) Note: unlike with C++, programmer is not responsible for deleting dynamic objects JVM performs automatic garbage collection to reclaim unused memory Java only provides by-value parameter passing! but reference objects are implemented as pointers to dynamic memory! resulting behavior mimics by-reference public void Assign(String str) str = "foo"; String s = "bar"; Assign(s); System.out.println(s); 8

Java ADTs import java.util.*; // needed for Random class import java.lang.math; // needed for Math.abs function public class Die private int mynumsides, mynumrolls; private Random myrandom; public Die(int numsides) myrandom = new Random(); mynumsides = numsides; mynumrolls = 0; public int Roll() mynumrolls++; return (Math.abs(myRandom.nextInt()) % mynumsides) + 1; the class constructor: allocates reference types initializes primitive types in Java, class definition is in one file no equiv. to.h &.cpp public int NumSides() return mynumsides; public int NumRolls() return mynumrolls; import Die; class Rollem Die die1 = new Die(6); Die die2 = new Die(6); int roll = die1.roll() + die2.roll(); System.out.println("Dice total = " + roll); MarbleJar class import java.util.*; import java.lang.math; public class MarbleJar private int numblack, numwhite; private Random randy; public MarbleJar(int black, int white) randy = new Random(); numblack = black; numwhite = white; public void AddMarble(String color) if (color == "BLACK") numblack++; else if (color == "WHITE") numwhite++; public boolean IsEmpty() return (numblack + numwhite == 0); public String DrawMarble() if (Math.abs(randy.nextInt())%(numBlack+numWhite) < numblack) numblack--; return "BLACK"; else numwhite--; return "WHITE"; 9

import MarbleJar; public class Puzzle private static final int NUM_BLACK = 10; private static final int NUM_WHITE = 7; Puzzle class MarbleJar jar = new MarbleJar(NUM_BLACK, NUM_WHITE); while (!jar.isempty()) String marble1 = jar.drawmarble(); if (jar.isempty()) System.out.println("Only one marble left -- it is " + marble1 + "."); else String marble2 = jar.drawmarble(); System.out.print("I drew " + marble1 + " and " + marble2); if (marble1 == marble2) System.out.println(" -- adding a BLACK marble."); jar.addmarble("black"); else System.out.println(" -- adding a WHITE marble."); jar.addmarble("white"); Java libraries String class (automatically loaded from java.lang) int length() char charat(index) int indexof(substring) String substring(start, end) String touppercase() boolean equals(object)... Array class (automatically loaded from java.lang) int length instance variable char [](index) operator String tostring() boolean equals(object)... Java provides extensive libraries of data structures & algorithms java.util # Vector Stack LinkedList Dictionary HashTable Random Calendar 10

Java & inheritance Java does NOT have templates! generic functions/classes are obtained via inheritance with inheritance, can derive a new class from an existing class automatically inherit attributes & methods of the parent class object of derived class can be used wherever parent object is expected! every reference type is implicitly derived from the Object class! by defining data structures that contain Objects, any reference type can be stored (and even mixed) Stack things = new Stack(); String str = "foobar"; things.push(str); // pushes String as an Object Calendar today = Calendar.getDate(); // pushes Calendar as an Object things.push(today); Java & inheritance (cont.) to display an object using System.out.print, that object must have a tostring method that returns the corresponding output string method calls are dynamically bound in Java! an object knows its own type, so method calls find the appropriate code while (!things.empty() ) Object top = things.pop(); // removes & returns top Object System.out.println(top); // tostring method for the appropriate // type is called to display if desired, can coerce Objects back to their more specific types Calendar today = (Calendar)things.pop(); String word = (String)things.pop(); 11

Wrapper classes since primitive types are different from reference types, Java handles them very differently! a primitive type is NOT an Object! thus, cannot have a Vector of ints, a Stack of chars, THIS SEEMS LIKE A BIG PROBLEM! solution: "wrapper classes"! a wrapper class defines an Object that encapsulates a primitive type Character ch = new Character('A');! can access the underlying primitive value using typevalue char c = ch.charvalue();! thus, if you want to use a primitive where an object is expected, wrap it Stack stk = new Stack(); stk.push(new Character('A')); Example: delimiter matching each char must be wrapped in a Character before pushing pop returns an Object, which must be coerced into a Character, which can be accessed using charvalue() Note: Strings are not accessed the same as arrays charat(i) instead of [i] length() instead of length import java.io.*; import java.util.stack; public class DelimMatch throws java.io.ioexception System.out.print("Enter expression: "); BufferedReader d = new BufferedReader(new InputStreamReader(System.in)); String line = d.readline(); Stack parens = new Stack(); for (int i = 0; i < line.length(); i++) if (line.charat(i) == '(' line.charat(i) == '[') parens.push(new Character(line.charAt(i))); else if (line.charat(i) == ')' line.charat(i) == ']') if (parens.empty()) System.out.println("Error: unmatched right delimeter at index " + i); return; else Character top = (Character)parens.pop(); if (!match(top.charvalue(), line.charat(i))) System.out.println("Error: mismatched delimeters at index " + i); return; if (!parens.empty()) System.out.println("Error: unclosed left delimiter"); else System.out.println("Expression is OK"); private static boolean match(char ch1, char ch2) return ((ch1 == '(' && ch2 == ')') (ch1 == '[' && ch2 == ']')); 12

No pointers? recall: there are no (explicit) pointers in Java DOES THIS PRECLUDE LINKED STRUCTURES? ANSWER: No! since reference types are really pointers to structures, can use the type itself where a C++ pointer would be expected public class IntNode public int data; public IntNode next; // reference to another node structure IntNode front = null; // initializes front to an empty list IntNode newnode = new IntNode; newnode.data = 14; newnode.next = front; // allocates a new node structure // stores 14 in data field // sets next field (reference) to front front = newnode; // sets front reference to new node Linked list class public class ObjectNode public Object data; public ObjectNode next; public class LinkedList private ObjectNode front; public LinkedList() front = null; public void Insert(Object obj) ObjectNode newnode = new ObjectNode(); newnode.data = obj; newnode.next = front; front = newnode; generic linked list class ObjectNode can store any Object (i.e., any reference type) LinkedList contains a linked sequence of ObjectNodes public String tostring() String liststr = "["; ObjectNode current = front; while (current!= null) liststr += " " + current.data; current = current.next; return liststr + " ]"; LinkedList list = new LinkedList(); for (int i = 1; i <= 10; i++) list.insert(new Integer(i)); list.insert("foo"); System.out.println(list); 13

Next week Java applets! APPLET tag in HTML! applet methods & event handling! graphical applets read Chapter 21 as always, be prepared for a quiz on! today s lecture (moderately thorough)! the reading (superficial) 14