Basic Java Syntax. COMP 401, Fall 2015 Lecture 2 1/13/2014

Similar documents
Java Programming Basics. COMP 401, Fall 2017 Lecture 2

Java Programming Basics. COMP 401, Spring 2017 Lecture 2

Basic Java Syntax, cont d. COMP 401, Fall 2015 Lecture 3 1/15/2015

Strings and Arrays. COMP 401, Fall 2017 Lecture 4

PROGRAMMING FUNDAMENTALS

Full file at

Basics of Java Programming

Introduction to Programming Using Java (98-388)

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

CS313D: ADVANCED PROGRAMMING LANGUAGE

Java Bytecode (binary file)

13 th Windsor Regional Secondary School Computer Programming Competition

Values and Variables 1 / 30

CS 231 Data Structures and Algorithms, Fall 2016

Java Notes. 10th ICSE. Saravanan Ganesh

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

Operators. Java operators are classified into three categories:

Lexical Considerations

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

1 Lexical Considerations

Flow Control. CSC215 Lecture

1007 Imperative Programming Part II

An overview of Java, Data types and variables

Lexical Considerations

Programming with Java

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

Getting started with Java

Control Flow. COMS W1007 Introduction to Computer Science. Christopher Conway 3 June 2003

CGS 3066: Spring 2015 JavaScript Reference

Binghamton University. CS-211 Fall Syntax. What the Compiler needs to understand your program

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

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

CS 112 Introduction to Computing II. Wayne Snyder Computer Science Department Boston University

Simple Java Reference

Objectives. Introduce the core C# language features class Main types variables basic input and output operators arrays control constructs comments

WEEK 4 OPERATORS, EXPRESSIONS AND STATEMENTS

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

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

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

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

CS313D: ADVANCED PROGRAMMING LANGUAGE

Introduction to Java & Fundamental Data Types

CprE 288 Introduction to Embedded Systems Exam 1 Review. 1

Fall 2017 CISC124 9/16/2017

Language Fundamentals Summary

More Programming Constructs -- Introduction

Introduction to the Java Basics: Control Flow Statements

Programming Language Basics

CS 112 Introduction to Computing II. Wayne Snyder Computer Science Department Boston University

Chapter 1 Getting Started

Pace University. Fundamental Concepts of CS121 1

CS260 Intro to Java & Android 03.Java Language Basics

Introduction to Java

Language Reference Manual

CS251L REVIEW Derek Trumbo UNM

BIT Java Programming. Sem 1 Session 2011/12. Chapter 2 JAVA. basic

Key Differences Between Python and Java

Zheng-Liang Lu Java Programming 45 / 79

Operators in java Operator operands.

Objectives. Chapter 2: Basic Elements of C++ Introduction. Objectives (cont d.) A C++ Program (cont d.) A C++ Program

Chapter 2: Basic Elements of C++

CS11 Java. Fall Lecture 1

Lecture Set 2: Starting Java

Chapter 2: Basic Elements of C++ Objectives. Objectives (cont d.) A C++ Program. Introduction

Lecture Set 2: Starting Java

The Java language has a wide variety of modifiers, including the following:

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

Advanced Computer Programming

JAC444 - Lecture 1. Introduction to Java Programming Language Segment 4. Jordan Anastasiade Java Programming Language Course

CSC 1214: Object-Oriented Programming

C++ Basics. Lecture 2 COP 3014 Spring January 8, 2018

Following is the general form of a typical decision making structure found in most of the programming languages:

Object-Oriented Programming

7/8/10 KEY CONCEPTS. Problem COMP 10 EXPLORING COMPUTER SCIENCE. Algorithm. Lecture 2 Variables, Types, and Programs. Program PROBLEM SOLVING

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

COMP-202 Unit 2: Java Basics. CONTENTS: Using Expressions and Variables Types Strings Methods

Lecture Set 4: More About Methods and More About Operators

LOON. Language Reference Manual THE LANGUAGE OF OBJECT NOTATION. Kyle Hughes, Jack Ricci, Chelci Houston-Borroughs, Niles Christensen, Habin Lee

Mr. Monroe s Guide to Mastering Java Syntax

