Java is an objet-oriented programming language providing features that support

Similar documents
CSCI 136 Data Structures & Advanced Programming. Fall 2018 Instructors Bill Lenhart & Bill Jannen

Introduction to Programming Using Java (98-388)

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

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

3. Java - Language Constructs I

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

Primitive Data, Variables, and Expressions; Simple Conditional Execution

Chapter 3: Operators, Expressions and Type Conversion

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

Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal

JAVA OPERATORS GENERAL

CSc 10200! Introduction to Computing. Lecture 2-3 Edgardo Molina Fall 2013 City College of New York

Full file at

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

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

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

Objects and Types. COMS W1007 Introduction to Computer Science. Christopher Conway 29 May 2003

A Java program contains at least one class definition.

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

Programming in C++ 5. Integral data types

egrapher Language Reference Manual

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

Prof. Navrati Saxena TA: Rochak Sachan

Review for Test 1 (Chapter 1-5)

Operators. Java operators are classified into three categories:

Sir Muhammad Naveed. Arslan Ahmed Shaad ( ) Muhammad Bilal ( )

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

COMP 202 Java in one week

CSC 1214: Object-Oriented Programming

CSCI 136 Data Structures & Advanced Programming. Lecture 3 Fall 2017 Instructors: Bill & Bill

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

1 Lexical Considerations

Unit-II Programming and Problem Solving (BE1/4 CSE-2)

Pace University. Fundamental Concepts of CS121 1

Will introduce various operators supported by C language Identify supported operations Present some of terms characterizing operators

SECTION II: LANGUAGE BASICS

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Spring 2016 Howard Rosenthal

3. Java - Language Constructs I

Computer Programming, I. Laboratory Manual. Experiment #3. Selections

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

Control Structures in Java if-else and switch

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Fall 2016 Howard Rosenthal

Values and Variables 1 / 30

Two Types of Types. Primitive Types in Java. Using Primitive Variables. Class #07: Java Primitives. Integer types.

MODULE 02: BASIC COMPUTATION IN JAVA

Programming with Java

A flow chart is a graphical or symbolic representation of a process.

PROGRAMMING FUNDAMENTALS

CSCI 136 Data Structures & Advanced Programming. Lecture 3 Fall 2018 Instructors: Bill & Bill

By the end of this section you should: Understand what the variables are and why they are used. Use C++ built in data types to create program

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

Building Java Programs

Java Notes. 10th ICSE. Saravanan Ganesh

COMP 202. Java in one week

Midterm I - CSE11 Fall 2013 CLOSED BOOK, CLOSED NOTES 50 minutes, 100 points Total.

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

Chapter 2: Data and Expressions

CS 106 Introduction to Computer Science I

Control Structures in Java if-else and switch

CSCI 2010 Principles of Computer Science. Data and Expressions 08/09/2013 CSCI

School of Computer Science CPS109 Course Notes 5 Alexander Ferworn Updated Fall 15

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

Building Java Programs

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

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

UNIT- 3 Introduction to C++

Building Java Programs. Chapter 2: Primitive Data and Definite Loops

Expressions and Data Types CSC 121 Spring 2017 Howard Rosenthal

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

CS171:Introduction to Computer Science II

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

AP Computer Science A

Basic C Programming (2) Bin Li Assistant Professor Dept. of Electrical, Computer and Biomedical Engineering University of Rhode Island

IPCoreL. Phillip Duane Douglas, Jr. 11/3/2010

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

Lexical Considerations

Sequence structure. The computer executes java statements one after the other in the order in which they are written. Total = total +grade;

Lexical Considerations

Basics of Java Programming

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

CMPT 125: Lecture 3 Data and Expressions

LESSON 1. A C program is constructed as a sequence of characters. Among the characters that can be used in a program are:

Full file at

Introduction to Object-Oriented Programming

Object-Oriented Programming

Program Fundamentals

DEPARTMENT OF MATHS, MJ COLLEGE

QUIZ. 1. Explain the meaning of the angle brackets in the declaration of v below:

Bits, Words, and Integers

Java Basic Programming Constructs

CS113: Lecture 3. Topics: Variables. Data types. Arithmetic and Bitwise Operators. Order of Evaluation

The Arithmetic Operators. Unary Operators. Relational Operators. Examples of use of ++ and

The Arithmetic Operators

Lecture 2: Variables and Operators. AITI Nigeria Summer 2012 University of Lagos.

Operators in java Operator operands.

Visual C# Instructor s Manual Table of Contents

