1 CSC 533: Organization of Programming Languages Spring 2005 The Java Programming Language  language properties  classes/ADTs  program basics  primitive.

Slides:



Advertisements
Similar presentations
Core Java Lecture 4-5. What We Will Cover Today What Are Methods Scope and Life Time of Variables Command Line Arguments Use of static keyword in Java.
Advertisements

Programmer-defined classes Part 2. Topics Returning objects from methods The this keyword Overloading methods Class methods Packaging classes Javadoc.
1 CSC 551: Web Programming Spring 2004 client-side programming with JavaScript  scripts vs. programs  JavaScript vs. JScript vs. VBScript  common tasks.
The Assembly Language Level
Lab Information Security Using Java (Review) Lab#0 Omaima Al-Matrafi.
 2005 Pearson Education, Inc. All rights reserved Introduction.
1 A Balanced Introduction to Computer Science, 2/E David Reed, Creighton University ©2008 Pearson Prentice Hall ISBN Chapter 17 JavaScript.
Lab#1 (14/3/1431h) Introduction To java programming cs425
George Blank University Lecturer. CS 602 Java and the Web Object Oriented Software Development Using Java Chapter 4.
Introduction to Java Kiyeol Ryu Java Programming Language.
COMP 519: Web Programming Fall 2006 Acknowledgment: The slides are by Dr. David Reed.Dr. David Reed Java Overview  Design goals & features  platform.
1 Chapter 2 Introductory Programs. 2 Getting started To create and run a Java program –Create a text file with a.java extension for the source code. For.
C++ fundamentals.
Lecture 1: Overview of Java. What is java? Developed by Sun Microsystems (James Gosling) A general-purpose object-oriented language Based on C/C++ Designed.
CMSC 341 Introduction to Java Based on tutorial by Rebecca Hasti at
Java Software Solutions Lewis and Loftus Chapter 2 1 Copyright 1997 by John Lewis and William Loftus. All rights reserved. Software Concepts -- Introduction.
1 CSC 551: Web Programming Spring 2004 Java Overview  Design goals & features  platform independence, portable, secure, simple, object-oriented, … 
JAVA v.s. C++ Programming Language Comparison By LI LU SAMMY CHU By LI LU SAMMY CHU.
OOP Languages: Java vs C++
1 CSC 221: Computer Programming I Fall 2004 Objects and classes: a first pass  software objects, classes, object-oriented design  BlueJ IDE, compilation.
© The McGraw-Hill Companies, 2006 Chapter 1 The first step.
Week 4-5 Java Programming. Loops What is a loop? Loop is code that repeats itself a certain number of times There are two types of loops: For loop Used.
Introduction to Java Appendix A. Appendix A: Introduction to Java2 Chapter Objectives To understand the essentials of object-oriented programming in Java.
FALL 2005CSI 4118 – UNIVERSITY OF OTTAWA1 Part 4 Web technologies: HTTP, CGI, PHP,Java applets)
Programming Languages and Paradigms Object-Oriented Programming.
1 CSC 533: Organization of Programming Languages Spring 2008 Java and OOP  design goals  language properties  classes & inheritance  abstract classes.
Java Introduction Lecture 1. Java Powerful, object-oriented language Free SDK and many resources at
1 CSC 221: Computer Programming I Spring 2008 ArrayLists and arrays  example: letter frequencies  autoboxing/unboxing  ArrayLists vs. arrays  example:
1 Module Objective & Outline Module Objective: After completing this Module, you will be able to, appreciate java as a programming language, write java.
Algorithm Programming Bar-Ilan University תשס"ח by Moshe Fresko.
ArrayList, Multidimensional Arrays
1 Java: AP Curriculum Focus and Java Subset Alyce Brady.
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.
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition.
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.
Computer Science and Software Engineering University of Wisconsin - Platteville 2. Pointer Yan Shi CS/SE2630 Lecture Notes.
1 CSC 533: Organization of Programming Languages Spring 2010 Java and OOP  design goals  language properties  classes & inheritance  abstract classes.
CHAPTER 3 GC Java Fundamentals. 2 BASICS OF JAVA ENVIRONMENT  The environment  The language  Java applications programming Interface API  Various.
 JAVA Compilation and Interpretation  JAVA Platform Independence  Building First JAVA Program  Escapes Sequences  Display text with printf  Data.
