CISC 370: Introduction to Java

Similar documents
Review: Python Transi,on Warning

9/16/15. Review: Assign 0. Objec,ves. Review. Review: Python Transi,on Warning. What is the output? INTRO TO JAVA LIBRARIES

Objec+ves. Review. Basics of Java Syntax Java fundamentals. What are quali+es of good sooware? What is Java? How do you compile a Java program?

Lecture 2. COMP1406/1006 (the Java course) Fall M. Jason Hinek Carleton University

BASIC COMPUTATION. public static void main(string [] args) Fundamentals of Computer Science I

"Hello" " This " + "is String " + "concatenation"

CS11 Java. Fall Lecture 1

9/8/16. What is Programming? CSCI 209: So.ware Development. Discussion: What Is Good So.ware? CharacterisJcs of Good So.ware?

CS 11 java track: lecture 1

Program Fundamentals

Outline. Parts 1 to 3 introduce and sketch out the ideas of OOP. Part 5 deals with these ideas in closer detail.

Outline. Overview. Control statements. Classes and methods. history and advantage how to: program, compile and execute 8 data types 3 types of errors

Lecture 1: Overview of Java

Pace University. Fundamental Concepts of CS121 1

Full file at

CS 231 Data Structures and Algorithms, Fall 2016

Chapter 2 Using Data. Instructor s Manual Table of Contents. At a Glance. Overview. Objectives. Teaching Tips. Quick Quizzes. Class Discussion Topics

Object-Oriented Programming. Topic 2: Fundamental Programming Structures in Java

Chapter 1 Introduction to java

Full file at

COSC 123 Computer Creativity. Introduction to Java. Dr. Ramon Lawrence University of British Columbia Okanagan

Exam 1 Prep. Dr. Demetrios Glinos University of Central Florida. COP3330 Object Oriented Programming

Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal

Java Basic Programming Constructs

Index COPYRIGHTED MATERIAL

Fall 2017 CISC124 9/16/2017

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

Introduction Basic elements of Java

Java Language Basics: Introduction To Java, Basic Features, Java Virtual Machine Concepts, Primitive Data Type And Variables, Java Operators,

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

Variables and literals

Object-Oriented Programming

Programming with Java

Introduction to Software Development (ISD) David Weston and Igor Razgon

cis20.1 design and implementation of software applications I fall 2007 lecture # I.2 topics: introduction to java, part 1

Strings. Strings and their methods. Dr. Siobhán Drohan. Produced by: Department of Computing and Mathematics

CSC 1214: Object-Oriented Programming

DATA TYPES AND EXPRESSIONS

MPATE-GE 2618: C Programming for Music Technology. Syllabus

MODULE 02: BASIC COMPUTATION IN JAVA

Java language. Part 1. Java fundamentals. Yevhen Berkunskyi, NUoS

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

Basics of Java Programming

13 th Windsor Regional Secondary School Computer Programming Competition

Values and Variables 1 / 30

Fundamentals of Programming. By Budditha Hettige

CprE 288 Introduction to Embedded Systems Exam 1 Review. 1

Mobile Computing Professor Pushpendra Singh Indraprastha Institute of Information Technology Delhi Java Basics Lecture 02

COT 3530: Data Structures. Giri Narasimhan. ECS 389; Phone: x3748

Introduction to Programming Using Java (98-388)

COMP-202: Foundations of Programming. Lecture 5: Arrays, Reference Type, and Methods Sandeep Manjanna, Summer 2015

History of Java. Java was originally developed by Sun Microsystems star:ng in This language was ini:ally called Oak Renamed Java in 1995

CompSci 125 Lecture 02

JAVA OPERATORS GENERAL

Object oriented programming. Instructor: Masoud Asghari Web page: Ch: 3

CS5000: Foundations of Programming. Mingon Kang, PhD Computer Science, Kennesaw State University

Strings. Strings and their methods. Mairead Meagher Dr. Siobhán Drohan. Produced by: Department of Computing and Mathematics

CMPT 125: Lecture 3 Data and Expressions

Mr. Monroe s Guide to Mastering Java Syntax

Programming. Syntax and Semantics

Review Chapters 1 to 4. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

A variable is a name that represents a value. For

Expressions and Data Types CSC 121 Spring 2017 Howard Rosenthal

Programming with Java

5/23/2015. Core Java Syllabus. VikRam ShaRma

A variable is a name for a location in memory A variable must be declared

COMP 202. Built in Libraries and objects. CONTENTS: Introduction to objects Introduction to some basic Java libraries string

