Tony Valderrama, SIPB IAP 2010

Similar documents
Tony Valderrama, SIPB IAP 2009

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

CSC 1214: Object-Oriented Programming

1. Introduction to Java for JAS

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

Learning the Java Language. 2.1 Object-Oriented Programming

3. Java - Language Constructs I

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

An overview of Java, Data types and variables

Index COPYRIGHTED MATERIAL

Java Programming. Atul Prakash

Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal

Introduction to Programming Using Java (98-388)

2 rd class Department of Programming. OOP with Java Programming

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

Tony Valderrama, SIPB IAP 2009

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

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

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

CSEN 202 Introduction to Computer Programming

Imports. Lexicon. Java/Lespérance 1. PROF. Y. LESPÉRANCE Dept. of Electrical Engineering & Computer Science

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

Control Flow Statements

Language Fundamentals Summary

1 Shyam sir JAVA Notes

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

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

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

Program Fundamentals

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

CONDITIONAL EXECUTION: PART 2

CS260 Intro to Java & Android 03.Java Language Basics

Programming in C++ 4. The lexical basis of C++

CHAPTER 2 Java Fundamentals

Objectives. Problem Solving. Introduction. An overview of object-oriented concepts. Programming and programming languages An introduction to Java

: Primitive data types Variables Operators if, if-else do-while, while, for. // // First Java Program. public class Hello {

Introduction to Programming (Java) 2/12

6.096 Introduction to C++ January (IAP) 2009

Java Notes. 10th ICSE. Saravanan Ganesh

Introduction to. Android Saturday. Yanqiao ZHU Google Camp School of Software Engineering, Tongji University. In courtesy of The Java Tutorials

Programming. Syntax and Semantics

JAVA Programming Fundamentals

Java Identifiers. Java Language Essentials. Java Keywords. Java Applications have Class. Slide Set 2: Java Essentials. Copyright 2012 R.M.

Basic Types, Variables, Literals, Constants

Basics of Java Programming

Java Overview An introduction to the Java Programming Language

Java: framework overview and in-the-small features

Programming Language Basics

Expressions and Data Types CSC 121 Spring 2017 Howard Rosenthal

Pace University. Fundamental Concepts of CS121 1

Getting started with Java

3. Java - Language Constructs I

Week 6: Review. Java is Case Sensitive

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

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

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

COMP 202 Java in one week

The Java Language The Java Language Reference (2 nd ed.) is the defining document for the Java language. Most beginning programming students expect

The MaSH Programming Language At the Statements Level

Preview from Notesale.co.uk Page 9 of 108

.Net Technologies. Components of.net Framework

Full file at

JOSE LUIS JUAREZ VIVEROS com) has a. non-transferable license to use this Student Guide

Outline. Why Java? (1/2) Why Java? (2/2) Java Compiler and Virtual Machine. Classes. COMP9024: Data Structures and Algorithms

Course information. Petr Hnětynka 2/2 Zk/Z

A variable is a name that represents a value. For

For the course, we will be using JCreator as the IDE (Integrated Development Environment).

Lexical Considerations

The Sun s Java Certification and its Possible Role in the Joint Teaching Material

DM550 / DM857 Introduction to Programming. Peter Schneider-Kamp

c) And last but not least, there are javadoc comments. See Weiss.

Accelerating Information Technology Innovation

Operators and Expressions

Java Fundamentals p. 1 The Origins of Java p. 2 How Java Relates to C and C++ p. 3 How Java Relates to C# p. 4 Java's Contribution to the Internet p.

Java Programming Language Mr.Rungrote Phonkam

CompSci 125 Lecture 02

Language Features. 1. The primitive types int, double, and boolean are part of the AP

Computational Expression

Chapter 2. Elementary Programming

Chapter. Focus of the Course. Object-Oriented Software Development. program design, implementation, and testing

Building Java Programs. Introduction to Programming and Simple Java Programs