CS 251 Intermediate Programming Java Basics

Java Programming. Atul Prakash

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

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

JAVA Programming Fundamentals

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

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

COMP Primitive and Class Types. Yi Hong May 14, 2015

CS111: PROGRAMMING LANGUAGE II

ARG! Language Reference Manual

Sri Vidya College of Engineering & Technology

CMPT 125: Lecture 3 Data and Expressions

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

3. Java - Language Constructs I

CSE 142 Su 04 Computer Programming 1 - Java. Objects

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

Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal

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

Lecture 3. More About C

UNIT- 3 Introduction to C++

In Java, data type boolean is used to represent Boolean data. Each boolean constant or variable can contain one of two values: true or false.

Transcription:

Basic Java Syntax COMP 401, Fall 2015 Lecture 2 1/13/2014

Program OrganizaDon and ExecuDon All code in Java is organized into classes and interfaces One public class or interface per file. Not strictly true, but accept this as true for now. Also, don t worry about what an interface is for now. Must match file name. Classes can be organized into packages. Again, more on that later. Java compiler (javac) produces byte code. Java interpreter (java) executes program Need to specify a specific class name as the main class. Interpreter starts execudon with the method main Must be defined with the signature: public static void main(string[] args)!

AverageHeightApp (1/2) Open a plain text editor. Create a file called AverageHeightApp.java Enter the following text: public class AverageHeightApp {!!! public static void main(string[] args) {! double[] heights = readheightdata();! double sum_of_heights = 0.0;! for (int i=0; i<heights.length; i++) {! sum_of_heights += heights[i];!!}!!double avg_height = sum_of_heights /! heights.length;!!system.out.println("the average height is: " + avg_height + " inches");! }!! static double[] readheightdata() {! double[] height_data = {66.0, 72.0, 69.5, 68.2, 75.0, 64.5, 63.0};! return height_data;! }! }!

AverageHeightApp (2/2) At a terminal command line (console for you Windows people), execute the following commands: > javac AverageHeightApp.java > java AverageHeightApp

AverageHeightApp Notables Demonstrates: Use of javac and java from the command line Appropriate declaradon of main Using a for loop to iterate over an array Using System.out.println for console output See reference documentadon for System class AutomaDc type conversion from integer to string Contextual interpretadon of + operator

You might want to drop the class if you didn t recognize the idea of an array of values and/or the nodon of retrieving a value from the array by its index. you can t recognize what in the program is acdng as a variable. you are unsure of how a for loop works.... you don t grock the nodon of defining a funcdon and/or calling a funcdon. you can t write a program of similar complexity in some other language if not Java. The above are necessary condidons for success in this class, but may not be sufficient condidons for success. Trust your own judgment, don t be afraid of a challenge. Programming takes pracdce.

AverageHeightApp take 2 Same as before, but with Eclipse. Eclipse Workspace CreaDng new project CreaDng a new package CreaDng new class More in recitadon

Comments Single line comments: // This is a comment.! MulDple line comments: /*! All of these lines.! Are commented.! */!

A Word About Types Value Types Integers Real numbers Booleans Character Reference Types String Array Objects typed by their class Classes themselves Values types are defined endrely by their value. Reference types are structures in memory. Address in memory uniquely idendfies them. The value of a variable that holds a reference type is this address.

Integers byte, short, int, long! Difference is in size (1, 2, 4, or 8 bytes) No unsigned version Value Types Decimal (255), hexidecimal (0xff), and binary (0b11111111) literal formats Real Numbers float, double! Difference is in precision. Characters char! Characters in Java are 16- bit Unicode values Literals use single- quote: c Non- printable escape sequence: \u#### where # is hex digit. Logical boolean! Example: \u00f1 for ñ Literals are true and false

Packages, classes, and methods, oh my! A package is a collecdon of classes. Defined by a package statement at the beginning of a source code file. Example: package lec02.ex01;! All classes defined in the file belong to that package. A class is a collecdon of funcdons (for now). Defined by class keyword followed by a block of code delimited by curly braces. Example: public class {! /* Class definition. */! }! A method is just another name for a funcdon or procedure and is a named sequence of Java statements. Defined within a class. Can be called, or invoked with parameters Syntax: a method header or signature followed by a block of code delimited by curly braces.

