CS11 Java. Fall Lecture 1

Similar documents
CS 11 java track: lecture 1

Full file at

Introduction to Programming Using Java (98-388)

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

Java Bytecode (binary file)

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

Getting started with Java

Basics of Java Programming

Lecture 1: Overview of Java

CS 106 Introduction to Computer Science I

Programming Language Basics

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

CS 231 Data Structures and Algorithms, Fall 2016

B.V. Patel Institute of BMC & IT, UTU 2014

Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal

Section 2.2 Your First Program in Java: Printing a Line of Text

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

Basic Operations jgrasp debugger Writing Programs & Checkstyle

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

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

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

Full file at

Introduction to Java

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

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

Pace University. Fundamental Concepts of CS121 1

Programming. Syntax and Semantics

Expressions and Data Types CSC 121 Spring 2017 Howard Rosenthal

CSE 421 Course Overview and Introduction to Java

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

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

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

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

Chapter 2: Data and Expressions

CS111: PROGRAMMING LANGUAGE II

Variables, Constants, and Data Types

Entry Point of Execution: the main Method. Elementary Programming. Learning Outcomes. Development Process

Tester vs. Controller. Elementary Programming. Learning Outcomes. Compile Time vs. Run Time

Lecture Set 2: Starting Java

13 th Windsor Regional Secondary School Computer Programming Competition

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

Character Stream : It provides a convenient means for handling input and output of characters.

Chapter 2: Data and Expressions

Elementary Programming

Lecture Set 2: Starting Java

Chapter 2: Data and Expressions

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

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

CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 3: SEP. 13TH INSTRUCTOR: JIAYIN WANG

Program Elements -- Introduction

4 Programming Fundamentals. Introduction to Programming 1 1

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

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

Chapter 2 Elementary Programming

Contents. Jairo Pava COMS W4115 June 28, 2013 LEARN: Language Reference Manual

PROGRAMMING FUNDAMENTALS

CMPT 125: Lecture 3 Data and Expressions

Programming with Java

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

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

Università degli Studi di Bologna Facoltà di Ingegneria. Principles, Models, and Applications for Distributed Systems M

Primitive Data, Variables, and Expressions; Simple Conditional Execution

Inf1-OOP. Textbooks. Who and What. Organizational Issues. Why Java? Course Overview. Hello, World! in Java. Ewan Klein, Perdita Stevens

Praktische Softwaretechnologie

2.1. Chapter 2: Parts of a C++ Program. Parts of a C++ Program. Introduction to C++ Parts of a C++ Program

Introduction to Java Chapters 1 and 2 The Java Language Section 1.1 Data & Expressions Sections

CT 229 Fundamentals of Java Syntax

Object-Oriented Programming

CS112 Lecture: Primitive Types, Operators, Strings

Introduction Basic elements of Java

Introduction to Java Applications

Chapter 1 Introduction to java

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

Fundamentals of Programming. By Budditha Hettige

MODULE 02: BASIC COMPUTATION IN JAVA

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

Introduction to Java Applications; Input/Output and Operators

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

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

Chapter 2: Using Data

Zhifu Pei CSCI5448 Spring 2011 Prof. Kenneth M. Anderson

Section 2: Introduction to Java. Historical note

CS321 Languages and Compiler Design I. Winter 2012 Lecture 2

Program Fundamentals

DATA TYPES AND EXPRESSIONS

Typescript on LLVM Language Reference Manual

Introduction to Java

Software and Programming 1

Java Overview An introduction to the Java Programming Language

Chapter 2: Using Data

CIS133J. Working with Numbers in Java

Chapter 02: Using Data

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

CS313D: ADVANCED PROGRAMMING LANGUAGE

The Warhol Language Reference Manual

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

C: How to Program. Week /Mar/05

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

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

Chapter 2: Programming Concepts

Transcription:

CS11 Java Fall 2006-2007 Lecture 1

Welcome! 8 Lectures Slides posted on CS11 website http://www.cs.caltech.edu/courses/cs11 7-8 Lab Assignments Made available on Mondays Due one week later Monday, 12 noon CS Cluster Account Software environment Electronic submission ~/cs11/java/lab1 etc.

Course Texts No textbook is required Sun Java API documentation online Sun Java tutorials online If you want a textbook: The Java Programming Language, 3 rd ed. Ken Arnold, James Gosling, David Holmes Check http://www.bookpool.com

A Brief History of Java Developed by Sun Microsystems, starting in late 1990 Intended for embedded-systems programming Primary goal was improving on C++ Initially named Oak Renamed to Java in 1994, first release in 1995 Language, and standard libraries, have expanded dramatically over the years Java 1.5 released in 2004 introduced new language features, new APIs Even more changes planned for 1.6, 1.7,

