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

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

Lab # 2. For today s lab:

Introduction to Computer Programming

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

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

Entering the world of Javatar

Java Bytecode (binary file)

Chapter 2 Author Notes

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

17 Hello world 18 Type: String: literal 19 Standard API: System: out.println() 20 Hello world 21 Statement 22 Statement: simple statements are ended w

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

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

List of Slides 1 Title 2 Chapter 2: Sequential execution and program errors 3 Chapter aims 4 Section 2: Example:Hello world 5 Aim 6 Class: programs ar

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

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

Class 1: Homework. Intro to Computer Science CSCI-UA.0101 New York University Courant Institute of Mathematical Sciences Fall 2017

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

CS 152: Data Structures with Java Hello World with the IntelliJ IDE

Computer Hardware. Java Software Solutions Lewis & Loftus. Key Hardware Components 12/17/2013

3 CREATING YOUR FIRST JAVA APPLICATION (USING WINDOWS)

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

UEE1302 (1102) F10: Introduction to Computers and Programming

Building Java Programs. Introduction to Programming and Simple Java Programs

Lecture 1: Basic Java Syntax

4 Programming Fundamentals. Introduction to Programming 1 1

Creating a Program in JCreator. JCreator is then used to create our program. But the first step is to create a new file.

Full file at

Fundamentals of Programming. By Budditha Hettige

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

A PROGRAM IS A SEQUENCE of instructions that a computer can execute to

Chapter 2: Programming Concepts

