Sie sind auf Seite 1von 32

Java Basics

Introduction

DrJava navigation

Java Basics

We will begin by typing simple commands in the DrJava interactions pane. (refer to page 19 in textbook)
Math Operators Java recognizes numbers and will automatically add, subtract, multiply and divide.

Mathematical Exercise

Type the following in DrJavas interactions pane:

34 + 26 (then press the Enter key)

DrJava automatically calculates the mathematical operation!

Do the same with the following mathematical operations:


26 3 3*4 4/2

Math Operators

The code 34 + 56 is a numeric expression that Java understands composed of two numbers and an operation that Java knows how to do. In Java, math symbols are called operators
Symbol Operator + * / % Addition Subtraction Multiplication Division Modulo (Remainder) Example 3+4=7 3 4 = -1 3 * 4 = 12 3/4 =0 3%4=3
(the remainder of the first number after it is divided by the second number)

Math Operators Exercise

Use DrJava to type the following in the interactions pane

Subtract 7 from 9 Add 7 to 3 Divide 3 by 2 Divide 4.6 by 2 Multiply 5 by 10 Find the remainder when you divide 10 by 3

Semicolon use

In Java you will end a programming statement with a semicolon (;) As you saw in the interactions pane, you can leave off the semicolon and DrJava will print the result of whatever you have typed. If you add the semicolon at the end of a Java statement in the interactions pane, DrJava will execute the statement but not automatically print the result in the interactions pane.

Semicolon use
IMPORTANT NOTE: Even though you do not have to type the semicolon after statements in the interactions pane, you must type the semicolon at the end of your statements in the definitions pane or the code will not compile. It is good practice to go ahead and use the semicolon in the interactions pane even though it is not required. But then, how will you show the result of a statement in the interactions pane?

Printing the Result of a Statement

The phrase System.out.println()

NOTE that ln is short for line, so even though many may mistake the l for the number 1 or a capital i, that would not be correct!

The phrase means Use the PrintStream object known as out in the System class to print out the value of whatever is in the parentheses followed by an end-of-line character DrJava will print the result of an expression in the interactions pane when you use System.out.println (expression). In the interactions pane, try the following:

System.out.println(34 + 56); (then hit Enter key)

If you have nothing in the parentheses, Java will just insert a new line.

Console Output Exercise

Complete the following in the interactions pane:

System.out.println(26 3); System.out.println(3 * 4); System.out.println(4 / 2); System.out.println(9 % 4); System.out.println(9 / 5 * -3 + 32); System.out.println(3 + 2 * 4); System.out.println((3 + 2) * 4); System.out.println("My" + "name"); System.out.println("256 + 234"); What happens?

Try using System.out.print(); instead

Mathematical Precedence

Normally, multiplication has higher precedence that addition by default it is done first. With the use of parenthesis, you can change the default order of evaluation of an expression. You can also use parenthesis to make clear the order of evaluation. Common Bug: Matching Parenthesis

When you use parenthesis, you will need to ensure that you have an open parenthesis for each close parenthesis. Otherwise, you will get a syntax error message.

Data Types in Math Expressions

Try this exercise by typing the following in the DrJava interaction pane:

Divide 3 by 2 Divide 3 by 2.0

Did you expect the results to be the same? Why do you think the results are different?

Data Types in Math Expressions (cont)

Java is a strongly typed language


Each value has a type associated with it Type tells the computer how to interpret the number

The compiler determines the type if it isnt specified (literals)


It is an integer, floating point, double, letter, etc

2 is an integer (by default) 2.0 is a floating point number (has a fractional part)

The result of an operation is in the same type as the operands


5 and 2 are integers so the answer is an integer 2 The type of the data determines how many bits are used to represent the value and how the bits are interpreted by the computer.

The type of the data determines how many bits are used to represent the value and how the bits are interpreted by the computer.

Casting

There are two floating point types in Java: float and double.

You can make one of the values floating point by adding .0 (then type is set to float by default)

3.0 / 2 3 / 2.0

Or you can specifically cast one of the values to the primitive types: float or double

(double) 3 / 2 3 / (float) 2

Type the expressions from above in the DrJava interactions pane to see the results.

Java Primitive Types

Integers (numbers without fractional parts) are represented by


The types: int or short or long 235, -2, 33992093, etc

Floating point numbers (numbers with fractional parts) are represented by

The types: double or float 3.233038983 -423.9, etc The type: char a b A etc

A single character is represented by


Notice the single quotes!

True and false values are represented by


The type: boolean true or false Note that these are reserved words in Java!

Types float or double


How should you decide to use one over the other? Type the following in DrJavas interactions pane:

float f = 1.23456789012345678901234567890f; double d = 1.23456789012345678901234567890d; System.out.println(f); System.out.println(d);

Basically, float can handle about 7 decimal places. A double can handle about 16 decimal places. Double is more precise than float. Float uses 4 bytes less memory. The decision gets down to what is important to the program precision or space?

Types Exercise

What type would you use for