DM550 Introduction to Programming part 2. Jan Baumbach.

CONTENTS: Compilation Data and Expressions COMP 202. More on Chapter 2

Basic Computation. Chapter 2

PROGRAMMING FUNDAMENTALS

Zheng-Liang Lu Java Programming 45 / 79

2 rd class Department of Programming. OOP with Java Programming

Mathematical Functions, Characters, and Strings. CSE 114, Computer Science 1 Stony Brook University

Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following groups:

Tools : The Java Compiler. The Java Interpreter. The Java Debugger

Programming Language Basics

Getting started with Java

Object-oriented programming. and data-structures CS/ENGRD 2110 SUMMER 2018

What did we talk about last time? Examples switch statements

Chapter 2: Data and Expressions

12/22/11. Java How to Program, 9/e. Help you get started with Eclipse and NetBeans integrated development environments.

5/3/2006. Today! HelloWorld in BlueJ. HelloWorld in BlueJ, Cont. HelloWorld in BlueJ, Cont. HelloWorld in BlueJ, Cont. HelloWorld in BlueJ, Cont.

appreciate the difference between a char and a string understand and use the String class methods

Last Time. University of British Columbia CPSC 111, Intro to Computation Alan J. Hu. Readings

Datatypes, Variables, and Operations

Data and Variables. Data Types Expressions. String Concatenation Variables Declaration Assignment Shorthand operators. Operators Precedence

CIS192 Python Programming. Robert Rand. August 27, 2015

Introduction To Java. Chapter 1. Origins of the Java Language. Origins of the Java Language. Objects and Methods. Origins of the Java Language

Course Outline. Introduction to java

Midterms Save the Dates!

Lecture Notes. System.out.println( Circle radius: + radius + area: + area); radius radius area area value

Crash Course in Java. Why Java? Java notes for C++ programmers. Network Programming in Java is very different than in C/C++

COMP 202 Java in one week

CSE 421 Course Overview and Introduction to Java

CS313D: ADVANCED PROGRAMMING LANGUAGE

Java Fall 2018 Margaret Reid-Miller

CS 106 Introduction to Computer Science I

Lexical Structure (Chapter 3, JLS)