Lesson 04: Our First Java Program (W01D4

CS 177 Recitation. Week 1 Intro to Java

CSC116: Introduction to Computing - Java

Week 2: Data and Output

Introduction to Java Applications

Java Programming Fundamentals - Day Instructor: Jason Yoon Website:

COMP-202: Foundations of Programming. Lecture 2: Java basics and our first Java program! Jackie Cheung, Winter 2016

CSC116: Introduction to Computing - Java

CPS109 Lab 1. i. To become familiar with the Ryerson Computer Science laboratory environment.

Chapter 1. Introduction

Project 1. Java Control Structures 1/17/2014. Project 1 and Java Intro. Project 1 (2) To familiarize with

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

CS11 Java. Fall Lecture 1

Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal

Software and Programming 1

CHAPTER 2 Java Fundamentals

CSC116: Introduction to Computing - Java

COMP 110 Project 1 Programming Project Warm-Up Exercise

Identifiers. Identifiers are the words a programmer uses in a program Some identifiers are already defined. Some are made up by the programmer:

IT 374 C# and Applications/ IT695 C# Data Structures

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

Building Java Programs

Introduction to Java Applications; Input/Output and Operators

COMP-202: Foundations of Programming. Lecture 2: Java basics and our first Java program! Jackie Cheung, Winter 2015

Lecture Set 2: Starting Java

Chapter 3 Intro to Java

Lecture Set 2: Starting Java

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

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

Getting Started with Java. Atul Prakash

Chapter 1: A First Program Using C#

Building Java Programs

A A B U n i v e r s i t y

3. Except for strings, double quotes, identifiers, and keywords, C++ ignores all white space.

Basic Programming Language Syntax

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

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

CMSC 150 LECTURE 1 INTRODUCTION TO COURSE COMPUTER SCIENCE HELLO WORLD

Building Java Programs

Basics of Java Programming

Lec 3. Compilers, Debugging, Hello World, and Variables

Program Fundamentals

CS 251 Intermediate Programming Coding Standards

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

Get JAVA. I will just tell you what I did (on January 10, 2017). I went to:

Building Java Programs. Chapter 1: Introduction to Java Programming

Assignment Marking Criteria

CS 112 Introduction to Programming

Static Methods & Decomposition

Software and Programming 1

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

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

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

Programming with Java

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

An overview of Java, Data types and variables

CS 106 Introduction to Computer Science I

Getting started with Java

Getting Started with Eclipse/Java

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

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

Chapter 2: Introduction to C++

Chapter 2, Part I Introduction to C Programming

Chapter 2: Special Characters. Parts of a C++ Program. Introduction to C++ Displays output on the computer screen

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

Section 2: Introduction to Java. Historical note

Welcome to Python 3. Some history

PROGRAMMING STYLE. Fundamentals of Computer Science I

Introduction to Computer Science I

Transcription:

Introduction to Java Java Programs Classes, Methods, and Statements Comments Strings Escape Sequences Identifiers Keywords Program Errors Syntax Runtime Logic Procedural Decomposition Methods Flow of Control

Review source code (ClassName.java) code written by programmer (text) Class name defined in source code: public class ClassName {.. byte code (ClassName.class) result of compiling source code platform independence Java Virtual Machine (JVM) translates byte code to executable code for native machine

Review Compile To compile our code, we use the javac command followed by the name of the Java file we want to compile > javac HelloWorld.java Execute After you compile your code, you will notice a.class file has been created in your directory. We execute the class by telling the Java Virtual Machine to run it. The command to run the Virtual Machine is java and the name of the class > java HelloWorld

Structure of Java Programs Class Method(s) Statement(s)

Classes Class A unit of code that is the basic building block of Java programs. All code in a Java file is written in a class. Each Java file starts with the words public class and the name you wish to give your program. It is convention to start the class name with a capital letter The content of a class is enclosed in a set of open and closed curly { braces. public class ClassName {

Methods Method A program unit that represents a particular action or computation. Method header: public static void methodname () { A method is made up of statements contained within curly braces. Every executable program has a main method. Java begins execution of the program with the main method.

The main Method public class ClassName { public static void main(string[ ] args) { Whatever code we write inside the main method s curly braces is the first thing that is executed. Can be placed anywhere but the convention is to put it as either the first or last method in the class.

Statements Statement An executable snippet of code that represents a complete command. All statements end with a semicolon ; public class Program { public static void main(string[ ] args) { System.out.println("Hello World!"); For now, we will use print statements of the form: System.out.println("text"); An empty print statement will produce a blank line of text: System.out.println(); To print text without advancing to the next line: System.out.print("text");

Indent nested code Readability public class Example {...public static void main(string[] args) {...System.out.println("Please indent!");... Always use braces Avoid long lines See style guidelines

Comments When writing code, it is easy to forget what you have done after a week or two go by. Comments help you and others understand what your code does It is desirable to be able to write in our code what a particular section of the code accomplishes without it affecting the program Comments are sections of our source code that are ignored by the compiler

Single Line Comments If we want to write a comment on a single line, we begin the line with // // Print an empty line System.out.println(); We can also have a comment after code System.out.println(); // Print an empty line

Area Comments If we want to have consecutive lines in the source code be comments, we use /* and */ around our comment /* This entire area in our source code is ignored by the compiler */

Javadoc Comments A third style of commenting is called Javadoc. It is a special format of commenting that we will discuss in more detail later in the course. /** * Notice it starts with two stars, * and each line has its own star. * It also allows tags for things like the author. * @author Michelle Glatz */

String Literals String A sequence of characters enclosed in double-quotes. Can contain spaces, punctuation, and special characters Cannot span more than one line "I am a valid String literal" "I m an invalid String literal"

Practice Create a Lab2 folder (cd to your exercises folder and then mkdir Lab2, cd Lab2) and then create a file PrintTest.java in this folder that contains the following code: public class PrintTest { public static void main(string[] args) { Write statements in the main method that will print the following text to the console. Each line of text gets its own System.out.println(); A well-formed Java program has a main method with { and braces. A System.out.println statement has ( and ) and usually a String that starts and ends with a " character. (But we type \" instead!)

Code does not Compile Why? Errors: PrintTest.java:10: error: ')' expected System.out.println("with a " character."); ^ PrintTest.java:10: error: illegal start of expression System.out.println("with a " character."); ^ PrintTest.java:10: error: unclosed string literal System.out.println("with a " character."); ^ 3 errors The compiler doesn t think the " and \ characters are part of the String How can we make them part of the String?

Escape Sequences We use "escape sequences" to include characters like double-quotes, tabs, newlines, and backslashes in Strings. When writing a string, we need to mark double quotes that are part of the string So the compiler knows they are part of the string We mark them by putting a backslash in front We re making an escape sequence: \" We say we escape the " to show it s actually part of the string. System.out.println("with a \" character."); System.out.println("But we type \\\" instead!)");

Escape Sequences (cont.) Common Escape Sequences \" Double-quote \n New line \t Tab \\ Backslash

Escape Sequences (cont.) Tab \t Example System.out.println("This is a\ttab"); Newline \n Example System.out.println("This is a\nnewline"); Backslash \\ Example System.out.println("//\\\\");

Escape Sequence In-class Exercise /** * This program outputs text given in RS Exercises 1.5 on page 55 * * @author your name */ public class MuchBetter { public static void main(string[] args) { Write the text in Exercise 1.5 (pg. 55) within your MuchBetter main method. Each line of text gets its own System.out.println(); Use escape sequences so your output matches the listed output. Submit to moodle MuchBetter.java assignment.

MuchBetter program output A "quoted" String is 'much' better if you learn the rules of "escape sequences." Also, " " represents an empty String. Don't forget: use \" instead of "! '' is not the same as "

Identifiers Identifier A name given to an entity in a program. Class Method Must begin with a letter, underscore, or $. After the first letter, it must contain only letters, digits, underscores, or $ Can not be a Java keyword/reserved word

Java Keywords Keyword Word that is reserved for use by Java. Sometimes called reserved word. Don t use a keyword to name a class, method, variable, or constant! Java keywords in our HelloWorld program: public, class, static, void Complete list of keywords on page 20 of text.

Case-Sensitivity Java is a case-sensitive language. Upper-case letters are interpreted as completely different letters than lowercase letters Example is a completely different identifier in Java than example

Are These Valid Identifiers? abc 5abc $$$$$$$ class _abc ab_c$ hello! Public go4it

Naming Conventions Classes start with a capital letter; subsequent words are capitalized: HelloWorld, MyFirstProgram, LetterWriter Methods start with a lowercase letter; subsequent words are capitalized: main, calculatecost, myage, nameofstudent See Style Guidelines

Program Errors Syntax Errors Runtime Errors Logic Errors

Syntax Errors (Compile-time errors) Caught by the compiler Examples: Missing semicolon ; at the end of a statement Missing curly brace { or Missing keyword Misspelling a keyword or identifier Common Error Messages: Exercise1.java:10: error: ; expected System.out.println("String that starts and ends ") Exercise1.java:10: error: cannot find symbol System.out.pruntln("String that starts and ends"); ^ symbol: method pruntln(string) location: variable out of type PrintStream ^ Strategy: Fix first compiler error and recompile

More Example Syntax error messages When too many s: TestingErrors.java:8: error: class, interface, or enum expected Missing : TestingErrors.java:7: error: reached end of file while parsing ^ Missing keyword on method header: TestingErrors.java:2: error: invalid method declaration; return type required public static main(string[] args) { ^

Common Error Messages Class name and filename don t match: HelloWorld.java:1: error: class Hello is public, should be declared in a file named Hello.java public class Hello { ^ Execute javac classname without the.java extension: Error: Class names, HelloWorld', are only accepted if annotation processing is explicitly requested Execute java classname.java: Error: Could not find or load main class HelloWorld.java

Runtime Errors Discovered at Runtime: We are able to compile the program, but we are not able to run the program. Example: Missing (or misspelled) main method Error: main method not found in class HelloWorld, please define the main method as: public static void main(string[] args)

Logic Errors Program runs, but output/result is not correct Examples: Error in a calculation Incorrect output (ex. Words misspelled in printed String) Strategy: Test programs thoroughly! Think about special cases that could occur during execution Try to make general and special cases occur during execution Make sure the program handles all of them

Errors In-class Exercise Go to our moodle page and complete the LotsOfErrors.java inclass lab. Download the given LotsOfErrors.java file to your Lab2 folder. Fix the program so that it will compile and run without errors. Put a single line comment on each line that you modified describing the change that you made. Submit your corrected LotsOfErrors.java file. Note: Before you fix any of the errors, compile the program to see the error messages that java generates. This will help you recognize what error messages are generated for each type of error, which will hopefully be beneficial when trying to decipher error messages generated when compiling your code for future assignments. Fix the errors that java finds and recompile. Once the initial errors are corrected, java will find the remaining errors that you need to correct.

Procedural Decomposition Two types of programming Procedural - a set of tasks to be executed sequentially to accomplish a goal (like a recipe) Object-oriented a set of objects that can perform tasks on themselves and interact with each other (what Java was designed for) Dividing a larger action into smaller actions Example: Baking Cookies, Doing Laundry

Static Methods A block of Java statements that is given a name Methods allow us to decompose programs into smaller pieces. Methods allow us to reuse the same piece of code thus eliminating redundancy. Procedural style (not object oriented) method

Static Method Syntax Template public static void <name>() { <statement>; <statement>;... <statement>;

Method Header Keywords public static void <name>() public indicates that the method is available to be used by all parts of your program static this is a procedural (not-object oriented) method void this method does not return a value

Calling a Method We want to move our functionality out of main Use procedural decomposition to identify methods Put common functionality in identified methods Method Call: a command to execute another method, which causes all of the statements inside the called method to be executed methodname();

Flow of Control The order in which the statements of a Java program are executed Calling a method Control is transferred to the called method When the called method is complete, the control returns to the calling method method1() { stmta; stmtb; method2(); stmtc; method2() { stmtd; stmte; stmtf;

Flow of Control Example public class Tricky { public static void main(string[] args) { first(); second(); second(); first(); public static void first() { System.out.println("Inside first method"); public static void second() { System.out.println("Inside second method"); first();

Static Methods Example Write a program to print these figures using static methods to provide structure and eliminate redundancy. / \ / \ \ / \ / - - - - - - / \ / \ \ / \ / - - - - - - \ / \ / / \ / \ - - - - - - \ / \ /

Development Strategy / \ / \ \ / \ / - - - - - - / \ / \ \ / \ / - - - - - - \ / \ / / \ / \ - - - - - - \ / \ / First version (unstructured, redundant): Create an empty program and main method. Copy the expected output into it, surrounding each line with System.out.println() syntax. Run it to verify the output.

Program Version 1 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(); 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(" \\ /");

Development Strategy (cont) / \ / \ \ / \ / - - - - - - / \ / \ \ / \ / - - - - - - \ / \ / / \ / \ - - - - - - \ / \ / Second version (structured, without redundancy): Identify the structure of the output Identify redundancy in the output Divide the main method into static methods based on this structure. Identify redundancy in the output, and create methods to eliminate as much as possible. Add comments to the program.

Output Structure/Redundancy / \ / \ \ / \ / - - - - - - / \ / \ \ / \ / - - - - - - \ / \ / / \ / \ - - - - - - \ / \ / The structure of the output: initial total" figure ( top + bottom ) second line" divider figure third total" figure ( top + bottom ) fourth line + bottom" figure fifth top+line+bottom" figure This structure can be represented by methods: top line bottom

Program Version 2 // Prints several figures, with methods for structure and // redundancy. public class Figures2 { public static void main(string[] args) { total(); System.out.println(); line(); System.out.println(); total(); System.out.println(); lineplusbottom(); System.out.println(); totalwithline(); // Draws the total figure. public static void total() { top(); bottom(); // Draws the divider line. public static void line() { System.out.println("-\"-'-\"-'-\"-");...

Program Version 2, cont'd.... // Draws the line+bottom figure. public static void lineplusbottom() { line(); bottom(); // Draws total figure with divider line in middle. public static void totalwithline() { top(); line(); bottom(); // Draws the top half of the total figure. public static void top() { System.out.println(" "); System.out.println(" / \\"); System.out.println("/ \\"); // Draws the bottom half of the total figure. public static void bottom() { System.out.println("\\ /"); System.out.println(" \\ /");

Structure Diagram (Figures2) main total line lineplusbottom totalwithline top bottom line bottom top line bottom