Http://java.oracle.com Introduction to Java.

Slides:



Advertisements
Similar presentations
Chapter 1: Computer Systems
Advertisements

Building Java Programs Chapter 1 Lecture 1-2: Static Methods reading:
Building Java Programs Chapter 1 Introduction to Java Programming.
Java Programs + Algorithms
Basic Java programs with println statements. 2 Compile/run a program 1.Write it –code or source code: the set of instructions in a program 2.Compile it.
1 Procedural decomposition using static methods suggested reading:1.4.
Building Java Programs Chapter 1 Introduction to Java Programming.
Copyright 2010 by Pearson Education Building Java Programs Chapter 1 Lecture 1-2: Static Methods reading:
The Java Programming Language
Copyright 2008 by Pearson Education Building Java Programs Chapter 1 Lecture 1-1: Introduction; Basic Java Programs reading: self-check: #1-14.
Outline Java program structure Basic program elements
Copyright 2008 by Pearson Education Building Java Programs Chapter 1 Lecture 1-2: Static Methods, Avoiding Redundancy reading: self-check:
Copyright 2008 by Pearson Education Building Java Programs Chapter 1: Introduction to Java Programming.
Copyright 2013 by Pearson Education Building Java Programs Chapter 1 Lecture 1-1: Introduction; Basic Java Programs reading:
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Copyright 2008 by Pearson Education Building Java Programs Chapter 1 Lecture 1-2: Static Methods reading:
Copyright 2008 by Pearson Education Building Java Programs Chapter 1 Lecture 1-1: Introduction; Basic Java Programs reading: self-check: #1-14.
Topic 3 static Methods and Structured Programming "The cleaner and nicer the program, the faster it's going to run. And if it doesn't, it'll be easy to.
Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 1: Introduction to Java Programming.
1 Identifiers  Identifiers are the words a programmer uses in a program  An identifier can be made up of letters, digits, the underscore character (
Java: Chapter 1 Computer Systems Computer Programming II.
Java Language and SW Dev’t
Static methods. 2 Algorithms algorithm: a list of steps for solving a problem Example algorithm: "Bake sugar cookies" –Mix the dry ingredients. –Cream.
BUILDING JAVA PROGRAMS CHAPTER 1 INTRODUCTION TO JAVA PROGRAMMING.
Introduction to Programming David Goldschmidt, Ph.D. Computer Science The College of Saint Rose Java Fundamentals (Comments, Variables, etc.)
The Java Programming Language
CS 112 Introduction to Programming Lecture 3: Java Methods Yang (Richard) Yang Computer Science Department Yale University 308A Watson, Phone:
Chapter 2: Java Fundamentals
Copyright 2010 by Pearson Education Building Java Programs Chapter 1 Lecture 1-2: Static Methods reading:
Building Java Programs Chapter 1 Introduction to Java Programming.
Building Java Programs Chapter 1 Introduction to Java Programming Copyright (c) Pearson All rights reserved.
CS 112 Introduction to Programming Lecture 3: Java Methods Yang (Richard) Yang Computer Science Department Yale University 308A Watson, Phone:
Copyright 2010 by Pearson Education CSE 142, Spring 2012 Building Java Programs Chapter 1 Lecture 1-1: Introduction; Basic Java Programs reading: 1.1 -
© 2011 Pearson Education, publishing as Addison-Wesley Chapter 1: Computer Systems Presentation slides for Java Software Solutions for AP* Computer Science.
Welcome to CSE 142! Zorah Fung University of Washington, Summer Building Java Programs Chapter 1 Lecture 1-1: Introduction; Basic Java Programs.
Copyright 2010 by Pearson Education APCS Building Java Programs Chapter 1 Lecture 1-1: Introduction; Basic Java Programs reading:
1 Problem Solving  The purpose of writing a program is to solve a problem  The general steps in problem solving are: Understand the problem Dissect the.
Building Java Programs Chapter 1 Introduction to Java Programming Copyright (c) Pearson All rights reserved.
Lecture 1: Introduction to Java Programming
Lecture 1: Basic Java Syntax
Static Methods and Method Calls
CSc 110, Autumn 2017 Lecture 2: Functions.
Working with Java.
Lecture 2: Static Methods Expressions reading: 1.4 – 2.1
Building Java Programs
CSE 190D, Winter 2013 Building Java Programs Chapter 1
AP Computer Science Mr. Wortzman.
Topic 3 static Methods and Structured Programming
Chapter 1: Computer Systems
Building Java Programs
Advanced Programming CS206
Lecture 1: Basic Java Syntax
Building Java Programs
Building Static Methods
CSc 110, Spring 2018 Lecture 2: Functions.
Lecture 2: Static Methods Expressions reading: 1.4 – 2.1
Building Java Programs
Building Java Programs
Building Java Programs
Building Java Programs
Building Java Programs Chapter 1
Building Java Programs
CSE 142, Spring 2012 Building Java Programs Chapter 1
Chapter 1 Lecture 1-2: Static Methods reading:
Zorah Fung University of Washington, Spring 2015
Building Java Programs
CSE 142, Winter 2014 Building Java Programs Chapter 1
Building Java Programs
Building Java Programs
Zorah Fung University of Washington, Winter 2016
Presentation transcript:

http://java.oracle.com Introduction to Java

A Brief History Originally released in 1995 by Sun Microsystems (now a subsidiary of Oracle) Designed to write programs for “embedded devices,” specifically TVs As such, Java is designed for small, lightweight programs Turns out, this makes it ideal for writing programs for the internet as well

Key Characteristics “Write-once, run anywhere” Java programs are compiled to bytecode rather than machine code The bytecode can be executed by any Java VM on any computer Similar to C# Automatic memory management Java tracks what memory is currently in use and reclaims memory that is no longer needed Other languages (such as C/C++) require the developer to track this themselves Object-oriented

Writing Java Programs Java has many, many predefined classes and objects that provide common behavior System.out from our program is one example This prevents Java developers from having to constantly “reinvent the wheel” These classes and objects (collectively referred to as the “Java API”) are documented on the Java website: http://download.oracle.com/javase/7/docs/api/ Bookmark this page– it will be your lifeline

Actually Writing Java Programs We could just use notepad (or any other text editor) and command-line tools javac (compiler) and java (vm) This is very simple and lightweight, but has a lot of drawbacks Very little confirmation we’re doing things right Introduces multiple potential points of failure

Using Eclipse Instead, we’ll use an Integrated Development Environment (IDE) called Eclipse Available for download from http://www.eclipse.org/downloads/ You want “Eclipse IDE for Java Developers” IDEs combine all the tools we need into one centralized, integrated environment (hence the name) Most IDEs (including Eclipse) also provide a bunch of other useful features

Eclipse Walkthrough

Exercise Create Hello World program. Outputs “Hello world. My name is <your name>.”

Actually Writing Java Programs Writing and running programs requires a number of tools: An editor to write and edit the code We will use eclipse A compiler to translate the program from Java code to Java bytecode A virtual machine or runtime to translate the bytecode to machine code, which the computer can execute A debugger to help track down and fix problems We will primarily use print statements to track and debug programs.

Actually Writing Java Programs Edit Compile Run Debug

Actually Writing Java Programs Edit Compile Run Debug Java Bytecode Java VM Machine Code

Actually Writing Java Programs Edit Compile Run Debug Java VM Machine Code Execute Java Bytecode

Your First Java program public class Hello { public static void main(String[] args) { System.out.println("Hello, world!"); System.out.println(); System.out.println("This program produces"); System.out.println("four lines of output"); } Its output: Hello, world! This program produces four lines of output console: Text box into which the program's output is printed.

Your First Java program class: a program public class Hello { public static void main(String[] args) { System.out.println("Hello, world!"); System.out.println(); System.out.println("This program produces"); System.out.println("four lines of output"); } Every executable Java program consists of a class, that contains a method named main, that contains the statements (commands) to be executed. method: a named group of statements statement: a command to be executed

System.out.println A statement that prints a line of output on the console. pronounced "print-linn" sometimes called a "println statement" for short Two ways to use System.out.println : System.out.println("text"); Prints the given message as output. System.out.println(); Prints a blank line of output.

Documentation Documentation refers to elements of code that help a reader understand what’s going on Comments are the primary, but not the only, form of documentation Two types of comments in Java: Single-line comments: // this is a single-line comment Multi-line (or C-style) comments: /* this is a multi-line comment */ Comments are ignored when compiling and executing code

Review What is the name of the statement that prints a line of output on the console? System.out.println What is Eclipse? An IDE that combines all the tools we need into one centralized, integrated environment In the program below, public class Hello { public static void main(String[] args) { System.out.println("Hello, world!"); System.out.println(); System.out.println("This program produces"); System.out.println("four lines of output"); } What is the name of the program? What is the name of a method? What is one statement in this program?

Documentation Use comments frequently to: Describe the basic, high-level behavior of a chunk of code Explain anything potentially unclear or tricky Explain why you chose to do something a certain way if there were multiple options Etc. You should also make your code self-documenting by: Choosing descriptive, readable names Using line breaks Indenting/aligning things well Readability of you code is important. For clarity and understanding especially on debugging You will be graded on the readability of your code.

Bugs A bug is anything that goes wrong with a program Debugging is the act of going through code and fixing bugs In industry, software engineers usually spend more time debugging code than they did writing it (sometimes orders of magnitude more)

Bugs Eclipse helps you find some bugs: Notice the red squiggly and red x Hovering over the x tells you what’s wrong When you try to compile, you also get an error:

Bugs Bugs that can be detected like this are called compile-time errors These are usually relatively simple to find and fix Bugs that don’t show up until you try to execute the program are called run-time errors Run-time errors are generally much trickier to deal with

ALL PROGRAMS HAVE BUGS, AND YOURS WILL TOO! Important takeaway: ALL PROGRAMS HAVE BUGS, AND YOURS WILL TOO! Don’t be discouraged when things don’t work right away Keep working at it, and try to see what the code really does, not what you think it does We’ll talk more about debugging and testing later

Names and identifiers You must give your program a name. public class ComputerScience { Naming convention: capitalize each word (e.g. MyClassName) Your program's file must match exactly (ComputerScience.java) includes capitalization (Java is "case-sensitive") identifier: A name given to an item in your program. must start with a letter or _ or $ subsequent characters can be any of those or a number legal: _myName TheCure ANSWER_IS_42 $bling$ illegal: me+u 49ers side-swipe Ph.D's

Identifiers continued Identifiers should be descriptive, but not unwieldy Bad: x (non-descriptive), myVariableThatIsUsedToCountSomething (too long) Good: count, numTries, xCoordinate Java has certain conventions for identifiers Identifiers are always a single word (no spaces) Class names should start with an uppercase letter, and use an uppercase letter to indicate word breaks e.g. String, PrintStream, MixedFraction This is called Pascal casing Variables/methods/etc. should start with a lowercase letter, and be cased similarly e.g. size, numLoops, firstName This called Camel casing

Keywords keyword: An identifier that you cannot use because it already has a reserved meaning in Java. abstract default if private this boolean do implements protected throw break double import public throws byte else instanceof return transient case extends int short try catch final interface static void char finally long strictfp volatile class float native super while const for new switch continue goto package synchronized

Strings A sequence of characters is called a string Strings are usually, but not exclusively, used for input and output Strings in Java are enclosed in double-quotes (“string”) Identify the string in System.out.println(“Welcome to Java!”); String is an example of a pre-defined Java class

Escape sequences escape sequence: A special sequence of characters used to represent certain special characters in a string. \t tab character \n new line character \" quotation mark character \\ backslash character Example: System.out.println("\\hello\nhow\tare \"you\"?\\\\"); Output: \hello how are "you"?\\

Review What kind of bugs don’t show up until you try to execute the program? Run-time bugs What is an identifier? A name given to an item in your program What kind of casing you should use for classes? Class names should start with an uppercase letter, and use an uppercase letter to indicate word breaks e.g. String, PrintStream, MixedFraction This is called Pascal casing What is a keyword? An identifier that you cannot use because it already has a reserved meaning in Java In Java, how do you specify a string? Strings in Java are enclosed in double-quotes (“string”)

Exercise Chapter 1 Exercises 1-5

Review What is the name of the method that all Java applications must have? main What is an identifier? A name given to an item in your program What kind of casing you should use for classes? Class names should start with an uppercase letter, and use an uppercase letter to indicate word breaks e.g. String, PrintStream, MixedFraction This is called Pascal casing What is a keyword? An identifier that you cannot use because it already has a reserved meaning in Java In Java, what is the escape sequence for a ‘\’ character? \\

Static methods

Algorithms algorithm: A list of steps for solving a problem. Example algorithm: "Bake sugar cookies" Mix the dry ingredients. Cream the butter and sugar. Beat in the eggs. Stir in the dry ingredients. Set the oven temperature. Set the timer. Place the cookies into the oven. Allow the cookies to bake. Spread frosting and sprinkles onto the cookies. ...

Problems with algorithms lack of structure: Many tiny steps; tough to remember. redundancy: Consider making a double batch... Mix the dry ingredients. Cream the butter and sugar. Beat in the eggs. Stir in the dry ingredients. Set the oven temperature. Set the timer. Place the first batch of cookies into the oven. Allow the cookies to bake. Place the second batch of cookies into the oven. Mix ingredients for frosting. ...

Structured algorithms structured algorithm: Split into coherent tasks. 1 Make the cookie batter. Mix the dry ingredients. Cream the butter and sugar. Beat in the eggs. Stir in the dry ingredients. 2 Bake the cookies. Set the oven temperature. Set the timer. Place the cookies into the oven. Allow the cookies to bake. 3 Add frosting and sprinkles. Mix the ingredients for the frosting. Spread frosting and sprinkles onto the cookies. ...

Removing redundancy A well-structured algorithm can describe repeated tasks with less redundancy. 1 Make the cookie batter. Mix the dry ingredients. ... 2a Bake the cookies (first batch). Set the oven temperature. Set the timer. 2b Bake the cookies (second batch). 3 Decorate the cookies.

Using static methods 1. Design the algorithm. Look at the structure, and which commands are repeated. Decide what are the important overall tasks. 2. Declare (write down) the methods. Arrange statements into groups and give each group a name. 3. Call (run) the methods. The program's main method executes the other methods to perform the overall task.

A program with redundancy public class BakeCookies { public static void main(String[] args) { System.out.println("Mix the dry ingredients."); System.out.println("Cream the butter and sugar."); System.out.println("Beat in the eggs."); System.out.println("Stir in the dry ingredients."); System.out.println("Set the oven temperature."); System.out.println("Set the timer."); System.out.println("Place a batch of cookies into the oven."); System.out.println("Allow the cookies to bake."); System.out.println("Mix ingredients for frosting."); System.out.println("Spread frosting and sprinkles."); }

Static methods static method: A named group of statements. denotes the structure of a program eliminates redundancy by code reuse procedural decomposition: dividing a problem into methods Writing a static method is like adding a new command to Java. What is a statement? statement: a command to be executed class method A statement method B method C

Gives your method a name so it can be executed Declaring a method Gives your method a name so it can be executed Syntax: public static void name() { statement; statement; ... statement; } Example: public static void printWarning() { System.out.println("This product causes cancer"); System.out.println("in lab rats and humans."); }

Design of an algorithm // This program displays a delicious recipe for baking cookies. public class BakeCookies2 { public static void main(String[] args) { // Step 1: Make the cake batter. System.out.println("Mix the dry ingredients."); System.out.println("Cream the butter and sugar."); System.out.println("Beat in the eggs."); System.out.println("Stir in the dry ingredients."); // Step 2a: Bake cookies (first batch). System.out.println("Set the oven temperature."); System.out.println("Set the timer."); System.out.println("Place a batch of cookies into the oven."); System.out.println("Allow the cookies to bake."); // Step 2b: Bake cookies (second batch). // Step 3: Decorate the cookies. System.out.println("Mix ingredients for frosting."); System.out.println("Spread frosting and sprinkles."); }

Executes the method's code Calling a method Executes the method's code Syntax: name(); You can call the same method many times if you like. Example: printWarning(); Output: This product causes cancer in lab rats and humans.

Program with static method public class Macklemore{ public static void main(String[] args) { rap(); // Calling (running) the rap method System.out.println(); rap(); // Calling the rap method again } // This method prints the lyrics to Can’t Hold Us. public static void rap() { System.out.println("So we put our hands up like the ceiling can't hold us. "); System.out.println("Like the ceiling can't hold us"); Output: So we put our hands up like the ceiling can't hold us. Like the ceiling can't hold us

Final cookie program // This program displays a delicious recipe for baking cookies. public class BakeCookies3 { public static void main(String[] args) { makeBatter(); bake(); // 1st batch bake(); // 2nd batch decorate(); } // Step 1: Make the cake batter. public static void makeBatter() { System.out.println("Mix the dry ingredients."); System.out.println("Cream the butter and sugar."); System.out.println("Beat in the eggs."); System.out.println("Stir in the dry ingredients."); // Step 2: Bake a batch of cookies. public static void bake() { System.out.println("Set the oven temperature."); System.out.println("Set the timer."); System.out.println("Place a batch of cookies into the oven."); System.out.println("Allow the cookies to bake."); // Step 3: Decorate the cookies. public static void decorate() { System.out.println("Mix ingredients for frosting."); System.out.println("Spread frosting and sprinkles.");

Demo: Methods calling methods public class MethodsExample { public static void main(String[] args) { message1(); message2(); System.out.println("Done with main."); } public static void message1() { System.out.println("This is message1."); public static void message2() { System.out.println("This is message2."); System.out.println("Done with message2."); Output: This is message1. This is message2. Done with message2. Done with main.

Control flow When a method is called, the program's execution... "jumps" into that method, executing its statements, then "jumps" back to the point where the method was called. public class MethodsExample { public static void main(String[] args) { message1(); message2(); System.out.println("Done with main."); } ... public static void message1() { System.out.println("This is message1."); } public static void message2() { System.out.println("This is message2."); message1(); System.out.println("Done with message2."); } public static void message1() { System.out.println("This is message1."); }

When to use methods Place statements into a static method if: The statements are related structurally, and/or The statements are repeated. You should not create static methods for: An individual println statement. Only blank lines. (Put blank printlns in main.) Unrelated or weakly related statements. (Consider splitting them into two smaller methods.)

Review What is a static method? What is an algorithm? A named group of statements What is an algorithm? A list of steps for solving a problem.

Exercise Write a Java program called TwoRockets that generates the following output. Use Static methods to show structure and eliminate redundancy in your solution. Note that there are two rocket ships next to each other. What redundancy can you eliminate using static methods? What redundancy can be eliminated? /\ /\ / \ / \ / \ / \ +---------+ +---------+ | | | | +---------+ +---------+ |United| |United| |States | |States | | | | | /\ /\ / \ / \ / \ / \ If they get done, Finish Homework Exercises Do the Binary Self-Check exercies (1-3)

Unit 1 Review Java programs Identifiers Method String Documentation

Your First Java program class: a program public class Hello { public static void main(String[] args) { System.out.println("Hello, world!"); System.out.println(); System.out.println("This program produces"); System.out.println("four lines of output"); } Every executable Java program consists of a class, that contains a method named main, that contains the statements (commands) to be executed. method: a named group of statements statement: a command to be executed

Identifiers The names of classes, methods, variables, etc. are referred to as identifiers Identifiers can consist of letters, digits, underscores (_), or $ The first character cannot be a digit Identifiers should be descriptive, but not unwieldy Bad: x (non-descriptive), myVariableThatIsUsedToCountSomething (too long) Good: count, numTries, xCoordinate

Identifiers Java has certain conventions for identifiers Identifiers are always … a single word (no spaces) Class names should start with … an uppercase letter, and use an uppercase letter to indicate word breaks e.g. String, PrintStream, MixedFraction This is called Pascal casing Variables/methods/etc. should start with a … lowercase letter, and be cased similarly e.g. size, numLoops, firstName

Keywords keyword: An identifier that you cannot use because it already has a reserved meaning in Java. abstract default if private this boolean do implements protected throw break double import public throws byte else instanceof return transient case extends int short try catch final interface static void char finally long strictfp volatile class float native super while const for new switch continue goto package synchronized

Methods A method is a defined behavior of a particular class Passing a message in Java is referred to as calling (or invoking) a method Method calls have the following parts: The target or receiver of the message is the object whose behavior we want to trigger The method name of the method we want to call If necessary, some number of arguments Arguments provide additional information needed by the method

Anatomy of a Method Call System.out.println(“Welcome to Java!”); Target or Receiver Argument Method Name

Documentation Use comments frequently to: Describe the basic, high-level behavior of a chunk of code Explain anything potentially unclear or tricky Explain why you chose to do something a certain way if there were multiple options Etc. You should also make your code self-documenting by: Choosing descriptive, readable names Using line breaks Indenting/aligning things well Readability of you code is important. For clarity and understanding especially on debugging You will be graded on the readability of your code.