Chapter 1 Introduction to Java

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

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

Full file at

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

Full file at

Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal

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

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

Computational Expression

Program Fundamentals

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

Introduction to Java Applications; Input/Output and Operators

Introduction to Java Applications

Course Outline. Introduction to java

TOPIC 2 INTRODUCTION TO JAVA AND DR JAVA

VENTURE. Section 1. Lexical Elements. 1.1 Identifiers. 1.2 Keywords. 1.3 Literals

AP Computer Science A

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

Expressions and Data Types CSC 121 Spring 2017 Howard Rosenthal

2.5 Another Application: Adding Integers

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

StudyHub+ 1. StudyHub: AP Java. Semester One Final Review

CEN 414 Java Programming

Getting started with Java

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

CS112 Lecture: Variables, Expressions, Computation, Constants, Numeric Input-Output

Chapter 2: Programming Concepts

A variable is a name for a location in memory A variable must be declared

Lecture Set 2: Starting Java

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

Lecture Set 2: Starting Java

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

Introduction to Java & Fundamental Data Types

JAVA Programming Fundamentals

Object-Oriented Programming

CSC 1051 Algorithms and Data Structures I. Midterm Examination February 24, Name: KEY 1

Datatypes, Variables, and Operations

Chapter 2: Using Data

CMPT 125: Lecture 3 Data and Expressions

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

12/22/11. Java How to Program, 9/e. public must be stored in a file that has the same name as the class and ends with the.java file-name extension.

Chapter 02: Using Data

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

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

Java How to Program, 10/e. Copyright by Pearson Education, Inc. All Rights Reserved.

Key Differences Between Python and Java

Chapter 1 Introduction to java

Using Graphics. Building Java Programs Supplement 3G

Interpreted vs Compiled. Java Compile. Classes, Objects, and Methods. Hello World 10/6/2016. Python Interpreted. Java Compiled

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

Basics of Java Programming

Lesson 02 Data Types and Statements. MIT 11053, Fundamentals of Programming By: S. Sabraz Nawaz Senior Lecturer in MIT Department of MIT FMC, SEUSL

Building Java Programs

Decisions: Logic Java Programming 2 Lesson 7

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

Oct Decision Structures cont d

Chapter 2: Using Data

Sir Muhammad Naveed. Arslan Ahmed Shaad ( ) Muhammad Bilal ( )

PROGRAMMING FUNDAMENTALS

CS112 Lecture: Working with Numbers

4 Programming Fundamentals. Introduction to Programming 1 1

c) Comments do not cause any machine language object code to be generated. d) Lengthy comments can cause poor execution-time performance.

Programming for Engineers Introduction to C

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

Chapter 2 Elementary Programming

VARIABLES & ASSIGNMENTS

Lab5. Wooseok Kim

JAVA OPERATORS GENERAL

Computer Programming, I. Laboratory Manual. Experiment #2. Elementary Programming

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

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

Chapter 2: Basic Elements of C++

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

2. Numbers In, Numbers Out

DaMPL. Language Reference Manual. Henrique Grando

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

Objectives. In this chapter, you will:

Chapter 2 Working with Data Types and Operators

Chapter 2. Elementary Programming

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

COMP-202: Foundations of Programming. Lecture 2: Variables, and Data Types Sandeep Manjanna, Summer 2015

Data Types and the while Statement

Objects and Types. COMS W1007 Introduction to Computer Science. Christopher Conway 29 May 2003

A Java program contains at least one class definition.

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

Hello World. n Variables store information. n You can think of them like boxes. n They hold values. n The value of a variable is its current contents

CS112 Lecture: Primitive Types, Operators, Strings

A very simple program. Week 2: variables & expressions. Declaring variables. Assignments: examples. Initialising variables. Assignments: pattern

Fundamentals of Programming Session 4

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

Elementary Programming

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

CSE115 / CSE503 Introduction to Computer Science I Dr. Carl Alphonce 343 Davis Hall Office hours:

Chapter 3 Syntax, Errors, and Debugging. Fundamentals of Java

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

CSCI 1103: Introduction

Java How to Program, 9/e. Copyright by Pearson Education, Inc. All Rights Reserved.

Simple Java Reference