Goals of Java Simple and familiar Based on C/C++, but with many of the subtleties removed. Object-oriented Well-suited to distributed systems Architecture-neutral Both source-code and binaries are portable Dynamic loading and binding Minimizes recompilations, and facilitates modularity! Secure Class-verification, code-signing, permissions Multithreaded Language specifies platform-neutral threading support

How Java Does Its Thing Source code goes into.java files. One top-level class per file. Class name dictates file name. Example: HelloWorldApp.java public class HelloWorldApp { public static void main(string[] args) { System.out.println("Hello, world!"); } }

How Java Does Its Thing (2) Java compiler takes.java files and compiles them into platform-independent.class files. These class-files contain byte-codes instructions for the Java Virtual Machine (JVM). javac HelloWorldApp.java produces HelloWorldApp.class Byte-codes for our example: public static void main(java.lang.string[]) 0: getstatic #2; //Field java/lang/system.out 3: ldc #3; //String "Hello, world!" 5: invokevirtual #4; //Method java/io/printstream.println 8: return

How Java Does Its Thing (3) Run the program with a Java Virtual Machine (JVM) The JVM takes a class-name, not the class file-name > java HelloWorldApp Hello, world! The java program implements the JVM for a specific platform Can run Java on any platform with a JVM implementation. (Windows, Linux, Solaris, MacOSX, ) Some JVMs improve performance by compiling Java byte-codes into native machine-code Called just-in-time compilation, or JIT for short