Discover how to get up and running with the Java Development Environment and with the Eclipse IDE to create Java programs.

1 Lexical Considerations

STRUCTURING OF PROGRAM

Chapter 2: Java Fundamentals

8/23/2014. Chapter Topics. Chapter Topics (2) Parts of a Java Program. Parts of a Java Program. Analyzing The Example. Chapter 2: Java Fundamentals

Outline. Java Compiler and Virtual Machine. Why Java? Naming Conventions. Classes. COMP9024: Data Structures and Algorithms

Fall 2017 CISC124 9/16/2017

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

Java Basic Programming Constructs

15CS45 : OBJECT ORIENTED CONCEPTS

Games Course, summer Introduction to Java. Frédéric Haziza

CS11 Java. Fall Lecture 1

Java Fall 2018 Margaret Reid-Miller

Syntax and Variables

Chapter 2: Data and Expressions

CS313D: ADVANCED PROGRAMMING LANGUAGE

boolean, char, class, const, double, else, final, float, for, if, import, int, long, new, public, return, static, throws, void, while

C OVERVIEW BASIC C PROGRAM STRUCTURE. C Overview. Basic C Program Structure

Data and Expressions. Outline. Data and Expressions 12/18/2010. Let's explore some other fundamental programming concepts. Chapter 2 focuses on:

Transcription:

Overview Getting started Background Syntax Announcements Course website: http://sipb.mit.edu/iap/java/ Email: sipb-iap-java@mit.edu Notes and code samples have been posted on the website. I need suggestions for advanced topics to cover next Thursday!

Wake up and smell the coffee! Software Java Development Kit (JDK) - http://java.sun.com/javase/downloads/index.jsp Eclipse Platform - http://www.eclipse.org/ Reference The Java Tutorial - http://java.sun.com/docs/books/tutorial/index.html Java Language API - http://java.sun.com/javase/reference/api.jsp Java SE Documentation - http://java.sun.com/javase/downloads/index.jsp Java SE Source Code - http://java.sun.com/javase/downloads/index.jsp

Not your daddy s cup of Joe There were five primary goals in the creation of the Java language: 1) It should be "simple, object oriented, and familiar". 2) It should be "robust and secure". 3) It should be "architecture neutral and portable". 4) It should execute with "high performance". 5) It should be "interpreted, threaded, and dynamic". Java was designed to be safe, simple, and powerful. Java whitedocs, as quoted in wikipedia

From beans to brew Images from the Java Tutorial

What s in the cup? Images from the Java Tutorial

Caf or decaf? Java is awesome at Cross-platform GUIs Large, complex applications Embedded systems Web-deployment Debugging Java sucks at Short scripts Low-level system code Malicious code Web-deployment High-volume data processing