Crayon (.cry) Language Reference Manual. Naman Agrawal (na2603) Vaidehi Dalmia (vd2302) Ganesh Ravichandran (gr2483) David Smart (ds3361)

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

Transcription:

Chapter 1 Introduction to Java Lesson page 0-1. Introduction to Livetexts Question 1. A livetext is a text that relies not only on the printed word but also on graphics, animation, audio, the computer, and the active participation of the reader. Lesson page 1-1. Hardware and software Question 1. A program is a set of instructions, written in a programming language, for a computer to execute. Question 2. A programming language is a language in which programs are written for a computer to carry out or execute. Question 3. The machine language is the language that a computer is designed to execute. Question 4. An assembly language is a symbolic language that reflects the machine language of a computer it includes one symbolic instruction for each machine language instruction. Activity 1-1-1 Hardware versus software Activity 1-1-2 Computer memory Question 5. Memry is the set of locations (bytes) of a computer that holds the programs and the data that the programs are manipulating when the program is being executed. Each location has a number by which it is referenced, called its address. Typically, the contents of memory is lost when the computer is turned off. Question 6. The address of a memory location is the number by which a memory location is referenced. The first memory location has address 0, the second 1, and so on. Question 7. A bit is either a 0 or a 1. Short for binary digit. Question 8. A byte is an eight-bit quantity, a memory location consisting of eight bits, and also a Java primitive type.

