Building Java Programs. Introduction to Java Programming

Similar documents
Building Java Programs

Procedural decomposition using static methods

Building Java Programs

Building Java Programs Chapter 1

Building Java Programs. Introduction to Programming and Simple Java Programs

Building Java Programs. Chapter 1: Introduction to Java Programming

Introduction to Computer Programming

Lecture 1: Basic Java Syntax

Entering the world of Javatar

Static Methods & Decomposition

COSC 236 Section 101 Computer Science 1 -- Prof. Michael A. Soderstrand

Building Java Programs Chapter 1

Building Java Programs

Building Java Programs

Building Java Programs

Welcome to CSE 142! Zorah Fung University of Washington, Spring Building Java Programs Chapter 1 Lecture 1: Introduction; Basic Java Programs

CS 112 Introduction to Programming

Recap: Structure of a Java program CS 112 Introduction to Programming. A Foundation for Programming Why Introduce Static Methods?

Topic 3 static Methods and Structured Programming

CSE 142, Summer 2015

Welcome to CSE 142! Whitaker Brand. University of Washington, Winter 2018

CSc 110, Autumn Lecture 2: Functions

CSE 142, Summer 2014

Lecture 1: Overview of Java

CSE 142. Lecture 1 Course Introduction; Basic Java. Portions Copyright 2008 by Pearson Education

Getting Started With Java

CSc 110, Spring Lecture 2: Functions. Adapted from slides by Marty Stepp and Stuart Reges

clicker question Comments Using comments Topic 3 static Methods and Structured Programming

Introduction to Java. Java Programs Classes, Methods, and Statements Comments Strings Escape Sequences Identifiers Keywords

2 rd class Department of Programming. OOP with Java Programming

CSE 201 Java Programming I. Smart Coding School website:

CS 112 Introduction to Programming

3. Java - Language Constructs I

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

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

Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal

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

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

BASIC ELEMENTS OF A COMPUTER PROGRAM

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

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

COMP 202 Java in one week

CompSci 125 Lecture 02

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

Introduction to Java

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

Java Programming Language Mr.Rungrote Phonkam

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

CS 231 Data Structures and Algorithms, Fall 2016

An overview of Java, Data types and variables

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

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

UEE1302 (1102) F10: Introduction to Computers and Programming

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

COSC 236 Section 101 Computer Science 1 -- Prof. Michael A. Soderstrand

Full file at

Java Programming. MSc Induction Tutorials Stefan Stafrace PhD Student Department of Computing

Program Fundamentals

Outline. CIS 110: Introduction to Computer Programming. What is Computer Science? What is computer programming? What is computer science?

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

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

Wentworth Institute of Technology. Engineering & Technology WIT COMP1000. Java Basics

The Java Language Rules And Tools 3

Chapter 2. Elementary Programming

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

CS Week 2. Jim Williams, PhD

CS 112 Introduction to Programming

Admin. CS 112 Introduction to Programming. Recap: Java Static Methods. Recap: Decomposition Example. Recap: Static Method Example

CS/B.TECH/CSE(OLD)/SEM-6/CS-605/2012 OBJECT ORIENTED PROGRAMMING. Time Allotted : 3 Hours Full Marks : 70

First Java Program - Output to the Screen

Tutorial 1 CSC 201. Java Programming Concepts عؾادئماظربجمةمبادؿكدامماجلاصا

CS11 Java. Fall Lecture 1

Fundamentals of Programming. By Budditha Hettige

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

3. Java - Language Constructs I

6.096 Introduction to C++ January (IAP) 2009

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

ECE 122 Engineering Problem Solving with Java

Lesson 01 Introduction

Java is a high-level programming language originally developed by Sun Microsystems and released in Java runs on a variety of

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

Accelerating Information Technology Innovation

Expressions and Data Types CSC 121 Spring 2017 Howard Rosenthal

Module 1: Introduction to Computers, Programs, and Java

Course Outline. Introduction to java

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

Java Bytecode (binary file)

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

Opening Problem. Find the sum of integers from 1 to 10, from 20 to 30, and from 35 to 45, respectively.

CSC 1214: Object-Oriented Programming

JAVA Ch. 4. Variables and Constants Lawrenceville Press

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

Lab # 2. For today s lab:

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