package tvald.intro2java; /** * This is a demo program. * @author tvald * @date 1/5/2009 */ public class Hello { public static void main(string[] args) { System.out.println("Mmmm... Smell that coffee!"); // say hi

package tvald.intro2java; /** * This is a demo program. * @author tvald * @date 1/5/2009 */ public class Hello { package declaration JavaDoc comment method declaration class declaration public static void main(string[] args) { System.out.println("Mmmm... Smell that coffee!"); // say hi class statement comment class method method body

package tvald.intro2java; /** * This is a demo program. * @author tvald * @date 1/5/2009 */ public class Hello { public static void main(string[] args) { System.out.println("Mmmm... Smell that coffee!"); // say hi

Keywords abstract continue for new switch assert default goto * package synchronized boolean do if private this break double implements protected throw byte else import public throws case enum instanceof return transient catch extends int short try char final interface static void class finally long strictfp volatile const * float native super while Literals: true false null * not used

Basics // Single line comment /* * Multi-line * comment */ /** * JavaDocs documentation */ { // blocks contain statements statement; another statement; Java is imperative

The importance of being consistent class { public Hello static void main ( String [ ] args ) { System. out. println ( Mmm Coffee!" ) ;

Variables <type> name = expression; // declaration, with optional initialization name = expression; // assignment, by value char c; int i = 2; int j = i+3; String string; //Declarations of the same type may be strung together with commas int a, A = 2, a_ = 3; Convention: All variable names begin with lowercase letter. Use camel case - firstsecondthird. Use only alphanumeric characters, and occasionally underscore. Use a noun! Java typing is static, strong, and nominative.

The Java Compiler is Your Friend!

Primitives /* integers */ byte b = 127; // 8 bits signed; -128 to 127 short s = 127; // 16 bits signed; -32,768 to 32,767 int i = 127; // 32 bits signed; -2,147,483,648 to 2,147,483,647 long l = 2000000000000L; // 64 bits signed int dec = 26, oct = 032, hex = 0x1a, HeX = 0X1Ab0; /* real numbers */ float f = 1.0f; // 32 bits signed double d = 2.0; // 64 bits signed double dec = 123.4, sci = 1.234e2; /* booleans */ boolean t = true, f = false; /* text */ char c = c, unicode = \u00f1, tab= \t ; String s = "Hello world!\nand hello again!";

Casting Variables can be converted to different types by casting. Must be compatible types (applies mainly to objects). Number conversion is handled by truncation (if converting to integer) then modulus size. int i; double d = 2.75; //compiler generates warning if cast is not present: i = (int)d; // i is 2 i = 2; d = i; // less exact numbers are automatically promoted

Operators Operators postfix expr++ expr-- unary ++expr --expr +expr -expr ~! multiplicative * / % additive + - shift << >> >>> relational equality ==!= bitwise AND bitwise exclusive OR bitwise inclusive OR logical AND logical OR < > <= >= instanceof & ^ && ternary? : assignment = += -= *= /= %= &= ^= = <<= >>= >>>= ~ - bitwise NOT! - logical NOT short-circuit as soon as result is determined

Strings A String is an Object, NOT an array of characters. A String is immutable. Any character is valid between quotes, except a CR / LF String s = "Hello World!"; String longtext = " Supercalifragilisticexpialidocious is " + "a very long word."; // concatenation String numstr = "I can count to " + 3 + '.'; Special characters can be escaped \b (backspace) \t (tab) \n (line feed) \f (form feed) \r (carriage return) \" (double quote) \' (single quote) \\ (backslash)

Conditionals if (conditional expression) { statement;... else if (condition2) { statement;... else { statement;... if (condition) statement; (condition? expression : elseexpression) // ternary inline conditional System.out.println("Good " + (Time.isMorning()? "morning" : "afternoon") + "!"); int i; if ((i = 1) == 0) statement; if (i = 1) statement; // invalid, number!= boolean

Switch switch (month) { case 1: System.out.println("January"); break; case 2: System.out.println("February"); break; case 3: System.out.println("March"); break; case 4: System.out.println("April"); break; case 5: System.out.println("May"); break; case 6: System.out.println("June"); break; case 7: System.out.println("July"); break; case 8: System.out.println("August"); break; case 9: System.out.println("September"); break; case 10: System.out.println("October"); break; case 11: System.out.println("November"); break; case 12: System.out.println("December"); break; default: System.out.println("Invalid month.");break;

Switch switch (month) { case 1: case 3: case 5: case 7: case 8: case 10: case 12: numdays = 31; break; case 4: case 6: case 9: case 11: numdays = 30; break; case 2: if ( ((year % 4 == 0) &&!(year % 100 == 0)) (year % 400 == 0) ) numdays = 29; else numdays = 28; break; default: System.out.println("Invalid month."); break;

Loops while (expression) { statement(s) while (true){ // infinite loop if (exitcondition) break; do { statement(s) while (expression);

Scope Where can I access a variable? Inside the block where you declare the variable. if (a < 10) { int c = 2; else { int c = 4; System.out.println(c); // ERROR! C isn t in scope!

Arrays <type>[] name = new <type>[length]; int[] intarray = new int[10]; // 10 elements, #0-9 String[] stringarray = new String[3]; // Objects work too. // stringarray.length -> 3 // intarray.length -> 10 NOTE: Java Arrays are first-class Objects, so initialized to null. Images from The Java Tutorial

Arrays int[] intarray = new int[] { 1, 2, 3; int[][] intarray2 = new int[][] { {1,2,3,4, {5,6,7,8, {9,10,11,12 ; intarray2 = new int[3][]; // element arrays are now null intarray2[0] = new int[1]; intarray2[1] = new int[2]; // element arrays can have different lengths // intarray2.length -> 3 // intarray2[0].length -> 1 // intarray2[1].length -> 2 // intarray2[2].length -> NullPointerException // efficient copying public static void arraycopy( Object src, int srcpos, Object dest, int destpos, int length) System.arraycopy(intArray, 1, intarray2[1], 0, 2); // intarray2[1][1] -> 3

For Loops for (initialization; termination; increment) { statement(s) int[] array = new int[10]; for (int i = 0; i < array.length; i++) { statements; for ( ; ; ) { // expressions are optional, this is an infinite loop for (<T> element : Iterable<T>) { // enhanced for loop

Branching out: // label any kind of loop while (condition1) { myloop: // nested label for ( ; condition2 ; ) { while (true) { if (condition3) break out; else if (condition4) continue myloop; else if (condition5) return; // return MUST match method type boolean foo() { return false;

Method Declaration modifiers <type> name (parameter list) throws exceptionlist { // method body public static void main(string[] args) {... public double calculateanswer(double wingspan, int numberofengines, double length, double grosstons) { //do the calculation here return result; Convention: Method names begin with an lowercase letter Use camel case - firstsecondthird. Use only letters. Use a verb!

Method Overloading Method Signature: name (parameters) Java compiler will choose the right method based on the supplied name and parameters public void println(string s) {... public void println(int i) {... public void println(double f) {... public void println(boolean b) {...

Parameters public void foo (parameters) { Parameters may be of any data type - arrays, primitives, objects, whatever... Can t pass a method, but you can pass an object and invoke its methods. Varargs (shortcut to create an array): public Polygon polygonfrom(point... corners) { for (Point p : corners.length) { // more method body code follows that creates // and returns a polygon connecting the Points Both primitives and object references are passed by value.

Error Handling try { // this may cause an error catch (Exception e) { // error recovery e.printstacktrace(); return; finally { /* this will ALWAYS be executed, regardless of what happens * within a try or catch block, even with a return or break. */ Three types of problems: Checked Exceptions: most expected problems, follow the Catch or Specify requirement. Runtime Exceptions: unusual cases, usually indicate a logic flaw or misuse of API. Error: computer unplugged, processor melts, Armageddon, whatever things you can t really do anything about, but you can try if you want.

Error Handling >java MyClass java.lang.nullpointerexception at MyClass.mash(MyClass.java:9) at MyClass.crunch(MyClass.java:6) at MyClass.main(MyClass.java:3)

Method Declaration with Exceptions modifiers type name (parameter list) throws exceptionlist { // method body public void readfile(string filename) throws FileNotFoundException, IOException {

What is a package? A package is a namespace for organizing classes and interfaces in a logical manner. Placing your code into packages makes large software projects easier to manage. package edu.mit.sipb.iap; import java.util.*; // wildcard import (load as needed) import static java.lang.math.pi; // import constant (static import) /* NOTE: only one public class, with the same name as the file, * is accessible outside of this source file */ public class Test { public static void main(string[] args){ double x = java.lang.math.e; // fully qualified name double rad = 2 * PI; // PI was statically imported java.util.linkedlist list1; // full class name unnecessary ArrayList list2; // java.util.arraylist

Application Programming Interface