Java Comments Java comments are just like C++ comments. /* * This method prints hello world. */ public static void main(string[] args) { // This next part is tricky... System.out.println("Hello, world!"); // phew! } Nested /* */ comments don t work! Block-comments end with first */ encountered.

Javadoc Comments Java provides tools for generating API docs from source-code. Tool is called javadoc Generated documentation is called javadocs Java API documentation is all auto-generated Javadoc processes special comments: /** * Prints "Hello World!" then exits. */ public class HelloWorldApp { /** Main function. */ public static void main(string[] args) {... } }

Java Data-Types Primitive Types boolean values are true or false byte char int long float double 8-bit signed integer 16-bit unsigned integer 32-bit signed integer 64-bit signed integer 32-bit signed floating-point value 64-bit signed floating-point value

More Java Data-Types Reference Types Refers to an object (not a primitive type) Can be null if the reference refers to nothing Examples: String, Integer Arrays are also reference-types int[] numarray; // preferred int numarray[]; More on arrays in a few weeks! // also works

Java Literals Boolean is simply true or false. Integer values are straightforward int i = 17; Long values use L suffix: long secondsinyear = 31556926L; Avoid lower-case l looks like 1 in many fonts Default type of a decimal value is double! double pi = 3.14159265358979323; Float literal uses F suffix: float goldenratio = 1.618f; In this case, either F or f is fine.

More Java Literals Character-literals can be numbers, or single-quoted characters. char ucasea = 65; char ucasea = 'A'; String literals are double-quoted: String meat = "pastrami"; Special characters must be escaped: String msg = "He said, \"Java is neat!\""; Most useful special-characters: \t = tab \r = carriage return \n = new line \\ = backslash \' = single quote \" = double quote

Java Variables Variable-declarations include type and name: int i; boolean err, done; String name; // This is a reference. Names must start with a letter, and can include only letters and digits. _ and $ are considered to be letters Don t use $ though used for auto-generated code

Initial Values Can specify initial value: int i = 0; boolean err = false, done = true; String name = "Donnie"; Integer answertolife = new Integer(42); A default initial value is only used sometimes int i; i = i + 1; Compile-time error: variable i might not have been initialized

Java Operators Same set of operators as C and C++ Operators have precedence Example: * has higher precedence than + int ans = 3 + 5 * 2; // Result = 13, not 16 Override precedence rules with parentheses int ans = (3 + 5) * 2; // Result = 16, not 13 Also use parentheses where precedence rules aren t obvious.

Arithmetic Operators Same as C/C++: + - * / % Note: Remember that % is a remainder operator! int rem = -7 % 4; // rem = -3 Operate on numeric types: int, float, etc. Preincrement and postincrement operators: int i = 5; int j = ++i; // j = 6, i = 6 int k = i++; // k = 6, i = 7 Compound assignment operators: totalscore += pointsearned; recipeamount *= scale;

Comparison Operators Compare two values, produce a boolean result Standard set: < > <= >= ==!= Note that boolean and int are not equivalent! Wrong: int res = (x < 64); // Won't compile! Correct: boolean res = (x < 64); In Java, no type can be cast to boolean boolean also cannot be cast to any other type

Logical Boolean Operators Again, same as C/C++: &&! Logical AND, logical OR, and logical NOT. These operators require boolean values, and produce boolean values. Lazy evaluation: For example: name!= null && name.equals("donnie") Conversely: name == null!name.equals("donnie") Precedence order:! && Example: isdone!foundvalue && iscorrect

String Operators String-concatenation also uses + operator. public static void main(string[] args) { String name = "Donnie"; System.out.println("Hello " + name); } At least one operand must be a String for + to do string-concatenation.

Flow-Control in Java If-statements are nearly identical to C and C++. if (cond) statement; else if (cond) statement; else statement; Difference: cond must produce boolean value! Blocks of statements are enclosed with curly-braces { }. Just like in C/C++. if (cond) { statement1; statement2; }

Looping in Java While-loops: while (condition) while (condition) { statement; statement1;... } Tests condition before each iteration. Iterates zero or more times. Example: int i = 1; while (i <= 10) { sum += i; i++; } Iterates 10 times. Sum is 55 at end of loop.

Looping in Java (2) Do-loops: do do { statement; statement1; while (condition);... } while (condition); Tests condition after each iteration. Iterates ONE or more times. Example: do { strbuf.append(num % 10); num /= 10; } while (num!= 0);

For-Loops Combine the basic operations into one syntax: for (init; condition; update) statement; for (init; condition; update) { statement1;... } Equivalent to while-loops, but more compact. We can rewrite our previous while-loop: Initialization int i = 1; Condition Update while (i <= 10) { for (i = 1; i <= 10; i++) sum += i; sum += i; i++; } Statement

More For-Loops! Can specify multiple initial values: int i, sum; for (i = 1, sum = 0; i < 10; i++) sum += i; Can declare loop-variables in for-loop: int sum = 0; for (int i = 1; i <= 10; i++) sum += i; In this example, i is only visible within the for-loop The scope of i is within the for-loop.

Even More For-Loops! Can specify multiple update operations: int sum = 0; for (int i = 1; i < 10; sum += i, i++) /* nothing */ ; Document that the for-loop doesn t need a body! Even more compact: int sum = 0; for (int i = 1; i <= 10; sum += i++) /* nothing */ ; Difficult to maintain! Best to be avoided.

Java Methods A Brief Overview public static void main(string[] args) Access Modifier Method Modifier Return Type Method Name Parameter List Methods return a value of the specified type. Or they return no value, indicated by void keyword. Methods can accept any number of arguments. Method Signature No arguments is indicated with empty parens (), not void. A method s signature includes its name and its parameter-list. Method modifiers will be covered in future classes.

Printing in Java System.out.println("Hello!"); Many flavors: System.out.println(String x) System.out.println(boolean x) System.out.println(char x) System.out.println(float x) System.out.println(int x) System.out.println(Object x) System.out.println() and a few more These are overloaded methods. Same name, but different signature.

More Printing Options System.out is the standard output stream System.err is the standard error stream Use this to report errors when bad things happen. System.in is the standard input stream We will use this next week. System.out.println( ) goes to next line Use System.out.print( ) to stay on same line

A Note About Class-Names Java classes can be grouped into packages This is optional, but typically very helpful! Packages form a hierarchy package1.package2.classname Package names are typically all lower-case Naming rules are same as variable names. Example: java.awt.event.mouseevent More details on this later!

Java Coding Style! Capitalization is very important in Java coding style! Fields, methods should follow camelcase naming convention Classes, interfaces should follow UpperCamelCase naming convention Package names should be all lowercase Java has a number of industry-wide conventions like this

The Java API Documentation Complete API docs for the entire Java platform Extremely useful, once you learn how to use it! Auto-generated from Java library source-code Lists all classes and interfaces How to use them What features they provide Their relationships with each other http://java.sun.com/j2se/1.5.0/docs/api/index.html So useful, you might even want a local copy!

Other Useful Java Documentation The Java Tutorial Different trails cover different topics Very helpful resource for learning new features! JDK Documentation Feature-changes and new features Tool documentation The Java Language Specification The Java VM Specification

This Week s Homework Create your first Java program. Use some of the looping constructs we discussed. Learn how to compile and run your program. Read about object-oriented programming in Java. Learn to navigate the Java API Documentation!

Next Time! Java classes and objects! Read about this in your homework. Fun with math. (Or, why computers can t do basic arithmetic.)