Introduction to Object Oriented Programming CMSC 331.
Using Data Within a Program Chapter 2.  Classes  Methods  Statements  Modifiers  Identifiers.
Methods in Java. Program Modules in Java  Java programs are written by combining new methods and classes with predefined methods in the Java Application.
1 CSC 221: Computer Programming I Fall 2004 Lists, data access, and searching  ArrayList class  ArrayList methods: add, get, size, remove  example:
1 CSC 221: Computer Programming I Spring 2008 Objects and classes: a broad view  software objects, classes, object-oriented design  BlueJ IDE, compilation.
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
1 CSC 221: Computer Programming I Spring 2010 Design & text processing  design principles  cohesion & coupling  objects vs. primitives  String methods:
Core Java Introduction Byju Veedu Ness Technologies httpdownload.oracle.com/javase/tutorial/getStarted/intro/definition.html.
COP INTERMEDIATE JAVA Designing Classes. Class Template or blueprint for creating objects. Their definition includes the list of properties (fields)
1 CSC 221: Computer Programming I Fall 2006 Lists, data storage & access  ArrayList class  methods: add, get, size, remove, contains, set, indexOf, toString.
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
SEEM Java – Basic Introduction, Classes and Objects.
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++)
SESSION 1 Introduction in Java. Objectives Introduce classes and objects Starting with Java Introduce JDK Writing a simple Java program Using comments.
 It is a pure oops language and a high level language.  It was developed at sun microsystems by James Gosling.
1 A Balanced Introduction to Computer Science, 2/E David Reed, Creighton University ©2008 Pearson Prentice Hall ISBN Chapter 15 JavaScript.
Sung-Dong Kim, Dept. of Computer Engineering, Hansung University Java - Introduction.
Fundamental of Java Programming (630002) Unit – 1 Introduction to Java.
Chapter No. : 1 Introduction to Java.
Java Primer 1: Types, Classes and Operators
CSC 222: Object-Oriented Programming Fall 2017
Internet and Java Foundations, Programming and Practice
C Basics.
CSC 221: Computer Programming I Fall 2005
MSIS 655 Advanced Business Applications Programming
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.
CSC 551: Web Programming Spring 2004
(Computer fundamental Lab)
CSC 551: Web Programming Spring 2004
Chapter 17 JavaScript Arrays
Chap 1. Getting Started Objectives
Presentation transcript:

1 CSC 533: Organization of Programming Languages Spring 2005 The Java Programming Language  language properties  classes/ADTs  program basics  primitive vs. reference types  data structures: String, array, ArrayList  Collections: Stack, HashSet, HashMap, TreeSet, TreeMap, …

2 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 Java desired features (from the Java white paper): simpleobject-orientednetwork-savvy interpretedrobustsecure architecture-neutralportablehigh-performance multi-threadeddynamic note: these are desirable features for any modern language (+ FREE)  Java has become very popular, especially when Internet related

3 Language features simple  syntax is based on C++ (familiarity  easier transition for programmers)  removed many rarely-used, confusing features e.g., operator overloading, multiple inheritance, automatic coercions  added memory management (reference count/garbage collection hybrid) network-savvy  extensive libraries for coping with TCP/IP protocols like HTTP & FTP  Java applications can access remote URL's the same as local files object-oriented  OOP facilities similar C++, but all member functions (methods) dynamically bound  pure OOP – everything is a class, no independent functions*