13 th Windsor Regional Secondary School Computer Programming Competition

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

Chapter 2: Basic Elements of C++

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

1 Epic Test Review 2 Epic Test Review 3 Epic Test Review 4. Epic Test Review 5 Epic Test Review 6 Epic Test Review 7 Epic Test Review 8

Introduction to OOP Using Java Pearson Education, Inc. All rights reserved.

Transcription:

Building Java Programs Introduction to Java Programming 1

What is java? Developed by Sun Microsystems (James Gosling) A general-purpose object-oriented language Based on C/C++ Designed for easy Web/Internet applications Widespread acceptance

Java Features (1) Simple fixes some clumsy features of C++ no pointers automatic garbage collection rich pre-defined class library http://java.sun.com/j2se/1.4.2/docs/api/ Object oriented focus on the data (objects) and methods manipulating the data all functions are associated with objects almost all datatypes are objects (files, strings, etc.) potentially better code organization and reuse

Java Features (2) Interpreted java compiler generate byte-codes, not native machine code the compiled byte-codes are platform-independent java bytecodes are translated on the fly to machine readable instructions in runtime (Java Virtual Machine) Portable same application runs on all platforms the sizes of the primitive data types are always the same the libraries define portable interfaces

Java Features (3) Reliable extensive compile-time and runtime error checking no pointers but real arrays. Memory corruptions or unauthorized memory accesses are impossible automatic garbage collection tracks objects usage over time Secure usage in networked environments requires more security memory allocation model is a major defense access restrictions are forced (private, public)

Java Features (4) Multithreaded multiple concurrent threads of executions can run simultaneously utilizes a sophisticated set of synchronization primitives (based on monitors and condition variables paradigm) to achieve this Dynamic java is designed to adapt to evolving environment libraries can freely add new methods and instance variables without any effect on their clients interfaces promote flexibility and reusability in code by specifying a set of methods an object can perform, but leaves open how these methods should be implemented can check the class type in runtime

Language basics (1) Data types 8 primitive types: boolean, byte, short, int, long, float, double, char Class types, either provided by Java, or made by programmers String, Integer, Array, Frame, Object, Person, Animal, Array types Variables datatype identifier [ = Expression]: Example variable declarations and initializations: int x; x=5; boolean b = true; Frame win = new Frame(); String x = how are you? ; int[] intarray; intarray = new int[2]; intarray[0] = 12; intarray[1] = 6; Person parray = new Person[10];

Language basics (2) Flow of control if, if-else, if-else if switch for, while, do-while break continue

Data Types Variables & Initializations String for strings of letters e.g. String LastName = Kim ; char for characters e.g. char alphabet = A ; byte, short, int, and long for integer numbers e.g. int number = 3; float & double for real numbers e.g. double pi = 3.14159 boolean for logical e.g. boolean check = true;

Expressions and Operators Expressions: ( ), *,/, +, - Operators: && for AND for OR! for NOT == for equal!= for NOT equal