Method Signature Almost everything you need to know about a method is in its signature. 5 parts to a method signature Access modifier public, private, protected! If unspecified, then package access. Method type static or default (i.e., not specified) The keyword stadc indicates that this is a class method. If the keyword stadc is not present, then this is an instance method. Return type The type of value returned by the method as a result. If there is no result, then this is indicated by the keyword void. Method name Must start with a leper, $, or _ Can contain lepers, numbers, $, or _ (no spaces or other punctuadon) Parameter list In parenthesis, comma- separated list of parameter typed variable names.» If the method has no parameters, then just: () Each parameter variable name is preceded by a type declaradon.

Method Signature Examples public static void main(string[] args)!! int foo (int a, MyType b, double c)!! protected static void bar()!! static String touppercase(string s)!! static private Secret my_secret()!

UnDl we know a liple more All of the methods in my examples today are going to be public class methods. This means their signatures will include the words: public stadc

Inside a method The body of a method is a sequence of statements. A statement ends in a semi- colon Types of statements: DeclaraDons of local variables Assignment CondiDonal Loop Method call Return statement Blocks Zero or more statements enclosed in curly braces { } Allowed anywhere a single statement is allowed. And vice versa

Inside a method The body of a method is a sequence of statements. A statement ends in a semi- colon Types of statements: DeclaraDon of local variables Assignment CondiDonal Loop Method call Return statement Statement Blocks One or more statements enclosed in curly braces { } Allowed anywhere a single statement is allowed. And vice versa

Local variable declaradon Syntax: type name;! type name1, name2, name3;! type name = value;! A local variable is valid within the block of statements where the declaradon occurs. This is known as the scope of the variable. The declaradon must occur before the variable is used. Parameter names are local variables that are in scope for the endre method body.

Variable Names Variable names should start with a leper and can contain lepers, digits, $, or _ Can not start with digit Can not contain whitespace or punctuadon other than $ or _ In general, use of punctuadon in variable names is discouraged. Case sensidve Can not be a keyword Legal: foo, bar, a_variable, var123 Legal but not considered good: var_with_$, _badness Illegal: 1var, while, break, this has whitespace

Inside a method The body of a method is a sequence of statements. A statement ends in a semi- colon Types of statements: DeclaraDons of local variables Assignment CondiDonal Loop Method call Return statement Blocks Zero or more statements enclosed in curly braces { } Allowed anywhere a single statement is allowed. And vice versa

Assignment Syntax: variable = expression;! Note: single equals for assignment. Lev hand side must be some sort of variable that can be assigned. Expression must produce a value that matches the type of the variable.

Expressions A sequence of symbols that can be evaluated to produce a value. Can be used wherever a value is expected. Types of expressions: Literal values: 123, c, a string, true Variable name: a_variable Value retrieved from an array: my_array[3] Class/object fields: Math.PI Value as a result of a method call: foo() Compound expressions formed by applying an operator: 4+3*2

Operators Unary: +, -,!, ++, - - ArithmeDc: +, -, /, *, % RelaDonal: ==,!=, >, >=, <, <= Boolean: &&, Ternary:?: expression? if_true : if_false Bitwise: ~, <<, >>, >>>, &,, ^ Be aware of precedence Can be controlled by explicitly grouping with () Be aware of context Some operators do different things depending on the types of the values they are applied to.

Assignment and Unary Operators Most numeric operators have an assignment form. Easy syntax for applying the operator to a variable and assigning the result back to the same variable. Examples: a += 3 // Equivalent to a = a + 3 b *= 4 // Equivalent to b = b * 4 Unary operators ++ and Used with integer typed variables to increment and decrement. Usually used as a statement unto itself: a++; // Equivalent to a = a + 1; b- - ; // Equivalent to b = b 1;

ImporDng JAR files into a project Save JAR file somewhere. Create a new project in Eclipse. Right click the src folder in the project and choose, Import Choose the type General- >Archive and click Next Browse for and select the JAR file. Click Finish

lec02.ex2.example2 Variable declaradons for value types Integer math vs. Real math Ternary operator Operator precedence Boolean operator shortcut