ECE 122 Engineering Problem Solving with Java

Contents. Figures. Tables. Examples. Foreword. Preface. 1 Basics of Java Programming 1. xix. xxi. xxiii. xxvii. xxix

Handout 4 Conditionals. Boolean Expressions.

Introduction to Programming (Java) 2/12

Transcription:

Java Essentials CSCI 136: Spring 2018 Handout 2 February 2 Language Basics Java is an objet-oriented programming language providing features that support Data abstraction Code reuse Modular development of large systems Automated low-level memory management Type-safety & Security Error-handling Multiple threads of computation Portability While its syntax can be occasionally awkward, the benefits of the language over time have substantially outweighed its weaknesses. This purpose of this document is to briefly summarize the essential elements of Java. Executing a Java program that has been entered into a text file, say MyProgram.java, using a Unix command shell (a program for entering commands in the Unix operating system) requires two steps. Compiling javac MyProgram.java Running java MyProgram The javac command converts the Java source code to an intermediate low-level language called Java bytecode. The bytecode will be placed into a file called MyProgram.class, (a Java class file). Assuming that the source code contained a method (aka procedure/function) called main, the java command will execute the code in the main method. Example: Hello World. There s a lot of syntactic overhead involved in writing this simple program. This is not an uncommon situation with programming languages that are designed for writing large, modular systems. You ll get used to it quickly. The next few topics talk about the non-object-oriented features of Java. After covering them, we ll revisit them from the perspective of object-oriented programming. Data Types in Java Programs store and manipulate data (sometimes called state). Data is held in variables. Java requires that every variable be declared, that is, be given an explicit type, before it can be used. For example: int age; float speed; char grade; String name; int[] scores; // A simple integer value // A numeric value with a fractional component // A single character // A sequence of characters // A one-dimensional array of integers A variable can be declared without being assigned a value, but a value can be provided in the declaration: Note that we omit the.class file suffix. 1

