JVM (java) compiler. A Java program is either a library of static methods (functions) or a data type definition

Similar documents
Introduction to Programming Using Java (98-388)

1.1 BASIC PROGRAMMING MODEL

Basic Data Structures

Analysis of Algorithms 1 / 18

Pace University. Fundamental Concepts of CS121 1

Basic Data Structures 1 / 24

CSC Java Programming, Fall Java Data Types and Control Constructs

Index COPYRIGHTED MATERIAL

CMAT Language - Language Reference Manual COMS 4115

1 Lexical Considerations

Chapter 2: Using Data

CS11 Java. Fall Lecture 1

Features of C. Portable Procedural / Modular Structured Language Statically typed Middle level language

CS313D: ADVANCED PROGRAMMING LANGUAGE

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

VENTURE. Section 1. Lexical Elements. 1.1 Identifiers. 1.2 Keywords. 1.3 Literals

Program Fundamentals

Lexical Considerations

Lexical Considerations

Java Bytecode (binary file)

CS313D: ADVANCED PROGRAMMING LANGUAGE

CS 61B Data Structures and Programming Methodology. June David Sun

Java+- Language Reference Manual

Full file at

Primitive Data Types: Intro

Simple Java Reference

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

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

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

Lecture 3. More About C

COS 126 General Computer Science Spring Written Exam 1

Instructions. This exam has 7 questions, worth 10 points each. You have 50 minutes.

F1 A Java program. Ch 1 in PPIJ. Introduction to the course. The computer and its workings The algorithm concept


1.1 Basic Programming Model 1.2 Data Abstrac9on

PROGRAMMING FUNDAMENTALS

Course PJL. Arithmetic Operations

Unit 2: Java in the small. Prepared by: Dr. Abdallah Mohamed, AOU-KW

2.2 Libraries and Clients

CSC 1214: Object-Oriented Programming

C-LANGUAGE CURRICULAM

1 Shyam sir JAVA Notes

More non-primitive types Lesson 06

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

Symbol Tables 1 / 15


Unit 2: Java in the small

Introduction to Visual Basic and Visual C++ Introduction to Java. JDK Editions. Overview. Lesson 13. Overview

Introduction to Java Applications

The Warhol Language Reference Manual

Java Basic Programming Constructs

An overview of Java, Data types and variables

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

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

1.1 Your First Program! Naive ideal. Natural language instructions.

MODULE 02: BASIC COMPUTATION IN JAVA

Computational Expression

1.1 Your First Program

Getting started with Java

Flow Control. CSC215 Lecture

1.1 Your First Program

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

Chapter 2: Using Data

Declaration and Memory

3. Java - Language Constructs I

Full file at

Lecture 2: C Programming Basic

Operators. Java operators are classified into three categories:

CS Programming I: Primitives and Expressions

Numerical Data. CS 180 Sunil Prabhakar Department of Computer Science Purdue University

Java Primer 1: Types, Classes and Operators

SECTION II: LANGUAGE BASICS

The Command Shell, Libraries and Clients, Formatted Printing. Fundamentals of Computer Science

Fundamental of Programming (C)

DATA TYPES AND EXPRESSIONS

UNIT - I. Introduction to C Programming. BY A. Vijay Bharath

C Language Part 1 Digital Computer Concept and Practice Copyright 2012 by Jaejin Lee

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

Programming with Java

Operators and Expressions

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

CSI33 Data Structures

CS 231 Data Structures and Algorithms, Fall 2016

Programming Language Basics

1 Introduction Java, the beginning Java Virtual Machine A First Program BlueJ Raspberry Pi...

Data Types, Variables and Arrays. OOC 4 th Sem, B Div Prof. Mouna M. Naravani

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

Programming Language Concepts: Lecture 2

CS 11 java track: lecture 1

C Syntax Out: 15 September, 1995

Language Reference Manual

CS4120/4121/5120/5121 Spring 2016 Xi Language Specification Cornell University Version of May 11, 2016

Review. Primitive Data Types & Variables. String Mathematical operators: + - * / % Comparison: < > <= >= == int, long float, double boolean char

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

Object oriented programming C++

Review for Test 1 (Chapter 1-5)

Chapter 4 Defining Classes I

CSCI 135 Exam #1 Fundamentals of Computer Science I Fall 2012

CSC Web Programming. Introduction to JavaScript

Chapter 2: Data and Expressions

Transcription:

Programming Model

Basic Structure of a Java Program The Java workflow editor (Code) P.java compiler (javac) P.class JVM (java) output A Java program is either a library of static methods (functions) or a data type definition To create a Java program (class), we use the following programming constructs Primitive data types and expressions Statements Arrays Static methods Strings Input and output (IO) Data abstraction