The number of people in your family A grade The price of an item The answer to do you have insurance The number of people in the class The number of people in your school The number of people in your state

Comparison (Relational) Operators

Used to decide if a value is greater than, equal to, less than, or not equal to another. Result is boolean. Symbol Operator > < == != >= Greater than Less than Equal Not equal Greater than or equal to Less than or equal to Example

<=

4 > 3 is true 3 > 4 is false 2 < 3 is true 3 < 2 is false 3 == 3 is true 3 == 4 is false 3 != 4 is true 3 != 3 is false 3 >= 4 is true 3 >= 3 is true 2 >= 4 is false 2 <= 3 is true 2 <= 2 is true 4 <= 2 is false

Comparison Operators Exercise

In DrJava

Try out the comparison operators in the interactions pane

with numbers
3<4 4 <= 4 5<4 6 == 6.0

with characters (single alphabet letter)


Put single quote around a character a < b b < a a == a

Operator Order

The default evaluation order is

Negation (i.e. a negative number) Multiplication * Division / Modulo (remainder) % Addition + Subtraction By using parenthesis (3 + 4) * 2 versus 3 + 4 * 2

The default order can be changed


Math Operator Order Exercise

Try

2+3*5+4

How do you change it so that 2 + 3 happens first? How do you change it so that it multiplies the result of 2 + 3 and the result of 4 + 5?

Strings

Java has a type called: String A string is an object that has a sequence of characters

It can have no characters (the null string "") It can have many characters

"This is one long string with spaces in it.

Everything in a string will be printed out as it was entered; it will not be evaluated.

Even math operations 128 + 234

Java knows how to add strings

It returns a new string with the characters of the second string after the characters of the first

With no space automatically added

This is called concatenating or appending

Strings Exercises

Type the following in DrJavas interactions pane:

System.out.println(Mark); System.out.println(13 + 5); System.out.println(Barbara + Ericson); System.out.println(Barbara + + Ericson); System.out.println(Barbara + Ericson); System.out.println(The total is + (13 + 5)); System.out.println(The total is + 13 + 5);

Can you figure out what happened to the last input?

Escapes

What if you wanted to have a quote as part of a string? You need a way to tell the computer that the double quote inside the string is not the double quote that ends the string. In Java, the backslash \ character is used to treat the next character differently So, using \ will result in a double quote inside a string. Other escapes:

\n will force a new line \t will force a tab stop

Escapes Exercises

Type the following in DrJavas interactions pane:

System.out.println(Barb says, \Hi\.); System.out.println(This is on one line.\nThis is on the next); System.out.println(This is on one line.\n\tThis is indented on the next);

Variables
Weve used Java to do calculations and to append strings, but we have not stored the results of our calculations. We can store values by naming them, then we can access those values by using the variable names. We call naming values declaring a variable

When you declare a variable in Java, you specify the type for the variable and a name

type name type may be double, float, int, etc.

Specifying a type lets Java know how many bits to reserve in memory and how to interpret the bits. You assign a value to a variable using the = operator

type name = expression

Using Variables in Calculations


Refer to page 26 in the textbook We will calculate the total bill for a meal including the tip. We will begin with the bill value and multiply it by the percentage we want to tip (20%) to get the tip amount. We will then add the tip amount to the bill total to get the total amount to leave. We will then calculate how much each person should leave. We will use the type double to store the bill amount, tip, and total amount since these can be decimals. We will use the type int to hold the number of people since this will not be a decimal.

Variable Exercise

Type the following in DrJavas interactions pane:

int numPeople = 2; System.out.println(numPeople); double bill = 32.45; System.out.println(bill); double tip = bill * 0.2; System.out.println(tip); double total = bill + tip; System.out.println(total); double totalPerPerson = total / numPeople; System.out.println(totalPerPerson);

Memory Assignments of Variables

In Java when you declare variables to be of the type int or double you are asking the computer to:

set aside space for a variable of that type (32 bits for int and 64 bits for double) and to remember the address of that space.

0 1 2 3 4
5 6 7 8 9 10 11

int numPeople = 2
Reserves 32 bits (4 bytes) and sets the value stored in that space to 2. The name numPeople is associated with this space.

double bill = 32.45 Reserves 64 bits (8 bytes) and sets the value stored in that space to 32.45. The name bill is associated with this space.

Summary

Java has typical math and relational operators Java is a strongly typed language

This can lead to odd results

integer division gives a integer result

You can use casting to solve this

Java has primitive types to represent integer and floating point numbers Math operations have a default order

You can specify the order with parentheses A string is an object that has a sequence of characters When you declare a variable in Java, you specify the type for the variable and a name You assign a value to a variable using the = operator

Strings

Variables

Assignment (due tomorrow)

Finish reading Chapter 2 of the textbook (p28 55) Review any portions of Chapter 2 that you did not understand during the PowerPoint and DrJava examples Complete the Chapter 2 Problems handout and turn in for credit

Das könnte Ihnen auch gefallen