Inside a method The body of a method is a sequence of statements. A statement ends in a semi- colon Types of statements: Variable declaradon Assignment CondiDonal Loop Method call Return statement Blocks Zero or more statements enclosed in curly braces { } Allowed anywhere a single statement is allowed. And vice versa

CondiDonal ExecuDon: if- else if- else if (expression) {!!block! } else if (expression) {!!block! } else {!!block! }! 27

if example if (score > 90) {!!System.out.println( You got an A! );! } else if (score > 80) {!!System.out.println( You got a B. );! } else if (score > 70) {!!System.out.println( You got a C? );! } else if (score > 60) {!!System.out.println( You got a D :-( );! } else {!!System.out.println( You failed );! }!!

CondiDonal ExecuDon: switch switch (expression) {! case value:!!statements!!break;! case value:!!statements!!break;!...! default:!!statements! }! Works with basic value data types Works with String as of Java 7 ExecuDon starts at first matching case value or default if provided and no case matches ConDnues undl break statement or end of switch.

Switch Example switch (c) {!!case 'a':!!case 'e':!!case 'i':!!case 'o':!!case 'u':!!!system.out.println("vowel");!!!break;!!default:!!!system.out.println("consonant");! }!!

lec02.ex3.example3 if and switch demo Variables scoped within block Style hint: Don t test boolean expression against true/false TesDng real numbers with epsilon bounds

Inside a method The body of a method is a sequence of statements. A statement ends in a semi- colon Types of statements: Variable declaradon Assignment CondiDonal Loop Method call Return statement Blocks Zero or more statements enclosed in curly braces { } Allowed anywhere a single statement is allowed. And vice versa

Loops: while while (expression) {!!block! }!! do {!!block! } while (expression);!

while example int sum = 0;! int n = 1;! while (n < 11) {! }! sum += n;! n++;! System.out.println( The sum of 1 to 10 is: + sum);!

Loops: for for (init; test; update) {!!block! }!

for example int sum = 0;! for(int n=1; n<11; n++) {! sum += n;! }! System.out.println( The sum of 1 to 10 is: + sum);!! Note that variable n is declared as part of init expression in for loop. This is a common programming idiom if loop variable is only needed for the loop. Scope of variable is limited to the loop block.

Loop odds and ends To skip to next iteradon of loop body use condnue statement. To break out of the loop body use break statement.

Example 4 while and for while and for equivalence scope of for loop variable break / condnue

Inside a method The body of a method is a sequence of statements. A statement ends in a semi- colon Types of statements: Variable declaradon Assignment CondiDonal Loop Method call Return statement Blocks Zero or more statements enclosed in curly braces { } Allowed anywhere a single statement is allowed. And vice versa

Calling Methods Calling a class method defined in the same class:!methodname(parameters);! Calling a class method defined in a different class (same package): ClassName.methodName(parameters);!! Calling a class method defined in a different package: PackageName.ClassName.methodName(parameters)!! In the above parameters is a comma separated list of values. A value can be also be an expression that results in a value. Must match in number and type according to method s signature. A method call that returns a value (i.e., not a void method) can be part of an expression. int max_times_min = max(a, b, c) * min(a, b, c);!

Inside a method The body of a method is a sequence of statements. A statement ends in a semi- colon Types of statements: Variable declaradon Assignment CondiDonal Loop Method call Return statement Blocks Zero or more statements enclosed in curly braces { } Allowed anywhere a single statement is allowed. And vice versa

Return Syntax: return expression;! Ends execudon of a method and returns the value of the expression as the result of the method. Must match type declared in method signature. If method return type is void, then simply: return;!

lec02.ex5.example5 Calling methods Compound expressions as part of method call to provide parameter value. Returning from middle of method Generally, try to avoid. Unreachable code error Calling method in same/different class, same/ different package lec02.ex5.example5other

Import DirecDve Maps class names from other packages into current name space. Convenient if going to use one or more class names repeatedly. Map all names from a package: import package.*;! Map a specific name from a package: import package.name;

Example5OtherRevisited import Math revisited Classes in java.lang package are automadcally imported.