Basic Structure of a Java Program Example (Java program that computes N!) import edu. princeton. cs. algs4. StdOut ; public class Factorial { // Returns N! public static int factorial ( int N) { int result = 1; for ( int i = 1; i <= N; i ++) { result *= i; return result ; // Test client public static void main ( String [] args ) { int N = Integer. parseint ( args [0]); StdOut. println (N + "! = " + Factorial. factorial (N )); $ javac Factorial. java $ java Factorial 5 5! = 120

Primitive Data Types and Expressions A data type (primitive or reference) is a set of values and a set of operations on those values Primitive types boolean: true and false values with logical operations (!,, and &&) byte: 8-bit integers with arithmetic operations (+, -, *, /, and %) char: 16-bit characters with arithmetic operations short: 16-bit integers with arithmetic operations int: 32-bit integers with arithmetic operations float: 32-bit single-precision real numbers with arithmetic operations long: 64-bit integers with arithmetic operations double: 64-bit double-precision real numbers with arithmetic operations

Primitive Data Types and Expressions An expression is a literal, a variable, or a sequence of allowed operations on literals and/or variables that produces a value Arithmetic operators * and / have higher precedence than + and - Among logical operators,! has the highest precedence, followed by && and then Two operands of the same type can be compared using the relational operators ==,!=, <, <=, >, and >=, producing a boolean result Relational operators have higher precedence than logical operators but lower precedence than arithmetic operators Operators of the same precedence are evaluated left to right Parentheses can be used to override precedence rules Numbers are automatically promoted to a more inclusive type A cast is a type name in parentheses within an expression, and converts the following value into a value of that type double x = ( double ) 42;

Statements A statement defines computation by creating variables, assigning data-type values to them, and controlling the flow of execution A declaration statement associates a variable name with a type <type > <name >; where the initial value for the variable is false for boolean type, 0 for numeric types, and null for reference types An assignment statement associates a data-type value with a variable <name > = <expression >; Declaration and assignment statements can be combined to provide an initial value for a variable <type > <name > = <expression >;

Statements A conditional statement is used when different actions are required for different inputs If statement if (< boolean expression >) { <statements > else if (< boolean expression >) { <statements >... else { <statements > Conditional operator (really an expression) <boolean expression >? <expression > : <expression > Switch statement switch (< expression >) { case <value >: <statements > case <value >: <statements >... default : <statements >

Statements A loop statement is used for repetitive computations While statement while (< boolean expression >) { <statements > For statement for (< initialize >; < boolean expression >; <increment >) { <statements > Do-while statement do { <statements > while (< boolean expression >); A break statement immediately exits a loop without letting it run to completion; when used as the last statement in a switch case, exits the switch statement preventing fallthrough to the following case A continue statement skips to next iteration of a loop

Statements A compound assignment statement is shorthand notation for modifying the value of a variable For example i += 5; is equivalent to i = i + 5; i++; is equivalent to i = i + 1; --i; is equivalent to i = i - 1; The scope of a variable is the statements that follow the declaration in the same block (marked by curly brackets) as the declaration

Arrays An array stores a sequence of values that are all of the same type Making an array in Java involves: declaring the array name and type; creating the array; and initializing the array values int [] a; a = new int [10]; for ( int i = 0; i < 10; i ++) { a[i] = i; An array when declared is initialized to null, and once created, each element is initialized to a default value based on the type of the array Initializing declaration int [] a = {1, 1, 2, 3, 5, 8, 13, 21, 34, 55; String [] b = {" Sun ", " Mon ", " Tue ", " Wed ", " Thu ", " Fri ", " Sat "; Example (reversing an array in place) int N = a. length ; for ( int i = 0; i < N / 2; i ++) { double temp = a[i]; a[i] = a[n - 1 - i]; a[n - i - 1] = temp ;

Arrays If we assign one array name to another (aliasing), then both refer to the same array A two-dimensional array in Java is an array of one-dimensional arrays, and may be ragged Initializing declaration for two-dimensional arrays int [][] I = {{1, 0, 0, {0, 1, 0, {0, 0, 1; Example (matrix multiplication C ij = p k=1 A ikb kj, where A is an m p, B is a p n, and C is an m n matrix) int m = A. length ; int p = B. length ; int n = B [0]. length ; double [][] C = new double [m][n]; for ( int i = 0; i < m; i ++) { for ( int j = 0; j < n; j ++) { for ( int k = 0; k < p; k ++) { C[i][j] += A[i][k] * B[k][j];

Static Methods A method encapsulates a computation defined as a sequence of statements A static method is composed of the keywords public static followed by a return type (or void), the signature (method name and a sequence of arguments, each with a declared type), and a body (a sequence of statements enclosed by curly brackets) Example (primality testing) public static boolean isprime ( int N) { if (N < 2) { return false ; for ( int i = 2; i <= N / i; i ++) { if (N % i == 0) { return false ; return true ; A call on a static method is its name followed by expressions that specify argument values in parentheses, separated by commas When a method call is part of an expression, the method computes a value and that value is used in place of the call in the expression Properties of methods Arguments are passed by value Method names can be overloaded A method has a single return value but may have multiple return statements A method can have side effects

Static Methods A recursive method is one that calls itself, has a base case, addresses subproblems that are smaller in some sense, and does not address subproblems that overlap Example of good recursion (computing N!) { N(N 1)! if N > 0, and N! = 1 if N = 0 public static int f( int N) { return (N == 0)? 1 : N * f(n - 1); Call trace for f(5) f (5) f (4) f (3) f (2) f (1) f (0) return 1 return 1 * 1 = 1 return 2 * 1 = 2 return 3 * 2 = 6 return 4 * 6 = 24 return 5 * 24 = 120

Static Methods Example of bad recursion (computing Nth Fibonacci number) f(n) = { f(n 1) + f(n 2) if N > 1, and 1 if N = 0 or N = 1 public static int f( int N) { return (N == 0 N == 1)? 1 : f(n - 1) + f(n - 2); Call trace for f(5)

Static Methods A best practice in Java programming is to include a main() method (aka development or test client) in every library of static methods We use static methods from four different kinds of libraries Standard system libraries java.lang.* Imported system libraries such as java.util.arrays Other libraries in the text Standard libraries edu.princeton.cs.algs4.* from the text

APIs An application programming interface (API) lists the library name and the return type, signatures, and short descriptions of each of the methods A client is a program that calls a method in another library An implementation is Java code that implements the methods in an API Standard system library (java.lang.math) method description static double abs(double a) a static double max(double a, double b) max(a, b) static double min(double a, double b) min(a, b) static double sin(double theta) sin(θ) static double cos(double theta) cos(θ) static double tan(double theta) tan(θ) static double random() real [0, 1) static double E e static double PI π...... Imported system library (java.util.arrays) method description static void sort(int[] a) put the array in ascending order......

APIs Standard libraries from the text edu.princeton.cs.algs4.stdrandom method description static void initialize(long seed) initialize static double random() real [0, 1) static int uniform(int N) integer [0, N) static int uniform(int lo, int hi) integer [lo, hi) static double uniform(double lo, double hi) real [lo, hi) static boolean bernoulli(double p) true with probability p static double gaussian() real N (0, 1) static double gaussian(double m, double s) real N (m, s) static int discrete(double[] a) i with probability a[i] static void shuffle(double[] a) shuffle the array...... edu.princeton.cs.algs4.stdstats method description static double max(double[] a) largest value static double min(double[] a) smallest value static double mean(double[] a) average static double var(double[] a) sample variance static double stddev(double[] a) sample standard deviation static double median(double[] a) median......

Strings A string is a sequence of characters (char values) A string literal is a sequence of characters within double quotes, such as "Hello, World" The result of concatenating two strings using the + operator is a single string, the first string followed by the second We use Java library methods such as Integer.parseInt(), Double.parseDouble(), and so on to convert strings to primitives We use the + operator to convert primitives to strings

Input and Output Bird s-eye biew of a Java program input P.java output Input types: command-line arguments, standard input, file input Output types: standard output, file output Command-line arguments are listed after the program name as follows $ java P arg_1 arg_2... arg_n and accessed within the main() method of the program via the array args as args[0], args[1],..., args[n - 1] Example import edu. princeton. cs. algs4. StdOut ; public class UseArgument { public static void main ( String [] args ) { StdOut. print ("Hi, "); StdOut. print ( args [0]); StdOut. println (". How are you?"); $ java UseArgument Alice Hi, Alice. How are you? $ java UseArgument Bob Hi, Bob. How are you?

Input and Output Standard output (edu.princeton.cs.algs4.stdout) API method description static void println(string s) print s, followed by a newline static void printf(string f,...) formatted print...... Example import edu. princeton. cs. algs4. StdOut ; import edu. princeton. cs. algs4. StdRandom ; public class RandomSeq { public static void main ( String [] args ) { int N = Integer. parseint ( args [0]); double lo = Double. parsedouble ( args [1]); double hi = Double. parsedouble ( args [2]); for ( int i = 0; i < N; i ++) { double x = StdRandom. uniform (lo, hi ); StdOut. printf (" %.2 f\n", x); $ java RandomSeq 2 100.0 200.0 193.12 190.79

Input and Output Standard input (edu.princeton.cs.algs4.stdin) API method description static boolean isempty() true if no more values, false otherwise static int readint() read a value of type int static double readdouble() read a value of type double...... Example import edu. princeton. cs. algs4. StdIn ; import edu. princeton. cs. algs4. StdOut ; public class Average { public static void main ( String [] args ) { int count = 0; double sum = 0.0; while (! StdIn. isempty ()) { double value = StdIn. readdouble (); sum += value ; count ++; double average = sum / count ; StdOut. println (" Average is " + average ); $ java Average 1 2 3 4 5 <ctrl -d> Average is 3.0

Input and Output Output redirection $ java RandomSeq 1000 100.0 200.0 > data. txt $ head -5 data. txt 155.83 191.65 197.83 191.90 111.84 Input redirection $ java Average < data. txt Average is 149.1812199999999 Piping $ java RandomSeq 1000 100.0 200.0 java Average Average is 150.0588699999999