4 Language features (cont.) robust  for embedded systems, reliability is essential  Java combines extensive static checking with dynamic checking  closes C-style syntax loopholes  compile-time checking more effective  even so, the linker understands the type system & repeats many checks  Java disallows pointers as memory accessors  arrays & strings are ADTs, no direct memory access  eliminates many headaches, potential problems secure  in a networked/distributed environment, security is essential  execution model enables virus-free*, tamper-free* systems  downloaded applets cannot open, read, or write local files  uses authentication techniques based on public-key encryption note: the lack of pointers closes many security loopholes by itself

5 Language features (cont.) architecture-neutral  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  byte code will run on any version of the Java Virtual Machine  alternative execution model:  can define and compile applets (little applications)  not stand-alone, downloaded & executed by a Web browser portable  architecture neutral + no implementation dependent features  size of primitive data types are set  libraries define portable interfaces

6 Language features (cont.) interpreted  interpreted  faster code-test-debug cycle  on-demand linking (if class/library in not needed, won't be linked) does interpreted mean slow? 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 high-performance  faster than traditional interpretation since byte code is "close" to native code  still somewhat slower than a compiled language (e.g., C++)

7 Language features (cont.) dynamic  Java was designed to adapt to an evolving environment e.g., the fragile class problem in C++, if you modify a parent class, you must recompile all derived classes in Java, memory layout decisions are NOT made by the compiler instead of compiling references down to actual addresses, the Java compiler passes symbolic reference info to the byte code verifier and the interpreter the Java interpreter performs name resolution when classes are being linked, then rewrites as an address thus, the data/methods of the parent class are not determined until the linker loads the parent class code if the parent class has been recompiled, the linker automatically gets the updated version Note: the extra name resolution step is price for handling the fragile class problem

8 Java classes (ADTs) public class Die { private int numSides; private int numRolls; public Die(int sides) { numSides = sides; numRolls = 0; } public int roll() { numRolls++; return (int)(Math.random()*numSides) + 1; } public int getNumSides() { return numSides; } public int getNumRolls() { return numRolls; } class structure is similar to C++  no semi-colon at end of class  no standalone functions – every function is a method of some class similar to C++, specify private or public access for fields/methods  but specify protection for each  even class has protection mode the class name must match the file name (e.g., Die.java)  class definition cannot be broken into two files (no equivalent to.h &.cpp) here, Math.random() is a library function* that returns a random number in the range (0..1]

9 Java classes (cont.) /** * Class that simulates a single die. Dave Reed 3/5/05 */ public class Die { private int numSides; // number of die sides private int numRolls; // number of rolls so far /** * Constructs a die object sides number of die sides */ public Die(int sides) { numSides = sides; numRolls = 0; } /** * Rolls the die, updating the number of rolls. random number between 1 and getNumSides() */ public int roll() { numRolls++; return (int)(Math.random()*numSides) + 1; } /** number of die sides */ public int getNumSides() { return numSides; } /** number of die rolls so far */ public int getNumRolls() { return numRolls; } Java comments can use  // for single line comments  /* … */ for multiple lines  /** … */ for documentation the javadoc utility will automatically generate HTML documentation based on /** … */  Die.html Die.html

10 Math utility class Math is an instance of a utility class (contained in java.lang.Math )  encapsulates useful mathematical functions and constants public class Math { public static final double E = ;// access as Math.E public static final double PI = ; // access as Math.PI public static double random() { … }// access as Math.random() public static int abs(int num) { … }// access as Math.abs(-4) public static double abs(double num) { … }// access as Math.abs(-4.0) public static double sqrt(double num) { … }// access as Math.sqrt(9.0)... } static fields & methods are same as in C++, i.e., belong to the entire class can access them directly using the class name (don't need to create an object) final is same as const in C++, i.e., specifies a constant once assigned a value, cannot be changed (checked at compile-time)

11 Using classes (OPTION 1) to create an object of a class and call its methods  can utilize a visual environment such as BlueJ  classes appear as icons in the upper panel right-click on class icon to call the constructor (will be prompted for parameters)  objects appear as icons in the lower-left panel right-click on object icon to call a method (will be prompted for parameters)

12 BlueJ IDE Java download:  download the JDK (Java Development Kit) & documentation BlueJ download:  download BlueJ (or greater) the BlueJ interactive development environment (IDE) is a tool for developing, visualizing, and debugging Java programs  BlueJ was developed by researchers at Deakin University (Australia), Maersk Institute (Denmark), and University of Kent (UK)  supported by Sun Microsystems, the developers of Java  note that BlueJ does NOT include a Java compiler/interpreter must install Sun’s Java SDK (software development kit); BlueJ connects to it BlueJ includes an editor, debugger, visualizer, documentation viewer, …

13 Using classes (OPTION 2) more generally, can have a utility class with a main method  a utility class is not intended to represent a class of objects instead, encapsulates useful functions (gets around pure OOP nature of Java)  similar to C++, public static void main is called automatically for a class a parameter ( String[] args ) contains command line arguments, if any /** * Utility class to test the Die class. * Dave Reed 3/5/05 */ public class Roller { public static void main(String[] args) { Die die = new Die(6); System.out.println(die.roll()); } to create an object, must use new to allocate space and call the constructor method calls similar to C++: object.method(args) screen output is accomplished via System.out.print and System.out.println

14 Language basics primitive types: as in 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: as in C++ control structures: as in C++, no goto public class Roller { public static final int NUM_ROLLS = 10; public static void main(String[] args) { Die die1 = new Die(6); Die die2 = new Die(6); for (int i = 1; i <= NUM_ROLLS; i++) { System.out.println("ROLL " + i + ": " + (die1.roll() + die2.roll())); }

15 Primitive vs. reference types the distinction between primitive & reference types (objects) is important  space for a primitive is implicitly allocated  stored in the stack (stack dynamic)  space for a reference object must be explicitly allocated in the program  stored as a pointer in the stack, pointing to data in the heap (heap dynamic) Java only provides by-value parameter passing  but reference objects are implemented as pointers to dynamic memory  parameter gets a copy of the reference, can call methods to affect the original public void Something(Die d) { d.roll(); } ______________________________ StringDie die = new Die(8); Something(die); System.out.println( die.getNumRolls() );

16 Java strings String is a predefined Java class (in java.lang.String )  a String object encapsulates a sequence of characters  you can declare a String variable and assign it a value just like any other type String firstName = "Dave"; which is equivalent to String firstName = new String("Dave");  you can display Strings using System.out.print and System.out.println System.out.println(firstName);  the '+' operator concatenates two strings (or string and number) together String str = "foo" + "lish"; str = str + "ly"; int age = 19; System.out.println("Next year, you will be " + (age+1));

17 String methods int length() returns number of chars in String char charAt(int index) returns the character at the specified index (indices range from 0 to str.length()-1) int indexOf(char ch) returns index where the specified char/substring int indexOf(String str) first occurs in the String (-1 if not found) String substring(int start, int end) returns the substring from indices start to (end-1) String toUpperCase() returns copy of String with all letters uppercase String toLowerCase() returns copy of String with all letters lowercase bool equals(String other) returns true if other String has same value int compareTo(String other) returns -1 if less than other String, 0 if equal to other String, 1 if greater than other String ALSO, from the Character utility class: char Character.toLowerCase(char ch) returns lowercase copy of ch char Character.toUpperCase(char ch) returns uppercase copy of ch boolean Character.isLetter(char ch) returns true if ch is a letter boolean Character.isLowerCase(char ch) returns true if lowercase letter boolean Character.isUpperCase(char ch) returns true if uppercase letter

18 Pig Latin converter public class PigLatin { public static String convert(String str) { int firstVowel = findVowel(str); if (firstVowel <= 0) { return str + "way"; } else { return str.substring(firstVowel, str.length()) + str.substring(0,firstVowel) + "ay"; } private static boolean isVowel(char ch) { final String VOWELS = "aeiouAEIOU"; return (VOWELS.indexOf(ch) != -1); } private static int findVowel(String str) { for (int i = 0; i < str.length(); i++) { if (isVowel(str.charAt(i))) { return i; } return -1; } convert method converts an English word into Pig Latin  utilizes several String methods  convert method is static, since don't need different converter objects  helper methods are private since not needed by the user

19 Arrays arrays are similar to C++ arrays, but full-blown objects  to declare an array, designate the type of value stored followed by [] String[] words;int[] counters;  to create an array, must use new (an array is an object)  specify the type and size inside brackets following new words = new String[100];counters = new int[26];  unlike C++, Java arrays are heap dynamic (so can determine size during runtime) System.out.println("How many grades? "); Scanner input = new Scanner(System.in); int num = input.nextInt(); double[] grades = new grades[num]; for (int i = 0; i < num; i++) { grades[i] = input.nextDouble(); }

20 Array example arrays are useful if the size is unchanging, no need to shift entries  e.g., to keep track of dice stats, can have an array of counters public class DiceStats { public static final int DIE_SIDES = 6; public static final int NUM_ROLLS = 10000; public static void main(String[] args) { int[] counts = new int[2*DIE_SIDES+1]; Die die = new Die(DIE_SIDES); for (int i = 0; i < NUM_ROLLS; i++) { counts[die.roll() + die.roll()]++; } for (int i = 2; i <= 2*DIE_SIDES; i++) { System.out.println(i + ": " + counts[i] + " (" + (100.0*counts[i]/NUM_ROLLS) + "%)"); } note: all fields & local arrays are automatically initialized: int = 0 double = 0.0 boolean = false

21 ArrayList class similar to C++ vector class, an ArrayList is a more robust, flexible list  can only store reference objects (but boxing/unboxing* usually works for primitives)  starting with Java 5, ArrayList s are generic (similar to C++ templates) ArrayList words = new ArrayList ();  add items to the end of the ArrayList using add words.add("Billy");// adds "Billy" to end of list words.add("Bluejay");// adds "Bluejay" to end of list  can access items in the ArrayList using get (indices start at 0) String first = words.get(0); // assigns "Billy" String second = words.get(1); // assigns "Bluejay"  can determine the number of items in the ArrayList using size int count = words.size();// assigns 2

22 ArrayList methods common methods: Object get(int index) returns object at specified index Object add(Object obj) adds obj to the end of the list Object add(int index, Object obj) adds obj at index (shifts to right) Object remove(int index) removes object at index (shifts to left) int size() removes number of entries in list boolean contains(Object obj) returns true if obj is in the list other useful methods: Object set(int index, Object obj) sets entry at index to be obj int indexOf(Object obj) returns index of obj in the list (assumes obj has an equals method) String toString() returns a String representation of the list e.g., "[foo, bar, biz, baz]"

23 Notebook class consider designing a class to model a notebook (i.e., a to-do list)  will store notes as String s in an ArrayList  will provide methods for adding notes, viewing the list, and removing notes import java.util.ArrayList; public class Notebook { private ArrayList notes; public Notebook() { … } public void storeNote(String newNote) { … } public void storeNote(int priority, String newNote) { … } public int numberOfNotes() { … } public void listNotes() { … } public void removeNote(int noteNumber) { … } public void removeNote(String note) { … } } any class that uses an ArrayList must load the library file that defines it

24... /** * Constructs an empty notebook. */ public Notebook() { notes = new ArrayList (); } /** * Store a new note into the notebook. newNote note to be added to the notebook list */ public void storeNote(String newNote) { notes.add(newNote); } /** * Store a new note into the notebook with the specified priority. priority index where note is to be added newNote note to be added to the notebook list */ public void storeNote(int priority, String newNote) { notes.add(priority, newNote); } /** the number of notes currently in the notebook */ public int numberOfNotes() { return notes.size(); }... constructor creates the (empty) ArrayList one version of storeNote adds a new note at the end numberOfNodes calls the size method another version adds the note at a specified index

25 Notebook class (cont.)... /** * Show a note. noteNumber the number of the note to be shown (first note is # 0) */ public void showNote(int noteNumber) { if (noteNumber = numberOfNotes()) { System.out.println("There is no note with that index."); } else { System.out.println(notes.get(noteNumber)); } /** * List all notes in the notebook. */ public void listNotes() { System.out.println("NOTEBOOK CONTENTS"); System.out.println(" "); for (int i = 0; i < notes.size(); i++) { System.out.print(i + ": "); showNote(i); }... showNote checks to make sure the note number is valid, then calls the get method to access the entry listNotes traverses the ArrayList and shows each note (along with its #)

26 Notebook class (cont.)... /** * Removes a note. noteNumber the number of the note to be removed (first note is # 0) */ public void removeNote(int noteNumber) { if (noteNumber = numberOfNotes()) { System.out.println("There is no note with that index."); } else { notes.remove(noteNumber); } /** * Removes a note. note the note to be removed */ public void removeNote(String note) { boolean found = false; for (int i = 0; i < notes.size(); i++) { if (note.equals(notes.get(i))) { notes.remove(i); found = true; } if (!found) { System.out.println("There is no such note."); }... one version of removeNote takes a note #, calls the remove method to remove the note with that number another version takes the text of the note and traverses the ArrayList – when a match is found, it is removed uses boolean variable to flag whether found or not

27 Arraylists & primitives ArrayLists can only store objects, but Java 5 will automatically box and unbox primitive types into wrapper classes (Integer, Double, Character, …) import java.util.ArrayList; public class DiceStats { public final static int DIE_SIDES = 6; public final static int NUM_ROLLS = 10000; public static void main(String[] args) { ArrayList counts = new ArrayList (); for (int i = 0; i <= 2*DIE_SIDES; i++) { counts.add(0); } Die die = new Die(DIE_SIDES); for (int i = 0; i < NUM_ROLLS; i++) { int roll = die.roll() + die.roll(); counts.set(roll, counts.get(roll)+1); } for (int i = 2; i <= 2*DIE_SIDES; i++) { System.out.println(i + ": " + counts.get(i) + " (" + (100.0*counts.get(i)/NUM_ROLLS) + "%)"); }

28 Java libraries Java provides extensive libraries of classes java.lang  StringMathBigInteger java.util  DateRandomTimer ArrayListLinkedList StackPriorityQueue TreeSetHashSet TreeMapHashMap even provides utility classes with useful algorithms Arrays.fill fills an array with a specified value Arrays.sort sorts an array of comparable items Arrays.binarySearch performs binary search on a sorted array Collections.fill fills a List with a specified value Collections.sort sorts a List of comparable items Collections.binarySearch performs binary search on a sorted List Collections.shuffle randomly shuffles the List contents

29 Non-OO programming in Java /** * Simple program that prints a table of temperatures * Dave Reed 3/5/05 */ public class FahrToCelsius { private static double FahrToCelsius(double temp) { return 5.0*(temp-32.0)/9.0; } public static void main(String[] args) { double lower = 0.0, upper = 100.0, step = 5.0; System.out.println("Fahr\t\tCelsius"); System.out.println("----\t\t "); for (double fahr = lower; fahr <= upper; fahr += step) { double celsius = FahrToCelsius(fahr); System.out.println(fahr + "\t\t" + celsius); } despite its claims as a pure OOP language, you can write non-OO code same as C++  static methods can call other static methods for large projects, good OO design leads to more reliable & more easily maintainable code