Computer Components. Software{ User Programs. Operating System. Hardware

Transcription:

CISC 370: Introduction to Java Instructor: Sara Sprenkle sprenkle@cis cis.udel.eduedu TA: Ke Li kli@cis cis.udel.eduedu 1

What is Java? and, why should I learn it? Sara Sprenkle - CISC370 2

What is Java? and, why should I learn it? From Sun Microsystems 1995, James Gosling and Patrick Naughton Specifications Develop cross-platform applications Web, desktop, embedded Object-oriented Simpler than C++ Rich and large library Sara Sprenkle - CISC370 3

What to Expect from this Class Programming intensive Interesting assignments and projects More freedom in design Building on large library of classes Compare/Contrast with C++ Learning on your own Online resources Sara Sprenkle - CISC370 4

Class Details Tuesday, Thursday lectures Quiz at beginning of each Tuesday class See web page for example code, lecture slides Expected Participation Optional Textbooks Use plentiful online resources instead! Sara Sprenkle - CISC370 5

Class Details Weekly Programming Assignments Due one week after assigned 2 Projects Demos with TA and me 1 Exam Final: TBD but August 11ish Course Project Manager https://128.4.133.74:8080/scheduler/group.html For viewing grades and scheduling demos Sara Sprenkle - CISC370 6

Course Dynamics Professor's Responsibilities: Be prepared for class Correct students non-judgmentally Treat students with respect Challenge and encourage students Make class material as clear as possible Student's Responsibilities: Be prepared for class (do readings and homework) Give attention and effort in class to learning Ask questions (during class and via email) Use professor's and TA s office hours when you re having trouble Let professor know if something is going wrong Treat other students, TA, and professor with respect Sara Sprenkle - CISC370 7

Survey Says More about you! Sara Sprenkle - CISC370 8

What is Java? Java Programming Language Java Virtual Machine Java Class Libraries Sara Sprenkle - CISC370 9

Java Programming Language Entirely object-oriented Similar to C++ Program.java Compiler javac Program.class Written in Java Programming Language Bytecode: machine code for a virtual CPU Sara Sprenkle - CISC370 10

Java Virtual Machine (JVM) Emulates the CPU, usually specified in software Executes the program s bytecode Bytecode: : virtual machine code Different versions for each platform Java supports program portability Sara Sprenkle - CISC370 11

Java Virtual Machine (JVM) Mac JVM Program.class UNIX JVM Bytecode Windows JVM Same bytecode executes on each platform What happens in C++? Sara Sprenkle - CISC370 12

Java Class Libraries Pre-defined classes Included with the Java 2 Software Development Kit (SDK) and the Java 2 Runtime Environment (JRE) View the available classes online: http://java.sun.com/j2se/1.5.0/docs/api/index.html Similar in purpose to library functions included with ANSI C Sara Sprenkle - CISC370 13

Benefits of Java Rapid development of programs Large library of classes, including GUIs Portability run program on multiple platforms without recompiling Sara Sprenkle - CISC370 14

Which Java is this class about? Java programming language Java class libraries Use the JVM but won t t learn about how it works For more information: http://java.sun.com/docs/books/vmspec/ Sara Sprenkle - CISC370 15

Java Development Kit (J2SDK) J2SDK: Java 2 Software Development Kit Free from Sun Contains javac: : Java compiler java: Java Virtual Machine Java class libraries Sara Sprenkle - CISC370 16

Java Development Kit (J2SDK) Installed on strauss Java 1.5 should be reachable using default path If not, add /usr/java1.5/bin to your path http://www.udel.edu/topics/os/unix/package/java/ Run java -version to determine which version you re running You can download the JDK for your machine from http://java.sun.com/j2se/1.5.0/download.jsp JRE is for running Java applications does not include the compiler Sara Sprenkle - CISC370 17

Summary of Java Platform SE 5.0 Image from Sun s site Sara Sprenkle - CISC370 18

Using the J2SDK Compile and run TestProgram.java javac TestProgram.java Compiles the program into TestProgram.class java TestProgram Runs the JVM, which executes the bytecode Sara Sprenkle - CISC370 19

Intro to Java Programming Language Examples Data types Control structures Sara Sprenkle - CISC370 20

First Java Program public class Hello { public static void main(string[] args) { System.out.println( Hello ); } } Sara Sprenkle - CISC370 21

First Java Program public class Hello { public static void main(string[] args) { System.out.println( Hello ); } } Everything in Java is inside a class This class is named Hello Sara Sprenkle - CISC370 22

First Java Program public class Hello { public static void main(string[] args) { System.out.println( Hello ); } } Access Modifier: controls if other classes can use code in this class Sara Sprenkle - CISC370 23

First Java Program public class Hello { public static void main(string[] args) { System.out.println( Hello ); } } Defines the class Hello Sara Sprenkle - CISC370 24

First Java Program public class Hello { public static void main(string[] args) { System.out.println( Hello ); } method } Class contains one method Functions are called methods in Java Sara Sprenkle - CISC370 25

First Java Program public class Hello { public static void main(string[] args) { System.out.println( Hello ); } } main methods Similar to main in C++ Takes one parameter: an array of Strings Must be public static Must be void: returns nothing Sara Sprenkle - CISC370 26

First Java Program public class Hello { public static void main(string[] args) { System.out.println( Hello ); } } Method contains one line of code What do you think it does? Sara Sprenkle - CISC370 27

First Java Program public class Hello { public static void main(string[] args) { System.out.println( Hello ); } } Calls the println method on the System.out object println takes one parameter, a String Displays string on terminal, terminates the line with new line (\n) character Sara Sprenkle - CISC370 28

First Java Program /* Our first Java program */ public class Hello { public static void main(string[] args) { // Print a message System.out.println( Hello ); } } Comments: same as C++ /* */ or // Sara Sprenkle - CISC370 29

Java Fundamentals Sara Sprenkle - CISC370 30

Java keywords/reserved words Case-sensitive Can t t be used for variable or class names Many same as in C/C++ Seen so far public class static void Exhaustive list Exhaustive list http://java.sun.com/docs/books/tutorial/java/nutsandbolts/_keywords.html Sara Sprenkle - CISC370 31

Data Types Java is strongly-typed Every variable must be a declared type All data in Java is an object except for the primitive data types int 4 bytes (-2,147,483,648 -> 2,147,483,647) short 2 bytes (-32,768 -> 32,767) long 8 bytes (really big integers) byte 1 byte (-128 -> 127) float 4 bytes (floating point) double 8 bytes (floating point) char 2 bytes (Unicode representation) boolean false or true Sara Sprenkle - CISC370 32

Variables Declared and initialized same as C and C++ Typically, names start with lowercase letter _ also a valid first character Convention: Subsequent words are capitalized Called Camel Casing Examples: int x; double pi = 3.14; char q = p ; boolean isvalid = false; Camel Casing Sara Sprenkle - CISC370 33

More Data Type Information Default data types Result of integer division is an int Same as C++ Example: 1/2 =?? Casting Same as C++ for primitive types Example: 1/(double) 2 Sara Sprenkle - CISC370 34

Constants Read-only variables Cannot be assigned new value Keyword final precedes data type final double CM_PER_INCH = 2.540; What was the equivalent keyword in C++? Sara Sprenkle - CISC370 35

Class Constants Constant variable for all methods in class or for multiple classes Much more common than constant instance variables Requires static keyword static: for whole class Also used for methods (will see later) public static final double CM_PER_IN = 2.540; Sara Sprenkle - CISC370 36

Operators Java has most of the same operators as C and C++: +, -, *, /, % (add, subtract, multiple, divide, modulus) ++ and -- (increment and decrement) ==,!=, <, >, <=, >= (relational operators, evaluate to a boolean value) &&,,! (logical operators: AND, OR, NOT) &,, ^, ~ (bitwise AND, OR, XOR, NOT) Sara Sprenkle - CISC370 37

Mathematical Functions and Constants java.lang lang.math class Similar to <math.h> Included in the Java class libraries in the JDK Included by default in every Java program Includes useful mathematical functions (methods) and related constants (final( values): double y = Math.pow pow(x, a); double z = Math.sin(y); double d = Math.exp(4.59) * Math.PI; Look at java.lang lang.math API online Sara Sprenkle - CISC370 38

Java API Documentation API: Application Programming Interface What the class can do for YOU! Complete documentation on every class included with the JDK and on every method and variable contained within each class. http://java.sun.com/j2se/1.5.0/docs/api/ Bookmark it! Too many classes, methods to remember them all Refer to it often Sara Sprenkle - CISC370 39

Strings Java makes strings very easy, compared to C, C++, and many other languages. The Java class libraries include a predefined String class in java.lang lang.string All java.lang classes are automatically included in Java programs Sara Sprenkle - CISC370 40

Strings Strings are represented by double quotes: Examples: String emptystring = ; String nicegreeting = Hello there. ; String badgreeting = What do you want? ; Note that you don t need to specify the String s size Sara Sprenkle - CISC370 41

String Concatenation Use + operator to concatenate Strings String nicegreeting = Hello ; String firstname = Clark ; String lastname = Kent ; String blankspace = ; String greeting = nicegreeting +, + blankspace + firstname + blankspace + lastname; System.out.println(greeting); Prints Hello, Clark Kent Sara Sprenkle - CISC370 42

String Concatenation If a string is concatenated with something that is not a string, the other variable is converted to a string. int totalpoints = 110; int earnedpoints = 87; float testscore = (float)earnedpoints/totalpoints; System.out.println( Your score is + testscore); Sara Sprenkle - CISC370 43

String methods: substring String substring(int beginindex) Returns a new string that is a substring of this string, from beginindex through end of this string String substring(int beginindex, int endindex) Returns a new string that is a substring of this string, from beginindex to endindex String greeting = Hello, Clark Kent! ; String substr = greeting.substring(7); String substr2 = greeting.substring(7, 11); Sara Sprenkle - CISC370 44

String methods: equal boolean equals(object anobject) Compares this string to the specified object String string1 = Hello ; String string2 = hello ; boolean test; test = string1.equals(string2); test is false because the strings are different Sara Sprenkle - CISC370 45

String methods: equal string1 == string2 will not yield the same result Tests if the objects are the same Not if the contents of the objects are the same Sara Sprenkle - CISC370 46

String methods: equalsignorecase Does what it s s named! String string1 = Hello ; String string2 = hello ; boolean test; test = string1.equalsignorecase equalsignorecase(string2); test is true! Sara Sprenkle - CISC370 47

String methods: charat A String is a collection of characters String teststring1; teststring1 = Demonstrate Strings ; char character1; char character2 = teststring1.charat(3); character1 = teststring1.charat(2); Sara Sprenkle - CISC370 48

String methods: and many more! boolean endswith(string suffix) boolean startswith(string prefix) length() tolowercase() trim(): remove trailing and leading white space See Java API for java.lang lang.string for all Sara Sprenkle - CISC370 49

Control Structures Sara Sprenkle - CISC370 50

Control Flow: Conditional Statements if statement (booleans are not ints in Java) if (purchaseamount( < availablecredit) { } Condition must evaluate to a boolean availablecredit = availablecredit purchaseamount; System.out.println println( Approved ); else System.out.println println( Denied ); Sara Sprenkle - CISC370 51

Control Flow: Conditional Statements if statement if (purchaseamount( < availablecredit) { } availablecredit = availablecredit purchaseamount; System.out.println println( Approved ); else System.out.println println( Denied ); Block of code Sara Sprenkle - CISC370 52

Blocks of Code Everything between { } is a block of code Has an associated scope Sara Sprenkle - CISC370 53

Control Flow: Conditional Statements switch statement int x = 3; switch(x) { case (1) : System.out.println println( It s s a 1. ); break; case (2) : System.out.println println( It s s a 2. ); break; default: System.out.println println( Not a 1 or 2. ); } Sara Sprenkle - CISC370 54

Control Flow: while Loops int counter = 0; while (counter < 10) { } System.out.println println(counter); counter++; System.out.println println( Done. Done. ); Sara Sprenkle - CISC370 55

Control Flow: do-while loop Loop runs at least once int counter = 0; do { System.out.println println(counter); counter++; } while (counter < 10); Sara Sprenkle - CISC370 56

Control Flow: for Loop for (int( count=10; count >= 1; count--) { } System.out.println println( Counting down + count); System.out.println println( Blastoff! Blastoff! ); Sara Sprenkle - CISC370 57

Control Flow: foreach Loop New to Java 1.5 Sun calls enhanced for loop Iterate over all elements in an array (or Collection) Simple, easy-to-read form int[] a; int result = 0;... for (int i : a) { result += i; } for each int element i in the array a The loop body is visited once for each value of i. Sara Sprenkle - CISC370 58

Changing control flow: break In general, I do not recommend using break But, you should know it for reading other people s s code Exits the current loop while ( <readingdata> ) { if( data is null ) { // shouldn t happen break; } } Sara Sprenkle - CISC370 59

Changing control flow: labeled break Does not exist in C++ Add a label to a block of code tagged_loop: while ( <readingdata> ) { for ( ) { // not tagged if( error condition ) { // get out of both loops break tagged_loop; } } } Sara Sprenkle - CISC370 60

Changing control flow: continue Jump to the next iteration of the loop while ( <readingdata> ) { if( data is null ) { // shouldn t happen continue; } dostuff(); } Alternative way to write code without using continue? Sara Sprenkle - CISC370 61

Arrays To declare an array of integers: int[] arrayofints; declaration makes only a variable named arrayofints does not initialize array or allocate memory for the elements To declare and initialize array of integers: int[] arrayofints = new int[100]; Sara Sprenkle - CISC370 62

Array Initialization Initialize an array at its declaration: int [] fibnumbs = {1, 1, 2, 3, 5, 8, 13}; Note that we do not use the new keyword when allocating and initializing an array in this manner Sara Sprenkle - CISC370 63

Array Length All array variables have a field called length int[] array = new int[10]; for (int( a = 0; a < array.length; ; a++) { } array[a] = 6; for (int( a = 0; a < array.length; ; a++) { } System.out.println println(array [a]); Sara Sprenkle - CISC370 64

Overstepping Array Length Java safeguards against overstepping length of array Runtime Exception: Array index out of bounds More on exceptions later int[] arrayofints = new int[100]; Attempts to access or write to index < 0 or index >= array.length (100) will generate exception Sara Sprenkle - CISC370 65

Array Copying It is possible to copy one array variable into another, but then both variables refer to the same array like manipulating pointers in C++ int [] fibnumbs = {1, 1, 2, 3, 5, 8, 13}; int [] otherfibnumbs; otherfibnumbs = fibnumbs; otherfibnumbs[2] = 99; fibnumbs[2] and otherfibnumbs[2] are both equal to 99. System.out.println(otherFibNumbs[2]); System.out.println(fibNumbs[2]); Sara Sprenkle - CISC370 66

Array Copying The copying of an array (element-by-element) can be done using the arraycopy method in the System class System.arraycopy arraycopy(from, fromindex,, to, toindex, count); For example: int [] fibnumbs = {1, 1, 2, 3, 5, 8, 13}; int [] otherfibnumbs = new int[7]; System.arraycopy(fibNumbs,0,otherFibNumbs,0,7); otherfibnumbs[2] = 99; System.out.println(otherFibNumbs[2]); System.out.println(fibNumbs[2]); fibnumbs[2] = 2, otherfibnumbs[2]= 99 Sara Sprenkle - CISC370 67

Arrays: Java vs C++ int[] array = new int[100]; // Java is not the same as: int array[100]; but is the same as: // C++ int * array = new int[100] // C++ array variable is the same as a pointer that points to the beginning of an array in C++. Sara Sprenkle - CISC370 68