4 Chapter 1. Introduction to Java Question 9. Symbols used in decimal notation: 0 1 2 3 4 5 6 7 8 9. Question 10. Symbols used in binary notation: 0 1. Question 11. Here are the binary equivalents of the first 20 decimal numbers: 0: 0 5: 101 10: 1010 15: 1111 1: 1 6: 110 11: 1011 16: 10000 2: 10 7: 111 12: 1100 17: 10001 3: 11 8: 1000 13: 1101 18: 10010 4: 100 9: 1001 14: 1110 19: 10011 Lesson page 1-2. Some simple Java programs Activity 1-2-1 A do-nothing Java program Question 1. In Java, a keyword is a word that has been reserved for a special purpose. Question 2. A method is a parameterized sequence of instructions. Java has three kinds of method: procedure, function, and constructor. Question 3. Execution starts by calling method main. Question 4. Every program has a method called main. Question 5. The class is the basic building block of Java. Question 6. The body of a class begins with { and ends with. Question 7. True; instruction and statement mean the same thing. Question 8. Here s the program with incorrect parts boxed: // This program won t even compile. public class Garble ( public static void start (String[] args) { ) Activity 1-2-2 A program that prints Question 9. The Java console is a window that appears when a Java program is executed. Output from println statements will appear here. Question 10. The instruction println moves the cursor to the next line after printing its argument in the Java console; print does not. Question 11. The following appears on the Java console, and the cursor is right after the e of everyone. Hello, everyone Question 12. Here s the program:

Chapter 1. Introduction to Java 5 public class PrintPractice { public static void main(string[] arguments) { System.out.println("Frances"); System.out.println(); System.out.println("#5 from the lighthouse"); Activity 1-2-3 A program that creates a window Question 13. API stands for Application Programming Interface. Question 14. GUI stands for Graphical User Interface. Question 15. A package is a collection of classes. Question 16. Package java.io deals with input/output. Question 17. Package javax.swing deals with GUI components. Question 18. This must appear at before the class: import javax.swing.*; Question 19. Class JFrame deals with windows. Question 20. Here s the program: import javax.swing.*; public class WindowPractice { public static void main(string[] args) { (new JFrame()).show(); (new JFrame()).show(); (new JFrame()).show(); Activity 1-2-4 A program that draws Question 21. import javax.swing.*; and import java.awt.*; Question 22. Method paint redraws the graphics window: Question 23. Method paint is called by the system when it decides that the graphics window has to be redrawn (e.g. if you had covered it with another window and then uncovered it). Question 24. Originally, the origin (pixel (0,0)) is the top-left corner of the window. In this program, it is has been changed to be under the title. Question 25. This statement sets the color: g.setcolor(color.black); Question 26. In (a,b), a is the horizontal coordinate. Question 27. False; the two pixels are the same distance from the bottom.

6 Chapter 1. Introduction to Java Question 28. False. Question 29. g.drawstring("wahoo!", 40, 60); Question 30. Here s the modified program: // A simple graphics window. import java.awt.*; public class JLiveGraphics1 extends Frame { // Repaint the Graphics Window with a silly face. public void paint(graphics g) { g.translate(getinsets().left, getinsets().top); g.setcolor(color.black); g.drawrect(77,10,40,30); g.drawstring("rectangle",77,60); g.setcolor(color.red); g.drawoval(15,10,30,30); g.drawstring("circle",15,60); g.setcolor(color.black); g.drawoval(15,10,90,90); g.setcolor(color.blue); g.drawoval(40,34,10,10); g.drawoval(70,34,10,10); g.setcolor(color.red); g.drawrect(58,50,4,15); g.drawoval(40,75,40,5); Activity 1-2-5 Simple Java program exercises Lesson page 1-3. Components of a Java program Activity 1-3-1 Comments and whitespace Question 1. Comments improve the reader s ability to understand the program. Question 2. The comment begins with /* and ends with */. Question 3. // Store in s the sum of the integers from 1 to n Question 4. The five forms of whitespace are given below. Whether you get an end-of-line character, a return character, or both when you press the return/enter key depends on the operating system you ar using. 1. The space character, which you get by typing the space bar on the keyboard.

Chapter 1. Introduction to Java 7 2. The tab character, which you get by typing the tab key. 3. The end-of-line character, you may get by typing the return/enter key. 4. The return character, which you may get by typing the return/enter key. 5. A comment. Question 5. False; comments are a form of whitespace. Question 6. Whitespace can appear between symbols of a Java program. Question 7. Whitespace cannot appear in the middle of a symbol. Question 8. Here s the program: // A simple graphics window. import java.awt.*; public class JLiveGraphics1 extends Frame { /* Repaint the Graphics Window with a silly face. */ public void paint(graphics g) { /* g.translate(getinsets().left, getinsets().top); g.setcolor(color.black); g.drawrect(77,10,40,30); g.drawstring("rectangle",77,60); g.setcolor(color.red); g.drawoval(15,10,30,30); g.drawstring("circle",15,60); */ // Draw the circular face, two blue eyes, // a narrow rectangular nose, and oval mouth. g.setcolor(color.black); g.drawoval(20,65,80,80); g.setcolor(color.blue); g.drawoval(40,84,10,10); g.drawoval(70,84,10,10); g.setcolor(color.red); g.drawrect(58,100,4,15); g.drawoval(40,125,40,5);

8 Chapter 1. Introduction to Java Activity 1-3-2 Exercises on comments and whitespace Activity 1-3-3 Keywords and identifiers Question 9. In Java, a keyword is a word that has been reserved for a special purpose. Question 10. import, public (used twice), class, static, void. Question 11. An identitfier is a case-sensitive sequence of characters where: 1. The first character is a lowercase letter, an uppercase letter, an underscore, or a dollar sign. 2. Each other character is a digit, a lowercase letter, an uppercase letter, an underscore, or a dollar sign. 3. Keywords may not be used as identifiers. 4. It is advisable not to use the dollar sign in identifiers because identifiers with dollar signs are used in special circumstances, which may conflict with your use of them. Question 12. Another word for alphameric is alphanumeric. Question 13. The dollar sign $ and the underscore can appear in identifiers. Question 14. False. Identifiers are case-sensitive in Java. Question 15. The conflicting guidelines are: 1. Long identifiers that relate to what they are used for are good. 2. To keep a program short, use short identifiers. Activity 1-3-4 Exercises on keywords and identifiers Activity 1-3-5 Variables and types Question 16. A variable is a name together with an associated value. Question 17. False. Keywords can not be used as identifiers. Question 18. A type is a set of values together with operations on them. Question 19. A variable declaration is a Java construct that declares a variable and gives its type. Its basic form is <type> <identifier> ;. Question 20. The three parts of a variable declaration are: 1. a type (such as int), which describes the values the variable can contain; 2. an identifier, which is the name given to the variable; and 3. a semicolon.

Chapter 1. Introduction to Java 9 Question 21. The range of int is: -2147483648..2147483647. Question 22. The range of byte is: -128..127. Question 23. Type String is not a primitive type; it is defined in package java.lang. Activity 1-3-6 Expressions Question 24. Division with both operands of type int is done as follows: perform conventional division; then truncate the result toward 0 to an integer. For example: 7 / 2 = 3 (-7) / 2 = -3 Question 25. Here s the program and its output: public class IntPrint { public static void main(string[] bob) { System.out.println(5 + 2 * 3); System.out.println(5 + (2 * 3)); System.out.println((5 + 2) * 3); System.out.println(5 / 2); System.out.println(7 / 2 * 4); System.out.println(7 / (3 * - 2)); Output: 11 11 21 2 12-1 Question 26. Here s a program that does the job: public class IntPrint { public static void main(string[] bob) { int x= 5; int y= 2; int z= 3; z= 4; System.out.println(z); x= 5; y= 2; z= 3; z= y; System.out.println(z); x= 5; y= 2; z= 3;

10 Chapter 1. Introduction to Java z= 22 / x; System.out.println(z); x= 5; y= 2; z= 3; z= x + z; System.out.println(z); x= 5; y= 2; z= 3; z= x + (z * y); System.out.println(z); x= 5; y= 2; z= 3; z= y + z * x; System.out.println(z); Output: 4 2 4 8 11 17-9 x= 5; y= 2; z= 3; z= (3 * (- (z))); System.out.println(z); Activity 1-3-7 Exercises on variables and expressions Lesson page 1-4. Three statements: assignment, conditional and block statements Activity 1-4-1 The assignment statement Question 1. <variable>= <expression>; Question 2. <type> <identifier>; Question 3. To execute an assignment statement: (1) evaluate the expression and (2) store the value of the expression in the variable. Question 4. False. A variable may be assigned many times during execution of a program. Question 5. Here s the program:

Chapter 1. Introduction to Java 11 public class AssignmentPractice { public static void main(string[] args) { int csquared= (3*3) + (5*5); System.out.print(cSquared); Output: 34 Activity 1-4-2 Swapping two variables Question 6. public class Swap { public static void main(string[] args) { int a= 1; int b = 2; int c= 3; // Rotate (the values of) a, b, and c. int temp= a; a= b; b = c; c= temp; Activity 1-4-3 Conditional statements: if Question 7. The form of the if-statement is: if ( <boolean expression> ) <statement > Question 8. A boolean expression evaluates to either true or false. Question 9. If the condition is true, the statement is executed. Question 10. If the condition is false, the if-statement terminates (without executing the statement). Activity 1-4-4 Conditional statements: if-else Question 11. The form of the if-else-statement is: if ( <boolean expression> ) <statement1 > else <statement2 > Question 12. If the condition is true, the then-part (statement1 ) isexe- cuted. Question 13. If the condition is false, the else-part (statement2 ) is executed.

12 Chapter 1. Introduction to Java Activity 1-4-5 Boolean expressions Question 14. The boolean values are: true and false. Question 15. A boolean expression is an expression that evaluates to either false or true. Question 16. A proposition is a declarative sentence; one that can be interpreted to be either true or false; it is verbal expression that is either false or true. Question 17. These six expressions produce a boolean value (when evaluated): 1. a < b 2. a == b 3. a > b 4. a <= b 5. a!= b 6. a >= b Question 18. Three boolean operators are: 1. negation:! 2. and: && 3. or: Question 19. Here s the program: Output: public class BooleanPractice { public static void main(string[] arg) { System.out.println(true && false); System.out.println(true false); System.out.println(false false); System.out.println(false && false); System.out.println(false && true); System.out.println(false true); System.out.println(false &&!true); System.out.println(!false); System.out.println(!true);

Chapter 1. Introduction to Java 13 false true false false false true false true false Activity 1-4-6 Blocks Question 20. To aggregate means to bring together, to collect into one sum, mass, or body. Accordingly, an aggregate is a sum, mass, or assemblage of particulars. Question 21. The block has the form { <sequence of statements and declarations> Question 22. False. Question 23. The rule is: indent substatements of a block to help make the structure of a program clear. Question 24. Here is the fixed program: public class ErrorRiddled { public static void main(string[] args) { Activity 1-4-7 Exercises on assignments, conditionals, and blocks Question 25. First version: public class IfX { public static void main(string args[]) { int y= 3; int x= 4; if (x < y) x= y + x; System.out.println("Now x >= y."); Second version: public class IfX { public static void main(string args[]) {

14 Chapter 1. Introduction to Java int y= 3; int x= 2; if (x < y) { x= y + x; System.out.println("Now x < y."); Lesson page 1-5. Input/Output Activity 1-5-1 Using the Java Console for output Question 1. The output of the program is: Once more unto the breach, dear friends, once more; Or close the wall up... -Shakespeare, King Henry V, Act 3, Scene 1 Activity 1-5-2 Using the Java Console for input Question 2. To prompt means to give a cue, to assist by suggesting something. In computing, one prompts the user to input text from the keyboard (or do other things as well) by printing a message of some form. Question 3. Add a space after the "i" in "Hi" or before the "P" in "Phred". high 5 340 5.0 is five See note 1 below. Is five 3.41.6 See note 2 below. 1. The values (from left to right) are of type double, double, String. The first + the second results in a double. Anything + a String results in a String. So 3.4 + 1.6 = 5.0; 5.0 + " is five" results in "5.0 is five". 2. The values (from left to right) are: String, double, double.astring + anything results in a String. So"Is five " + 3.4 results in "Is five 3.4". Then "Is five 3.4" + 1.6 results in "Is five 3.41.6". Activity 1-5-3 A GUI: JLiveWindow Question 4. 1. MyJLiveWindow testjlivewindow= new MyJLiveWindow(3, 0, 0);

Chapter 1. Introduction to Java 15 2. (a) Multiply the number in field 0 by the number in field 1 and store the result in mult. setintfield(2,mult); (b) Subtract the number in field 1 from the number in field 0 and store the result in other. setintfield(2,other); (c) Divide the number in field 0 by the number in field 1 and store the result in divresult. setintfield(2,divresult); If you type 4 into field 0 and 3 into field 1, 1 is displayed in field 2. The division results in an integer, and the fraction part is discarded. Activity 1-5-4 Exercises on the Java console and GUIs Activity 1-5-5 Graphics windows Question 5. No answer is provided. Activity 1-5-6 Using a graphics window Question 6. We would expect this statement to store the larger of a and b in x. Question 7. Here s method paint: public void paint(graphics g) { g.translate(getinsets( ).left, getinsets( ).top); g.drawoval(20,20,40,40); g.setcolor(color.magenta); g.drawoval(40,20,40,40); g.setcolor(color.blue); g.drawoval(30,40,40,40); Activity 1-5-7 Exercises on graphics windows Lesson page 1-6. Assertions in programs Activity 1-6-1 Relations about variables and values Question 1. A relation is a true-false statement. Question 2. In Java, the symbol for mathematical equality is: == Activity 1-6-2 Simplifying a particular kind of relation Question 3. True. Dogs can mean feet. Question 4. If it is not raining, wetpeople could be true or false.

16 Chapter 1. Introduction to Java Question 5. If it is raining, wetpeople is true; otherwise wetpeople is false. Or: It is raining = wetpeople. Question 6. greater0 == (x > 0) Question 7. I ll eat my hat = you re right. Or: If you re right, I ll eat my hat; otherwise I won t. Question 8. rain= it is raining Activity 1-6-3 Assertions Question 9. An assertion is a relation that is placed in a program (as a comment) in order to assert that it is true when execution of the program reaches that place. Question 10. A Hoare triple consists of an assertion (the precondition) followed by a statement followed by another assertion (the postcondition). It has the meaning: execution of the statement begun with the precondition true is guaranteed to terminate, and when it terminates, the postcondition will be true. Question 11. A precondition of a statement is an assertion that is placed before the statement. Question 12. A postcondition of a statement is an assertion that is placed after the statement. Question 13. This is what the code means: if (x+y)*y = 82 is true before execution of the statement x= x+y;, then execution will terminate, and when it does, x*y = 82 will be true. Lesson page 1-7. expressions Additional statements and