int age = 21; float speed = 47.25; char grade = A : String name = "Zeta"; int[] scores = {97, 85, 100; // A simple integer value // A numeric value with a fractional component // A single character // A sequence of characters // A one-dimensional array of integers Java provides four categories of types: primitive types, array types, class types and enum types. Primitive Types The primitive types are A collection of types for storing integer values, including: byte, short, int, long Two types for storing decimal values, including: float, double A type for logical values: bool. A variable of type bool has two possible values: true and false A type for storing a single character: char All other types are essentially built upon these primitive types in one of two ways. An array type is a fixed-sized collection of values of some other type. Each element of the collection is accessed using an integer index int[] scores = {97, 85, 100,; // A one-dimensional array of integers System.out.println(scores[1]); // Prints the value 85: arrays start at index 0 Each of these primitive share some characteristics Simple storage requirements: A value has a fixed size that can fit into a single word (or less) of memory Values can be explicit represented in the language: 37, -41, 3.14159, false, Z, w,... These representations of specific values are called literals. The String type is not primitive, although is unique among the non-primitive types that its values can be represented in Java by literals: Hi there!, Is 3 <2?, gibberish. We ll talk a lot more about strings later. Array Types All values stored in an array must be of the same type as the declared element type of the array. Example: Sum: A program to add two numbers Version 0: Numbers are hard-coded Version 1: Numbers are stored in variables Version 2: Items are read using a Scanner Version 3: Items are read using args[] parameter to main Version 4: More than two arguments are allowed; length of array is used in for loop Version 5: Iterator version of for loop is used. The Java class Arrays provides several utility methods for copying, searching, and sorting arrays. Operators Java provides a number of built-in operators (functions represented by 1 or 2 symbols) that perform basic computations. Here is a (non-exhaustive) list of frequently used binary (two argument) operators Arithmetic binary operators +, -, *, /, % Or, for class types, must be a subtype of that type. 2

Relational ==,!=, <, <=, >, >= Logical &&, (note: don t confuse with & and ) Assignment =, +=, -=, *=, /=,... Common unary operators include Arithmetic -, ++, (prefix and postfix) Logical! Notes There is no exponentiation operator in Java. The symbol ˆ, often used for exponentiation in other languages, is the bitwise or operator in Java. For positive arguments, the remainder operator % is the same as the mathematical mod function, but for negative arguments it is not. For example 8 mod 3 = 1 while 8%3 = 2. Here s the rule: c = a%b means 1. a = kb + c, 2. 0 c < b, and 3. sign(c) = sign(a) (i.e.: a and c are both positive, both negative, or both 0) Java provides an unambiguous operator precedence for all of its operatorshigher precedence operators (e.g., * or /) are evaluated before lower precedence operators (e.g, + or -); operators of equal precedence are evaluated from left to right. For example, 3 + 2 5 7/4 is equivalent to ((3 + (2 5)) (7/4)). The logical operator && has precedence over ; also, these operators use short-circuit evaluation: that is, once the value of the logical expression can be determined, no further evaluation takes place. For example, if x and y are boolean variables and x has the value false, the expression x && y will return false without evaluating y. This is useful in expressions such as (n!= 0) && (k/n > 3), since it will prevent division by 0 if n equals 0. Expressions and Control Structures in Java Java allows the computation of values by building expressions. Expressions use variables, operators, and method calls to produce a value the value of the expression. This value can then be assigned to a variable or passed to/returned from a method. Expressions that produce a bool value (true/false) are called boolean (or logical) expressions and can be used with conditional or looping constructs to determine the flow of control of the program. Some examples: // Assume x has been declared as an int and y as a double if (x!= 0) y = 1.0/x; else y = 0; while (x > 0) { System.out.println("x is positive"); x--; // decrement x There are two conditional statements: if and switch. The if statement has the form if (booleanexpression) // There is exactly 1 "if" clause else if (booleanexpression) // There can be 0 or more "else if" clauses else // There can be at most 1 "else" clause 3

The single statement can be replaced with a block a sequence of statements enclosed in brackets: if (booleanexpression) { statement1; statement2;... In many situations, the condition being tested is the value of a variable of type int. In this case, one can use the switch statement: // Assume that x has been declared to be an int switch (x) { case 0: System.out.println("Your card is a club"); case 1: System.out.println("Your card is a diamond"); case 2: System.out.println("Your card is a heart"); case 3: System.out.println("Your card is a spde"); default: System.out.println("Illegal value!"); Switch statements can also be used for enumeration types and (with some restrictions) Strings. In addition to the if and switch statements, which provide for conditional flow of control, Java also provides several statements that provide for repeated execution of a block of code loops. We ve already seen one of these, the for statement. We ll come back to it shortly, but first let s see the two simpler looping constructs: the while and do-while statements. There are also two flavors of while loop: while ( continue? ) do statement while ( continue? ); The latter form is guaranteed to execute the statement at least once, since the check happens after the statement. The for statement has two basic forms for ( onet imeinitialization, continue?, updatew ork ) for ( arrayv aluet ype identif ier : arrayn ame ) The latter form is frequently used in situations in which we wish to access (but not modify) each element of the array in order. The other fundamental control flow constructs provided by Java are the break, continue, and return statements. The break statement is used to within a switch, for, while, or do-while control structure to exit that structure and to transfer control to the first line of code after the exited structure. If instead, the goal is to stop executing the current iteration of a loop and begin the next iteration of the loop, then the continue statement is There is no point to allowing a continue statement in a switch structure, just as there s no point to allowing a break statement in an if structure. 4

used. Finally, as we ll see later, the return transfers control from an executing method back to the code that invoked that method. So far, we have the ability to write programs that use primitive types and arrays using the main() method of a class. If such a program gets to be too long, we can decompose it into smaller pieces using methods. Here s an example of a program that reads a list of integers from the command line and finds the smallest one. // Sample code using static methods class StaticMethods { // Sample code using static methods class StaticMethods { public static int posofmin(int[] nums) { int pos = 0; for( int i = 1; i < nums.length; i++ ) if ( nums[i] < nums[pos] ) pos = i; return pos; public static void main(string[] args) { // quit if no integers entered on command line if( args.length == 0 ) System.exit(0); // create a list of integers int[] numbers = new int[args.length]; int i = 0; // Convert each command line (String) value to an int for ( String s : args ) numbers[i++] = Integer.valueOf(s); // Find the location in the array of the smallest int int loc = posofmin(numbers); System.out.println("The smallest value is " + numbers[loc] + "; it is in position " + loc); We can create as many methods as we need to keep each method at a manageable (easy to understand, debug, maintain) size. Like main(), posofmin() is declared static. We ll explain why in the next handout. Also, posofmin() computes and returns a value: the location in the array of the smallest element. We indicate that the method returns an integer value by using the Java keyword int just before the name of the method. Much of the real power of Java (and other object-oriented languages) stems from the ability to supplement the primitive types with types of our own making. In Java, these are called class types and they are the topic of the next handout. 5