Selection Statements if statement ex) if (A>B) { System.out.println( A>B ); if else statement ex) if (A>B) { System.out.println( A>B ); else { System.out.println( A<=B ); switch Statement ex) switch (A) { case 1: { System.out.println( A=1 ); break; case 2: { System.out.println( A=2 ); break; default: { System.out.println( A Undefined );

Repetitions(while, do while, and for) An example adding all numbers between 1 to 100 Using While: // Variable Declaration & Initialization int sum = 0; int count = 0; // Processing while (count <= 1000) { sum = sum + count; count = count +1; //same as count++ // Output System.out.println( Sum: + sum);

Repetitions(while, do while, and for) Using do-while: // Variable Declaration & Initialization int sum =0; int count =0; // Processing do { sum = sum + count; count = count +1; //same as count++ while (count <=1000); Using for: // Variable Declaration & Initialization int sum =0; // Processing for (int count =0; count <= 100; count++) { sum = sum +count;

Introducing Methods A method is a collection of statements that are grouped together to perform an operation. Method Structure returnvaluetype modifier methodname parameter list public static double readdouble() { double d = 0.0; try { String str = df.readline(); st = new StringTokenizer (str); d = new Double (st.nexttoken()).doublevalue(); catch (IOException ex) { System.out.println(ex); return d;

Declaring Methods /** * This method returns the maximum of two numbers * @param num1 the first number * @param num2 the second number * @return either num1 or num2 */ int max(int num1, int num2) { if (num1 > num2) { else { return num1; return num2;

Passing Parameters /** * This method prints a message a specified number * of times. * @param message the message to be printed * @param n the number of times the message is to be * printed */ void nprintln(string message, int n) { for (int i=0; i<n; i++) { System.out.println(message);

The main method One of these methods is required for every program you write. If your program does not have one, then you cannot run it. The main method has a very specific syntax: public static void main(string[] args) { // Your code goes here! For example: public static void main(string[] args) { System.out.println( Hello World! );

An Example Program class MyProgram { /** * This method prints a message a specified number * of times. * @param message the message to be printed * @param n the number of times the message is to be * printed */ void nprintln(string message, int n) { for (int i=0; i<n; i++) { System.out.println(message); public static void main(string[] args) { nprintln( Hello World!, 10);

Object-Oriented Programming in Java Java programs are formed from a set of classes. A class is a container for code. Whenever you create a program, you write your code inside one or more classes. Some of the classes you will use in your programs are pre-written and are provided as part of the Java Application Programming Interfaces (APIs). Other classes you must write yourself.

Object-Oriented Programming in Java When we run a Java Program, we may create objects. Objects are instances of classes. Classes describes a general set of features. Objects specify concrete values for those features. For example: Let us start with a general description of a car: A Car has four wheels, an engine, a chassis, a colour, some doors The next two descriptions refer to particular cars. My car is brown and has a 2 litre engine, a Saab chassis, and five doors. Peter has a yellow car with a 1.4 litre engine, a VW Polo chassis, and three doors.

How does this relate to Java? The general description of a Car is like a class in Java a general description of what constitutes a car. Both my car and Peter s car are described in terms of the general description of a car (i.e. the colour, engine size, chassis type, number of doors). These particular cars are like objects in Java - a concrete instance of the general description of a Car. Note: The number of wheels is the same for all cars. We call things that are the same for all cars constants.

Data Attributes Methods, and Messages Classes contain two types of feature: Data attributes describe the information that a class contains (for example the colour of a car, the type of chassis, etc.) Methods describe operations that can be performed by instances (objects) of the class (for example, a Bank Account class may include methods to withdraw or deposit cash). To get an object to perform a method we send a message: This message must be sent to that object identifying the method to be performed.

Class Declaration class Circle { public double radius = 1.0; Data attribute /** * This method calculates the area of the circle. * @return the area of the circle */ public double findarea() { return radius*radius*3.14159; Method

Declaring Object Variables Syntax: ClassName objectname; Example: Circle mycircle;

Creating Objects Syntax: objectname = new ClassName(); Example: mycircle = new Circle();

Declaring/Creating Objects in a Single Step Syntax: ClassName objectname = new ClassName(); Example: Circle mycircle = new Circle();

Accessing Objects Referencing the object s data: Syntax: objectname.data Example: mycircle.radius Referencing the object s method (sending a message): Syntax: objectname.method( ) Example: mycircle.findarea()

Constructors Constructors are special methods that are called upon creation of an object. Their purpose is to initialise objects as they are created. Syntax: ClassName( ) { // Initialisation code goes here! Example: Circle(double r) { radius = r;

Constructors Example (cont): Circle() { radius = 1.0; We can specify which constructor to use when we create a new object. Example: mycircle = new Circle(5.0);

Modifiers By default, the class, variable, or data can be accessed by any class in the same package. public The class, data, or method is visible to any class in any package. private The data or methods can be accessed only by the declaring class.

An Example Program class TestCircle { public static void main(string[] args) { Circle mycircle = new Circle(); System.out.println("The area of the circle of radius " + mycircle.radius + " is " + mycircle.findarea()); class Circle { double radius = 1.0; /** * This method calculates the area of the circle. * @return the area of the circle */ double findarea() { return radius*radius*3.14159;

Basic Java programs with println statements 32

Computer programs program: A set of instructions that are to be carried out by a computer. program execution: The act of carrying out the instructions contained in a program. programming language: A systematic set of rules used to describe computations in a format that is editable by humans. 33

Languages A partial history of programming languages Some influential ones: FORTRAN science / engineering COBOL business data LISP logic and AI BASIC a simple language 34

Some modern languages procedural languages: programs are a series of commands Pascal (1970): designed for education C (1972): low-level operating systems and device drivers functional programming: functions map inputs to outputs Lisp (1958) / Scheme (1975), ML (1973), Haskell (1990) object-oriented languages: programs use interacting "objects" Smalltalk (1980): first major object-oriented language C++ (1985): "object-oriented" additions to C; successful in industrial programming (Windows is built in C++) Java (1995): Sun Microsystems' language designed for embedded systems, web applications, servers Runs on many platforms (Windows, Mac, Linux, cell phones...) The language taught in this textbook 35

A basic Java program public class Hello { public static void main(string[] args) { System.out.println("Hello, world!"); code or source code: The sequence of instructions in a program. The code in this program instructs the computer to display a message of Hello, world! on the screen. output: The messages printed to the user by a program. console: The text box onto which output is printed. Some editors pop up the console as an external "DOS" window, and others contain their own console window. 36

Compiling/running a program Before you run your programs, you must compile them. compiler: Translates a computer program written in one language into another language. Java Development Kit includes a Java compiler. The Java compiler converts your source code into a format named byte code that can be executed on many different kinds of computers. source code (Hello.java) compile byte code (Hello.class) execute output 37

Another Java program public class Hello2 { 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"); The code in this program instructs the computer to print four messages on the screen. 38

Structure of Java programs public class <name> { public static void main(string[] args) { <statement>; <statement>;... <statement>; Every executable Java program consists of a class that contains a method named main that contains the statements (commands) to be executed 39

Java terminology class: A module that can contain executable code. Every program you write will be a class. statement: An executable command to the computer. method: A named sequence of statements that can be executed together to perform a particular action. A special method named main signifies the code that should be executed when your program runs. Your program can have other methods in addition to main. (seen later) 40

Syntax syntax: The set of legal structures and commands that can be used in a particular programming language. some Java syntax: every basic Java statement ends with a semicolon ; The contents of a class or method occur between { and 41

Syntax and syntax errors syntax error or compiler error: A problem in the structure of a program that causes the compiler to fail. If you type your Java program incorrectly, you may violate Java's syntax and see a syntax error. 1 public class Hello { 2 pooblic static void main(string[] args) { 3 System.owt.println("Hello, world!")_ 4 5 compiler output: Hello.java:2: <identifier> expected pooblic static void main(string[] args) { ^ Hello.java:5: ';' expected ^ 2 errors 42

Fixing syntax errors Error messages do not always help us understand what is wrong: Hello.java:2: <identifier> expected pooblic static void main(string[] args) { ^ We'd have preferred a friendly message such as, "You misspelled 'public' " The compiler does tell us the line number on which it found the error... But it is not always the true source of the problem. 1 public class MissingSemicolon { 2 public static void main(string[] args) { 3 System.out.println("A rose by any other name") 4 System.out.println("would smell as sweet"); 5 6 MissingSemicolon.java:4: ';' expected System.out.println("would smell as sweet"); ^ 43

System.out.println System.out.println : A statement to instruct the computer to print 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("<Message>"); Prints the given message as a line of text on the console. System.out.println(); Prints a blank line on the console. 44

Strings and string literals string: A sequence of text characters that can be printed or manipulated in a program. sometimes also called a string literal strings in Java start and end with quotation mark " characters Examples: "hello" "This is a string" "This, too, is a string. It can be very long!" 45

Details about Strings A string may not span across multiple lines. "This is not a legal String." A string may not contain a " character. (The ' character is okay) "This is not a "legal" String either." "This is 'okay' though." A string can represent certain special characters by preceding them with a backslash \ (this is called an escape sequence). \t \n \" \\ tab character new line character quotation mark character backslash character Example: Output: System.out.println("\\hello\nhow\tare \"you\"?"); \hello how are "you"? 46

Questions What is the output of each of the following println statements? System.out.println("\ta\tb\tc"); System.out.println("\\\\"); System.out.println("'"); System.out.println("\"\"\""); System.out.println("C:\nin\the downward spiral"); Write a println statement to produce the following line of output: / \ // \\ /// \\\ 47

Questions What println statements will generate the following output? This program prints a quote from the Gettysburg Address. "Four score and seven years ago, our 'fore fathers' brought forth on this continent a new nation." What println statements will generate the following output? A "quoted" String is 'much' better if you learn the rules of "escape sequences." Also, "" represents an empty String. Don't forget to use \" instead of "! '' is not the same as " 48

Procedural decomposition using static methods 49

Algorithms algorithm: A list of steps for solving a problem. How does one bake sugar cookies? (what is the "bake sugar cookies" algorithm?) Mix the dry ingredients. Cream the butter and sugar. Beat in the eggs. Stir in the dry ingredients. Set the oven for the appropriate temperature. Set the timer. Place the cookies into the oven. Allow the cookies to bake. Mix the ingredients for the frosting. Spread frosting and sprinkles onto the cookies. 50

Structured algorithms structured algorithm: An algorithm that is broken down into cohesive tasks. A structured algorithm for baking sugar cookies: 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 for the appropriate 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.... 51

Redundancy in algorithms How would we express the steps to bake a double batch of sugar cookies? Unstructured: Mix the dry ingredients. Cream the butter and sugar. Beat in the eggs. Stir in the dry ingredients. Set the oven... Set the timer. Place the first batch of cookies into the oven. Allow the cookies to bake. Set the oven... Set the timer. Place the second batch of cookies into the oven. Allow the cookies to bake. Mix the ingredients for the frosting. Structured: 1. Make the cookie batter. 2a. Bake the first batch of cookies. 2b. Bake the second batch of cookies. 3. Add frosting and sprinkles. Observation: Hierarchical, thus easier to understand. Higher-level operations help eliminate redundancy. 52

A program with redundancy redundancy: Occurrence of the same sequence of commands multiple times in a program. public class TwoMessages { public static void main(string[] args) { System.out.println("Now this is the story all about how"); System.out.println("My life got flipped turned upside-down"); System.out.println(); System.out.println("Now this is the story all about how"); System.out.println("My life got flipped turned upside-down"); Program's output: Now this is the story all about how My life got flipped turned upside-down Now this is the story all about how My life got flipped turned upside-down We print the same messages twice in the program. 53

Static methods static method: A group of statements given a name. procedural decomposition: breaking a problem into methods using a static method requires two steps: 1.declare it (write down the recipe) write a group of statements and give it a name 2.call it (cook using the recipe) tell our program to execute the method static methods are useful for: denoting the structure of a larger program in smaller pieces eliminating redundancy through reuse 54

Declaring a static method The syntax for declaring a static method (writing down the recipe): public class <class name> { public static void <method name> () { <statement>; <statement>;... <statement>; Example: public static void printwarning() { System.out.println("This product is known to cause"); System.out.println("cancer in lab rats and humans."); 55

Calling a static method The syntax for calling a static method (cooking using the recipe). In another method such as main, write: <method name> (); Example: printwarning(); A benefit of static methods is that you can call the method multiple times. printwarning(); printwarning(); Resulting output: This product is known to cause cancer in lab rats and humans. This product is known to cause cancer in lab rats and humans. 56

A program w/ static method public class TwoMessages { public static void main(string[] args) { displaymessage(); System.out.println(); displaymessage(); public static void displaymessage() { System.out.println("Now this is the story all about how"); System.out.println("My life got flipped turned upside-down"); Program's output: Now this is the story all about how My life got flipped turned upside-down Now this is the story all about how My life got flipped turned upside-down 57

Methods calling methods One static method can call another: 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."); Program's output: This is message1. This is message2. This is message1. Done with message2. Done with main. 58

Control flow of methods When a method is called: the execution "jumps" into that method, executes all of its statements, and then "jumps" back to the statement after the method call. public class MethodsExample { public static void main(string[] args) { public static void message1() { message1(); System.out.println("This is message1.");... message2(); public static void message2() { System.out.println("This is message2."); message1(); System.out.println("Done with main."); System.out.println("Done with message2."); public static void message1() { System.out.println("This is message1."); 59

Static method problems Write a program that prints the following output to the console. Use static methods as appropriate. I do not like my email spam, I do not like them, Sam I am! I do not like them on my screen, I do not like them to be seen. I do not like my email spam, I do not like them, Sam I am! Write a program that prints the following output to the console. Use static methods as appropriate. Lollipop, lollipop Oh, lolli lolli lolli Lollipop, lollipop Oh, lolli lolli lolli Call my baby lollipop 60

When to use static methods Place statements into a static method if: The statements are related to each other and form a part of the program's structure, or The statements are repeated in the program. You need not create static methods for: Individual statements only occurring once in the program. (A single println in a method does not improve the program.) Unrelated or weakly related statements. (Consider splitting the method into two smaller methods.) Only blank lines. (Blank println statements can go in the main method.) 61

Identifiers identifier: A name that we give to a piece of data or part of a program. Identifiers allow us to refer to that data later in the program. Identifiers give names to: classes methods variables, constants (seen in Ch. 2) Conventions for naming in Java: classes: capitalize each word (ClassName) methods: capitalize each word after the first (methodname) (variable names follow the same convention) constants: all caps, words separated by _ (CONSTANT_NAME) 62

Details about identifiers Java identifier names: first character must a letter or _ or $ following characters can be any of those or a number identifiers are case-sensitive (name is different from Name) Example Java identifiers: legal: susan second_place _myname TheCure ANSWER_IS_42 $variable illegal: me+u 49er question? side-swipe hi there ph.d jim's 2%milk suzy@yahoo.com 63

Keywords keyword: An identifier that you cannot use, because it already has a reserved meaning in the Java language. Complete list of Java keywords: 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 You may not use char or while or this for the name of a class or method; Java reserves those words to mean other things. You could use CHAR, While, or ThIs, because Java is case-sensitive. However, this could be confusing and is not recommended. 64

Comments comment: A note written in the source code by the programmer to make the code easier to understand. Comments are not executed when your program runs. Most Java editors show your comments with a special color. Comment, general syntax: /* <comment text; may span multiple lines> */ or, // <comment text, on one line> Examples: /* A comment goes here. */ /* It can even span multiple lines. */ // This is a one-line comment. 65

Using comments Where to place comments: at the top of each file (also called a "comment header"), naming the author and explaining what the program does at the start of every method, describing its behavior inside methods, to explain complex pieces of code (more useful later) Comments provide important documentation. Later programs will span hundreds or thousands of lines, split into many classes and methods. Comments provide a simple description of what each class, method, etc. is doing. When multiple programmers work together, comments 66

Comments example /* Suzy Student CS 101, Fall 2019 This program prints lyrics from my favorite song! */ public class MyFavoriteSong { /* Runs the overall program to print the song on the console. */ public static void main(string[] args) { sing(); // Separate the two verses with a blank line System.out.println(); sing(); // Displays the first verse of the theme song. public static void sing() { System.out.println("Now this is the story all about how"); System.out.println("My life got flipped turned upside-down"); 67

How to comment: methods Do not describe the syntax/statements in detail. Instead, provide a short English description of the observed behavior when the method is run. Example: // This method prints the lyrics to the first verse // of my favorite TV theme song. // Blank lines separate the parts of the verse. public static void verse1() { System.out.println("Now this is the story all about how"); System.out.println("My life got flipped turned upside-down"); System.out.println(); System.out.println("And I'd like to take a minute,"); System.out.println("just sit right there"); System.out.println("I'll tell you how I became the prince"); System.out.println("of a town called Bel-Air"); 68

Static methods question Write a program to print the following figures. Use static methods to capture structure and and eliminate redundancy. / \ / \ \ / \ / \ / \ / +--------+ / \ / \ STOP \ / \ / / \ / \ +--------+ 69

Problem-solving methodology Some steps we can use to print complex figures: / \ First version of program (unstructured): / \ \ / \ / \ / \ / +--------+ / \ / \ STOP \ / \ / / \ / \ +--------+ Create an empty program with a skeletal header and main method. Copy the expected output into it, surrounding each line with System.out.println syntax. Run our first version and verify that it produces the correct output. 70

Program, version 1 // Suzy Student, CSE 142, Autumn 2047 // This program prints several assorted figures. // public class Figures1 { public static void main(string[] args) { System.out.println(" "); System.out.println(" / \\"); System.out.println("/ \\"); System.out.println("\\ /"); System.out.println(" \\ /"); System.out.println(); System.out.println("\\ /"); System.out.println(" \\ /"); System.out.println("+--------+"); System.out.println(); System.out.println(" "); System.out.println(" / \\"); System.out.println("/ \\"); System.out.println(" STOP "); System.out.println("\\ /"); System.out.println(" \\ /"); System.out.println(); System.out.println(" "); System.out.println(" / \\"); System.out.println("/ \\"); System.out.println("+--------+"); 71

Problem-solving 2 / \ / \ \ / \ / \ / \ / +--------+ / \ / \ STOP \ / \ / Second version of program (structured with redundancy): Identify the structure of the output, and divide the main method into several static methods based on this structure. / \ / \ +--------+ 72

Problem-solving 2 answer / \ / \ \ / \ / \ / \ / +--------+ / \ / \ STOP \ / \ / / \ / \ +--------+ The structure of the output: initial "egg" figure second "teacup" figure third "stop sign" figure fourth "hat" figure This structure can be represented by methods: drawegg drawteacup drawstopsign drawhat 73

Program, version 2 // Suzy Student, CSE 142, Autumn 2047 // Prints several assorted figures, with methods for structure. // public class Figures2 { public static void main(string[] args) { drawegg(); drawteacup(); drawstopsign(); drawhat(); // Draws a figure that vaguely resembles an egg. public static void drawegg() { System.out.println(" "); System.out.println(" / \\"); System.out.println("/ \\"); System.out.println("\\ /"); System.out.println(" \\ /"); System.out.println(); // Draws a figure that vaguely resembles a teacup. public static void drawteacup() { System.out.println("\\ /"); System.out.println(" \\ /"); System.out.println("+--------+"); System.out.println(); 74

Program, version 2, cont'd. // Draws a figure that vaguely resembles a stop sign. public static void drawstopsign() { System.out.println(" "); System.out.println(" / \\"); System.out.println("/ \\"); System.out.println(" STOP "); System.out.println("\\ /"); System.out.println(" \\ /"); System.out.println(); // Draws a figure that vaguely resembles a hat. public static void drawhat() { System.out.println(" "); System.out.println(" / \\"); System.out.println("/ \\"); System.out.println("+--------+"); 75

Problem-solving 3 / \ / \ \ / \ / \ / \ / +--------+ / \ / \ STOP \ / \ / Third version of program (structured without redundancy): Identify any redundancy in the output, and further divide the program into static methods to eliminate as much redundancy as possible. Add comments to the program to improve its readability. / \ / \ +--------+ 76

Problem-solving 3 answer / \ / \ \ / \ / \ / \ / +--------+ / \ / \ STOP \ / \ / / \ / \ +--------+ The redundancy in the output: top half of egg: reused on stop sign, hat bottom half of egg: reused on teacup, stop sign divider line: used on teacup, hat a single line, so making it a method is optional This redundancy can be fixed by methods: draweggtop draweggbottom drawline (optional) 77

Program, version 3 // Suzy Student, CSE 142, Autumn 2047 // Prints several figures, with methods for structure and redundancy. public class Figures3 { public static void main(string[] args) { drawegg(); drawteacup(); drawstopsign(); drawhat(); // draws redundant part that looks like the top of an egg public static void draweggtop() { System.out.println(" "); System.out.println(" / \\"); System.out.println("/ \\"); // draws redundant part that looks like the bottom of an egg public static void draweggbottom() { System.out.println("\\ /"); System.out.println(" \\ /"); // Draws a figure that vaguely resembles an egg. public static void drawegg() { draweggtop(); draweggbottom(); System.out.println(); 78

Program, version 3, cont'd. // Draws a figure that vaguely resembles a teacup. public static void drawteacup() { draweggbottom(); System.out.println("+--------+"); System.out.println(); // Draws a figure that vaguely resembles a stop sign. public static void drawstopsign() { draweggtop(); System.out.println(" STOP "); draweggbottom(); System.out.println(); // Draws a figure that vaguely resembles a hat. public static void drawhat() { draweggtop(); System.out.println("+--------+"); 79

Another example Write a program to print the following block letters spelling "banana". Use static methods to capture structure and and eliminate redundancy. BBBBB B B BBBBB B B BBBBB AAAA A A AAAAAA A A N N NNN N N NNN N N AAAA A A AAAAAA A A N N NNN N N NNN N N AAAA A A AAAAAA A A 80