16-jan-16 just enough java. 2 what is java? java is a programming language: a language that you can...

31
May 15, 2 022 Just Enough Java

Upload: isaac-russell

Post on 06-Jan-2018

224 views

Category:

Documents


3 download

DESCRIPTION

3 Structure of a Java program A program, or project, consists of one or more packages Package = directory = folder A package contains one or more classes A class contains one or more fields and methods A method contains declarations and statements Classes and methods may also contain comments We’ll begin by looking at the “insides” of methods packages classes fields methods declarations statements Project:

TRANSCRIPT

Page 1: 16-Jan-16 Just Enough Java. 2 What is Java? Java is a programming language: a language that you can learn to write, and the computer can be made to understand

May 3, 2023

Just Enough Java

Page 2: 16-Jan-16 Just Enough Java. 2 What is Java? Java is a programming language: a language that you can learn to write, and the computer can be made to understand

2

What is Java?

Java is a programming language: a language that you can learn to write, and the computer can be made to understand

Java is currently a very popular language Java is a large, powerful language

but it is not simple! Compared to C++, Java is elegant

Page 3: 16-Jan-16 Just Enough Java. 2 What is Java? Java is a programming language: a language that you can learn to write, and the computer can be made to understand

3

Structure of a Java program A program, or project, consists of one or more packages

Package = directory = folder A package contains one or more classes A class contains one or more fields and methods

A method contains declarations and statements Classes and methods may also contain comments We’ll begin by looking at the “insides” of methods

• packages• classes

• fields• methods

• declarations• statements

Project:

Page 4: 16-Jan-16 Just Enough Java. 2 What is Java? Java is a programming language: a language that you can learn to write, and the computer can be made to understand

4

Java structure and Eclipse A workspace is where Eclipse keeps projects When you use Eclipse to create a project (a single

“program”), it creates a directory with that name in your workspace

Within the project, you next create a package It is possible to skip this step and use the “default” package

Finally, you create a class in that package

For the simplest program, you need only a single package, and only one (or a very few) classes

Page 5: 16-Jan-16 Just Enough Java. 2 What is Java? Java is a programming language: a language that you can learn to write, and the computer can be made to understand

5

Simple program outline

Notes: The class name (MyClass) must begin with a capital main and run are methods This is the form we will use for now

Once you understand all the parts, you can vary things

class MyClass {

public static void main(String[ ] args) { new MyClass().run(); }

void run() { // some declarations and statements go here // this is the part we will talk about today }

}

main method

another

method

Page 6: 16-Jan-16 Just Enough Java. 2 What is Java? Java is a programming language: a language that you can learn to write, and the computer can be made to understand

6

Syntax and semantics

Syntax is the “grammar” of the language The syntax of Java is large, but finite Syntax must be absolutely correct The computer will point out every syntax error Error messages may be helpful or misleading

Semantics is the “meaning” of your program Semantic errors cause your answers to be wrong You may or may not get error messages

Page 7: 16-Jan-16 Just Enough Java. 2 What is Java? Java is a programming language: a language that you can learn to write, and the computer can be made to understand

7

Two aspects of Java

Java has syntax and semantics This is where you begin It is possible to learn everything about Java’s syntax and

semantics We will cover most of Java’s syntax and semantics

Java comes with many built-in “packages” Packages are sort of like vocabulary bundles To be good at Java, you need to learn many packages There are more Java packages than you can ever learn

Page 8: 16-Jan-16 Just Enough Java. 2 What is Java? Java is a programming language: a language that you can learn to write, and the computer can be made to understand

8

What you need to know You need to be able to:

Read in data (for now, numbers) We will use a Scanner for this

Save numbers in variables We will use declarations to create variables

Do arithmetic on numbers to get new numbers We will use assignment statements

Test whether or not to do something We will use if statements

Do something repeatedly We will use while statements

Print output We will use System.out.print and System.out.println

Not absolutely necessary, but very helpful: We will use methods

Page 9: 16-Jan-16 Just Enough Java. 2 What is Java? Java is a programming language: a language that you can learn to write, and the computer can be made to understand

9

Declarations, statements, comments

A declaration gives some information to the computer A statement tells the computer to do something

Statements should really be called “commands” Comments are ignored by the computer—they are

explanations of your program for human beings to read

A method may contain declarations, statements, and comments

Page 10: 16-Jan-16 Just Enough Java. 2 What is Java? Java is a programming language: a language that you can learn to write, and the computer can be made to understand

10

Variables A variable is a “box” that holds data

Every variable has a name Examples: name, age, address, isMarried Variables start with a lowercase letter In multiword variables, each new word is capitalized

Every variable has a type of value that it can hold For example,

name might be a variable that holds a String (sequence of characters)

age might be a variable that holds an integer value isMarried might be a variable that holds a boolean (true or

false) value

Page 11: 16-Jan-16 Just Enough Java. 2 What is Java? Java is a programming language: a language that you can learn to write, and the computer can be made to understand

11

Some Java data types In Java, the four most important primitive (simple)

types are: int variables hold integer values double variables hold floating-point numbers, that is,

numbers containing a decimal point boolean variables hold a true or false value char variables hold single characters

Another important type is the String A String is an Object, not a primitive type A String is composed of zero or more chars

Page 12: 16-Jan-16 Just Enough Java. 2 What is Java? Java is a programming language: a language that you can learn to write, and the computer can be made to understand

12

Declaring variables Every variable that you use in a program must be

declared (in a declaration) The declaration specifies the type of the variable The declaration may give the variable an initial value

Examples: int age; int count = 0; double distance = 37.95; boolean isReadOnly = true; String greeting = "Welcome to CIT 591"; String outputLine;

Page 13: 16-Jan-16 Just Enough Java. 2 What is Java? Java is a programming language: a language that you can learn to write, and the computer can be made to understand

13

Reading in numbers First, import the Scanner class:

import java.util.Scanner; Create a scanner and assign it to a variable:

Scanner scanner = new Scanner(System.in);

The name of our scanner is scanner new Scanner(...) says to make a new one System.in says the scanner is to take input from the keyboard

Next, it’s polite to tell the user what is expected:System.out.print("Enter a number: ");

Finally, read in the number:myNumber = scanner.nextInt();

If you haven’t previously declared the variable myNumber, you can do it when you read in the number:

int myNumber = scanner.nextInt();

Page 14: 16-Jan-16 Just Enough Java. 2 What is Java? Java is a programming language: a language that you can learn to write, and the computer can be made to understand

14

Printing There are two methods you can use for printing:

System.out.println(something); This prints something and ends the line

System.out.print(something); This prints something and doesn’t end the line (so the next thing you print will

go on the same line) These methods will print anything, but only one thing at a

time You can concatenate (join) things with the + operator Example:System.out.println("There are " + appleCount + " apples and " + orangeCount + " oranges.");

Page 15: 16-Jan-16 Just Enough Java. 2 What is Java? Java is a programming language: a language that you can learn to write, and the computer can be made to understand

15

Program to double a number package numberStuff;

import java.util.Scanner;

public class Doubler {

public static void main(String[] args) { new Doubler().run(); }

private void run() { Scanner scanner; int number; int doubledNumber; scanner = new Scanner(System.in); System.out.print("Enter a number: "); number = scanner.nextInt(); doubledNumber = 2 * number; System.out.println("Twice " + number + " is " + doubledNumber); }}

Page 16: 16-Jan-16 Just Enough Java. 2 What is Java? Java is a programming language: a language that you can learn to write, and the computer can be made to understand

16

Assignment statements Values can be assigned to variables by assignment

statements The syntax is: variable = expression; The expression must be of the same type as the variable The expression may be a simple value or it may involve

computation Examples:

name = "Dave"; count = count + 1; area = (4.0 / 3.0) * 3.1416 * radius * radius; isReadOnly = false;

When a variable is assigned a value, the old value is discarded and totally forgotten

Page 17: 16-Jan-16 Just Enough Java. 2 What is Java? Java is a programming language: a language that you can learn to write, and the computer can be made to understand

17

One-line comments A comment is a note to any human reading the program; comments

are ignored by Java A single-line comment starts with // and goes to the end of the

line A comment may be put after a statement (on the same line) to say

something about that one statement A comment may be put on a line by itself, to say something about

the following statements Example:

// Swap the values of x and ytemp = x; // save old value of x in tempx = y; // replace old value of x with yy = temp; // this many comments is just silly

Page 18: 16-Jan-16 Just Enough Java. 2 What is Java? Java is a programming language: a language that you can learn to write, and the computer can be made to understand

18

Multiline comments A multiline comment starts with /* and ends with */

Typically, these comments extend over several lines /* Here is an example of a multiline comment. It isn’t a very inspired one, but I needed an example of some sort. */

Single-line and multiline comments are used to make notes to yourself about how a method does what it does

Javadoc comments (next slide) are used to tell other programmers what a class is for, or how to use a method

Page 19: 16-Jan-16 Just Enough Java. 2 What is Java? Java is a programming language: a language that you can learn to write, and the computer can be made to understand

19

Javadoc comments Javadoc comments, also called documentation comments or doc

comments, are multiline comments used to describe the purpose of classes and methods

Javadoc comments start with /** and end with */ Each internal line typically begins with a *

Javadoc comments for a class should contain these tags: @version number_or_date @author your_name (may have more than one of these)

Javadoc comments for a method may contain these tags: @param parameter_name description_of_this_parameter @return description_of_value_returned (omit if void) @throws exception description_of_when_problem_occurs

Page 20: 16-Jan-16 Just Enough Java. 2 What is Java? Java is a programming language: a language that you can learn to write, and the computer can be made to understand

20

Methods A method is a named group of declarations and statements

void tellWhatYearItIs( ) { int year = 2009; System.out.println("Hello in " + year + "!");}

The name of the above method is tellWhatYearItIs The word void says that this method does not return a value

We “call,” or “invoke” a method by naming it in a statement: tellWhatYearItIs( ); This should print out Hello in 2009!

Page 21: 16-Jan-16 Just Enough Java. 2 What is Java? Java is a programming language: a language that you can learn to write, and the computer can be made to understand

21

Organization of a class A class may contain data declarations and methods (and constructors,

which are like methods), but not statements A method may contain (temporary) data declarations and statements A common error:

• class Example {• int variable ; // simple declaration is OK

• int anotherVariable= 5; // declaration with initialization is OK

• variable = 5; // statement! This is a syntax error

void someMethod( ) {• int yetAnotherVariable; //declaration is OK• yetAnotherVariable = 5; // statement inside method is OK}

}

Page 22: 16-Jan-16 Just Enough Java. 2 What is Java? Java is a programming language: a language that you can learn to write, and the computer can be made to understand

22

Arithmetic expressions Arithmetic expressions may contain:

+ to indicate addition - to indicate subtraction * to indicate multiplication / to indicate division % to indicate remainder of a division (integers only) parentheses ( ) to indicate the order in which to do things

An operation involving two ints results in an int When dividing one int by another, the fractional part of the result is

thrown away: 14 / 5 gives 2 Any operation involving a double results in a double:3.7 + 1 gives 4.7

Page 23: 16-Jan-16 Just Enough Java. 2 What is Java? Java is a programming language: a language that you can learn to write, and the computer can be made to understand

23

Boolean expressions Arithmetic comparisons

result in a boolean value of true or false There are six comparison

operators: < less than <= less than or

equals > greater than >= greater than

or equals == equals != not equals

There are three boolean operators: && “and”--true only if both

operands are true || “or”--true if either

operand is true ! “not”--reverses

the truth value of its one operand

Example: (x > 0) && !(x > 99) “x is greater than zero and is

not greater than 99”

Page 24: 16-Jan-16 Just Enough Java. 2 What is Java? Java is a programming language: a language that you can learn to write, and the computer can be made to understand

24

String concatenation You can concatenate (join together) Strings with the +

operator Example: fullName = firstName + " " + lastName;

In fact, you can concatenate any value with a String and that value will automatically be turned into a String Example:System.out.println("There are " + count + " apples.");

Be careful, because + also still means addition int x = 3;int y = 5;System.out.println(x + y + " != " + x + y);

The above prints 8 != 35 “Addition” is done left to right--use parentheses to change the order

Page 25: 16-Jan-16 Just Enough Java. 2 What is Java? Java is a programming language: a language that you can learn to write, and the computer can be made to understand

25

if statements An if statement lets you choose whether or not to execute one

statement, based on a boolean condition Syntax: if (boolean_condition) statement; Example:

if (x < 100) x = x + 1; // adds 1 to x, but only if x is less than 100

C programmers take note: The condition must be boolean An if statement may have an optional else part, to be executed if

the boolean condition is false Syntax:

if (boolean_condition) statement; else statement;

Example:if (x >= 0 && x < limit) y = x / limit;else System.out.println("x is out of range: " + x);

Page 26: 16-Jan-16 Just Enough Java. 2 What is Java? Java is a programming language: a language that you can learn to write, and the computer can be made to understand

26

Compound statements Multiple statements can be grouped into a single statement by

surrounding them with braces, { } Example:

if (score > 100) { score = 100; System.out.println("score has been adjusted"); }

Unlike other statements, there is no semicolon after a compound statement

Braces can also be used around a single statement, or no statements at all (to form an “empty” statement)

It is good style to always use braces in the if part and else part of an if statement, even if they enclose only a single statement

Indentation and spacing should be as shown in the above example

Page 27: 16-Jan-16 Just Enough Java. 2 What is Java? Java is a programming language: a language that you can learn to write, and the computer can be made to understand

27

while loops A while loop will execute the enclosed statement as long as a

boolean condition remains true Syntax: while (boolean_condition) statement; Example: n = 1; while (n < 5) { System.out.println(n + " squared is " + (n * n)); n = n + 1; }

Result: 1 squared is 1 2 squared is 4 3 squared is 9 4 squared is 16

C programmers take note: The condition must be boolean Danger: If the condition never becomes false, the loop never exits,

and the program never stops

Page 28: 16-Jan-16 Just Enough Java. 2 What is Java? Java is a programming language: a language that you can learn to write, and the computer can be made to understand

28

Method calls A method call is a request to an object to do something,

or to compute a value System.out.print(expression) is a method call; you

are asking the System.out object to evaluate and display the expression

A method call may be used as a statement Example: System.out.print(2 * pi * radius);

Some method calls return a value, and those may be used as part of an expression Example: h = Math.sqrt(a * a + b * b);

Page 29: 16-Jan-16 Just Enough Java. 2 What is Java? Java is a programming language: a language that you can learn to write, and the computer can be made to understand

29

A complete program public class SquareRoots { // Prints the square roots of numbers 1 to 10 public static void main(String args[]) { int n = 1; while (n <= 10) { System.out.println(n + " " + Math.sqrt(n)); n = n + 1; } }}

1 1.02 1.41421356237309513 1.73205080756887724 2.05 2.23606797749979etc.

Page 30: 16-Jan-16 Just Enough Java. 2 What is Java? Java is a programming language: a language that you can learn to write, and the computer can be made to understand

30

Another complete programpublic class LeapYear {

public static void main(String[] args) { int start = 1990; int end = 2015; int year = start; boolean isLeapYear; while (year <= end) { isLeapYear = year % 4 == 0; // a leap year is a year divisible by 4... if (isLeapYear && year % 100 == 0) { // ...but not by 100... if (year % 400 == 0) isLeapYear = true; // ...unless it’s also divisible by 400 else isLeapYear = false; } if (isLeapYear) { System.out.println(year + " is a leap year."); } year = year + 1; } }}

1992 is a leap year.1996 is a leap year.2000 is a leap year.2004 is a leap year.2008 is a leap year.2012 is a leap year.

Page 31: 16-Jan-16 Just Enough Java. 2 What is Java? Java is a programming language: a language that you can learn to write, and the computer can be made to understand

31

The End

“If you give someone a program, you will frustrate them for a day;if you teach them how to program, you will frustrate them for a lifetime.” --Anonymous