03 data types, variables & operators

58
Data Types, Variables & Operators AHMAD MURSYIDUN NIDHOM, S.PD, M.PD TEKNIK ELEKTRO   UNIVERSITAS NEGERI MALANG

Upload: riorokutom

Post on 02-Jun-2018

237 views

Category:

Documents


0 download

TRANSCRIPT

8/10/2019 03 Data Types, Variables & Operators

http://slidepdf.com/reader/full/03-data-types-variables-operators 1/66

Data Types,Variables &

OperatorsAHMAD MURSYIDUN NIDHOM, S.PD, M.PD

TEKNIK ELEKTRO – UNIVERSITAS NEGERI MALANG

8/10/2019 03 Data Types, Variables & Operators

http://slidepdf.com/reader/full/03-data-types-variables-operators 2/66

Memory and DataSalah satu komponen penting komputer adalah memory .

Memori komputer menyimpan:data yang akan diproses

data hasil dari sebuah proses

Dapat kita bayangkan bahwa sebuah memori komputer tersusunatas kotak-kotak/ laci untuk menyimpan data.

Ukuran kotak akan tergantung pada tipe data yang dipakai.

8/10/2019 03 Data Types, Variables & Operators

http://slidepdf.com/reader/full/03-data-types-variables-operators 3/66

Identifiers

Kita harus memberi nama untuk setiap kotak memori yang kitapakai untuk menyimpan data.

Nama itulah yang dikenal sebagai nama variabel , atau identifiers .

Data asli adalah nilai literal dari identifier.

subject

BIT106 value of subject

identifier / variable nam

The box is identified assubject and it stores thevalue “BIT106”

8/10/2019 03 Data Types, Variables & Operators

http://slidepdf.com/reader/full/03-data-types-variables-operators 4/66

Java Spelling Rules

An identifier can consist of:Sebuah identifier dapat tersusun dari:

Letters/ huruf (A – Z, a – z)

Digits/ angka (0 to 9)

the characters/ karakter _ and $

The first character cannot be a digit.

Karakter pertama tidak boleh sebuah angka.

8/10/2019 03 Data Types, Variables & Operators

http://slidepdf.com/reader/full/03-data-types-variables-operators 5/66

Identifier Rules

A single identifier must be one word only (no spaces) of any length.Sebuah identifier harus berupa satu kata (tanpa spasi) denganpanjang berapapun.

Java is case-sensitive .Reserved Words cannot be identifiers.

These are words which have a special meaning in Java

Kata-kata yang telah memiliki makna khusus dalam bahasa Java

8/10/2019 03 Data Types, Variables & Operators

http://slidepdf.com/reader/full/03-data-types-variables-operators 6/66

ExamplesExamples of identifiers

num1 num2 first_name lastName

numberOfStudents accountNumber

myProgram MYPROGRAM

Examples of reserved wordspublic if int double

see Appendix 1 in the text book for others.

Illegal identifiers3rdValue my program this&that

8/10/2019 03 Data Types, Variables & Operators

http://slidepdf.com/reader/full/03-data-types-variables-operators 7/66

Exercise

Which of the following are valid identifier names? my_granny’s_name

joesCar

integer

2ndNum

Child3double

third value

mid2chars

PUBLIC

8/10/2019 03 Data Types, Variables & Operators

http://slidepdf.com/reader/full/03-data-types-variables-operators 8/66

Types of Data

What kind of data can be collected for use in a computer system?

Data jenis apakah yang dapat dikumpulkan untuk pemakaiansebuah sistem komputer?

Consider data on:College application form/ Formulir SPMB

Student transcript/ Transkrip mahasiswaRole Playing Game (RPG)

8/10/2019 03 Data Types, Variables & Operators

http://slidepdf.com/reader/full/03-data-types-variables-operators 9/66

Types of Data

We typically want to collect data which may benumeric

characters

Strings

choice (Y/N)

8/10/2019 03 Data Types, Variables & Operators

http://slidepdf.com/reader/full/03-data-types-variables-operators 10/66

Java Data TypesIn order to determine the sizes of storage (boxes)required to hold data, we have to declare the data

types of the identifiers used.Untuk menetukan ukuran penyimpanan (kotak) yangdiperlukan untuk menyimpan data, maka kita perlumendeklarasikan tipe data yang dipakai oleh identifier.Integer data types are used to hold whole numbers

0, -10, 99, 1001The Character data type is used to hold any single

character from the computer keyboard'>', 'h', '8'Floating-point data types can hold numbers with adecimal point and a fractional part.

-2.3, 6.99992, 5e6, 1.5fThe Boolean data type can hold the values true or false

8/10/2019 03 Data Types, Variables & Operators

http://slidepdf.com/reader/full/03-data-types-variables-operators 11/66

Primitive vsReference Data Types

A data type can be a:Primitive type

Reference type (or Class type)

8/10/2019 03 Data Types, Variables & Operators

http://slidepdf.com/reader/full/03-data-types-variables-operators 12/66

Primitive vs Reference Data Types

A Primitive type is one that holds a simple, indecomposable value ,such as:

a single number

a single character

A Reference type is a type for a class :

it can hold objects that have data and methods

8/10/2019 03 Data Types, Variables & Operators

http://slidepdf.com/reader/full/03-data-types-variables-operators 13/66

Java Primitive Data TypesThere are 8 primitive data types in Java

Type name Kind of value Memory used

byte integer 1 byte

short integer 2 bytes

int integer 4 bytes

long integer 8 bytesfloat floating-point number 4 bytes

double floating-point number 8 bytes

char single character 2 bytes

boolean true or false 1 bit

8/10/2019 03 Data Types, Variables & Operators

http://slidepdf.com/reader/full/03-data-types-variables-operators 14/66

Declaring variables

When we want to store some data in a variable,we must first declare that variable.

to prepare memory storage for that data.

Syntax:

Type VariableName;

8/10/2019 03 Data Types, Variables & Operators

http://slidepdf.com/reader/full/03-data-types-variables-operators 15/66

Declaring variables

Examples:

The following statements will declarean integer variable called studentNumber to store a student number:

a double variable to store the score for a student

a character variable to store the lettergrade

public static void main(String[] args){

// declaring variablesint studentNumber;double score;char letterGrade;

8/10/2019 03 Data Types, Variables & Operators

http://slidepdf.com/reader/full/03-data-types-variables-operators 16/66

8/10/2019 03 Data Types, Variables & Operators

http://slidepdf.com/reader/full/03-data-types-variables-operators 17/66

Assignment StatementsExamples:

Setting the student number, score and lettergrade for the variablesdeclared earlier:

public static void main(String[] args){

// declaring variablesint studentNumber;

double score;char letterGrade;

// assigning values to variablesstudentNumber = 100;score = 50.8;letterGrade = 'D';

}

8/10/2019 03 Data Types, Variables & Operators

http://slidepdf.com/reader/full/03-data-types-variables-operators 18/66

Initializing VariablesWe may also initialize variables when declaring them.

Syntax:

Type VariableName = value;

This will set the value of the variable the moment it is declared.

This is to protect against using variables whose values areundetermined.

8/10/2019 03 Data Types, Variables & Operators

http://slidepdf.com/reader/full/03-data-types-variables-operators 19/66

Initializing VariablesExample: the variables are initialized as they are declared:

public static void main(String[] args){

// declaring variablesint studentNumber = 100;double score = 50.8;char letterGrade = 'D';

}

8/10/2019 03 Data Types, Variables & Operators

http://slidepdf.com/reader/full/03-data-types-variables-operators 20/66

Arithmetic Operators

We can use arithmetic operators in our assignment statements.The Java arithmetic operators are:

addition, + (integer and floating-point)

subtraction, - (integer and floating-point)

multiplication, * (integer and floating-point)

division, / (integer and floating-point)

modulus, % (integer division to find remainder)

8/10/2019 03 Data Types, Variables & Operators

http://slidepdf.com/reader/full/03-data-types-variables-operators 21/66

Arithmetic OperatorsExample: using the + operator

public static void main(String[] args){

// declaring two integer variablesint num1 = 5, num2 = 8;

// declaring a variable to store the total

int total;

// performing addition:total = num1 + num2;

// display resultSystem.out.println(“total = “ + total);

}

8/10/2019 03 Data Types, Variables & Operators

http://slidepdf.com/reader/full/03-data-types-variables-operators 22/66

Arithmetic ExpressionsMore examples of expressions:

public static void main(String[] args){// declaring variablesint num1 = 5, num2 = 8;int quotient, remainder;double total, average;

// performing arithmetic:total = num1 + num2;average = total / 2; // floating-point divisionquotient = num1 / num2; //integer divisionremainder = num1 % num2;

// how to display the results?

}

8/10/2019 03 Data Types, Variables & Operators

http://slidepdf.com/reader/full/03-data-types-variables-operators 23/66

Operator Precedence

Operators follow precedence rules :Thus you should use parentheses ( ) where necessary.

Generally according to algebraic rules:

( ) , * , / , % , + , -

8/10/2019 03 Data Types, Variables & Operators

http://slidepdf.com/reader/full/03-data-types-variables-operators 24/66

Operator Precedence

Example:The expressions

3 + 5 * 5 will evaluate to 28

(3 + 5) * 5 will evaluate to 40

8/10/2019 03 Data Types, Variables & Operators

http://slidepdf.com/reader/full/03-data-types-variables-operators 25/66

Assignment Compatibilities

In an assignment statement, you

can assign a value of one typeinto another type:int iVariable = 6;double dblVariable;dblVariable = iVariable; // assigning int to double

8/10/2019 03 Data Types, Variables & Operators

http://slidepdf.com/reader/full/03-data-types-variables-operators 26/66

Assignment Compatibilities

However, you can not directly

assign a double into an intdouble dblVariable = 6.75;int iVariable;iVariable = dblVariable;

// assigning double to intCompiler error! Possible loss of precision

8/10/2019 03 Data Types, Variables & Operators

http://slidepdf.com/reader/full/03-data-types-variables-operators 27/66

Type Casting

Generally, you can only assign a

type to the type appearing furtherdown the list:byte > short > int > long > float > doubleHowever, if you wish to change a double type to an int , youmust use type casting

8/10/2019 03 Data Types, Variables & Operators

http://slidepdf.com/reader/full/03-data-types-variables-operators 28/66

Type Casting: Example

The value of iVariable is now 6The value of dblVariable is truncated and assigned toiVariable .

The value of dblVariable remains 6.75

double dblVariable = 6.75;int iVariable;iVariable = (int) dblVariable;

// assigning double to int by typecasting

8/10/2019 03 Data Types, Variables & Operators

http://slidepdf.com/reader/full/03-data-types-variables-operators 29/66

Sample ProgramLet's have a look at the following program. What does it do?

public class SimpleMaths{

public static void main (String[] args){

int num1 = 5, num2 = 6;int sum, diff, product, quotient, remainder;

sum = num1 + num2;diff = num1 - num2;

product = num1 * num2;quotient = num1 / num2;remainder = num1 % num2;

}

}

8/10/2019 03 Data Types, Variables & Operators

http://slidepdf.com/reader/full/03-data-types-variables-operators 30/66

Displaying outputWe must use display the results obtained

public class SimpleMaths{

public static void main (String[] args){

int num1 = 5, num2 = 6;int sum, diff, product, quotient, remainder;

sum = num1 + num2;diff = num1 - num2;…System.out.println (sum);System.out.println (diff);// etc

}}

displays thevalue stored the variablesum

8/10/2019 03 Data Types, Variables & Operators

http://slidepdf.com/reader/full/03-data-types-variables-operators 31/66

Displaying outputHowever, we should always make our output meaningfuland clear.

public class SimpleMaths{

public static void main (String[] args){

int num1 = 5, num2 = 6;int sum, diff, product, quotient, remainder;sum = num1 + num2;…

System.out.println("The sum is");System.out.println(sum);// etc

}}

8/10/2019 03 Data Types, Variables & Operators

http://slidepdf.com/reader/full/03-data-types-variables-operators 32/66

Displaying outputWe can use the System.out.print() method:

public class SimpleMaths{

public static void main (String [] args){

int num1 = 5, num2 = 6;int sum, diff, product, quotient, remainder;

sum = num1 + num2;…

System.out. print ("The sum is ");System.out.println(sum);// etc

}

}

Displaying output

8/10/2019 03 Data Types, Variables & Operators

http://slidepdf.com/reader/full/03-data-types-variables-operators 33/66

Displaying output

We can combine Strings and data using theconcatenation operator +

public class SimpleMaths{

public static void main (String [] args){

int num1 = 5, num2 = 6;int sum, diff, product, quotient, remainder;sum = num1 + num2;…

System.out.print("The sum is " + sum);

// etc}

}

8/10/2019 03 Data Types, Variables & Operators

http://slidepdf.com/reader/full/03-data-types-variables-operators 34/66

8/10/2019 03 Data Types, Variables & Operators

http://slidepdf.com/reader/full/03-data-types-variables-operators 35/66

Concatenation +

'+' will be used for addition if:

both operands are numeric

System.out.println(8 + 6);System.out.println(17.5 + 4);

System.out.println("8" + 6); System.out.println(8 + "6”) System.out.println("8" + "6”) System.out.println("The answer is " + 14);System.out.println("The answer is " + 8 + 6);

'+' will be used to concatenate if:

if either operand is a String or text

8/10/2019 03 Data Types, Variables & Operators

http://slidepdf.com/reader/full/03-data-types-variables-operators 36/66

Exercise

Write a Java program that sets the values of three integer-valuedassignment scores and then calculates and displays:

the total of the three scores

the average of the three scores

8/10/2019 03 Data Types, Variables & Operators

http://slidepdf.com/reader/full/03-data-types-variables-operators 37/66

ExerciseWhat is wrong with the following program?

public class countAvg{

public static void main (String[] args){

int score1, score2;double average = 0.0;score1 = 56;score2 = 73;average = score1 + score2 / 2System.out.print("The average of ");System.out.print(score1);System.out.print("and");System.out.println(score2);System.out.println("is " + average);

}}

8/10/2019 03 Data Types, Variables & Operators

http://slidepdf.com/reader/full/03-data-types-variables-operators 38/66

The Char data typeAnother primitive data type is char

The char data type can hold values of the following character

literals:the letters of the alphabet, eg.: 'A', 'b'

the digits, eg. : '0' , '3'

other special symbols, eg.: '(', '&', '+'

the null (empty) character: ''

8/10/2019 03 Data Types, Variables & Operators

http://slidepdf.com/reader/full/03-data-types-variables-operators 39/66

8/10/2019 03 Data Types, Variables & Operators

http://slidepdf.com/reader/full/03-data-types-variables-operators 40/66

Escape Sequence

Sometimes it is necessary to represent symbols:which already have special meanings in the Java language, such as ' or"

other characters such as a tab or return.

8/10/2019 03 Data Types, Variables & Operators

http://slidepdf.com/reader/full/03-data-types-variables-operators 41/66

Escape Sequence

The escape sequence character \ is used in this case.'\'' to represent the single quote character

'\"' to represent the double quote character

'\\' to represent a backslash character.

'\t' to represent a tab

'\n' to create a new line

8/10/2019 03 Data Types, Variables & Operators

http://slidepdf.com/reader/full/03-data-types-variables-operators 42/66

Exercise

Write a program that will display thefollowing:

She said "Hello!" to me!

Th S i D T

8/10/2019 03 Data Types, Variables & Operators

http://slidepdf.com/reader/full/03-data-types-variables-operators 43/66

The String Data Type

A String type is an example of a reference data type.A string is defined as a sequence of characters.

Th S i D T

8/10/2019 03 Data Types, Variables & Operators

http://slidepdf.com/reader/full/03-data-types-variables-operators 44/66

The String Data Type

Examples of String literals:" " (space, not the character ' ')

"" (empty String)

"a"

"HELLO"

"This is a String"

"\tThis is also a String\n"

D l i S i

8/10/2019 03 Data Types, Variables & Operators

http://slidepdf.com/reader/full/03-data-types-variables-operators 45/66

Declaring a String

Strings can be used to store names, titles, etc.

We can declare a String data type by giving it a variable name:String name;

We can also initialize the variable upon declaration:String subjectCode = “BIT106”;

E i

8/10/2019 03 Data Types, Variables & Operators

http://slidepdf.com/reader/full/03-data-types-variables-operators 46/66

ExerciseWrite a program to print out the following, using Stringvariables:

Subject code: BIT106 Subject name: Java ProgrammingStudent name: Lee Ah YewAssignment 1 Score (out of 25): 24.0Assignment 2 Score (out of 25): 23.5Exam Raw Score (out of 50) : 48.90

Lee Ah Yew's Total Score for BIT106 (JavaProgramming): 96.40

K b d I t

8/10/2019 03 Data Types, Variables & Operators

http://slidepdf.com/reader/full/03-data-types-variables-operators 47/66

Keyboard Input

Java 5.0 has reasonable facilities for handling keyboard input.

These facilities are provided by the Scanner class in thejava.util package.

A package is a library of classes.

Using the Sc nner Cl ss

8/10/2019 03 Data Types, Variables & Operators

http://slidepdf.com/reader/full/03-data-types-variables-operators 48/66

Using the Scanner Class

Near the beginning of your program, insertimport java.util.*

Create an object of the Scanner classScanner sc = new Scanner (System.in)

Read data (an int or a double , for example)

int n1 = sc.nextInt();

double d1 = sc.nextDouble();

Keyboard Input Demonstration

8/10/2019 03 Data Types, Variables & Operators

http://slidepdf.com/reader/full/03-data-types-variables-operators 49/66

class ScannerDemo

Some Scanner Class Methods

8/10/2019 03 Data Types, Variables & Operators

http://slidepdf.com/reader/full/03-data-types-variables-operators 50/66

syntaxInt_Variable = Object_Name .nextInt();

Double_Variable =Object_Name .nextDouble();

String_Variable = Object_Name .next();

String_Variable = Object_Name .nextLine();

Remember to prompt the user for input, e.g.System.out.print(“Enter an integer: “);

8/10/2019 03 Data Types, Variables & Operators

http://slidepdf.com/reader/full/03-data-types-variables-operators 51/66

Exercise

8/10/2019 03 Data Types, Variables & Operators

http://slidepdf.com/reader/full/03-data-types-variables-operators 52/66

Exercise

Write a program that asks the user to enter the name ofan item, the price and the quantity purchased. The

program must calculate the total price and display thefollowing:

Item Unit Qty Total

widget RM5.30 10 RM53.00

Pseudocode

8/10/2019 03 Data Types, Variables & Operators

http://slidepdf.com/reader/full/03-data-types-variables-operators 53/66

PseudocodeWhen we want to write a computer program, we shouldalways:

ThinkPlan

Code

We can write out our planning using pseudocode – writingthe steps in simple English and not strict programminglanguage syntax.

Documentation

8/10/2019 03 Data Types, Variables & Operators

http://slidepdf.com/reader/full/03-data-types-variables-operators 54/66

Documentation

A computer programmer generally spends more time reading andmodifying programs than writing new ones.

It is therefore important that your programs are documented:

clearly

neatly

meaningfully

Documentation

8/10/2019 03 Data Types, Variables & Operators

http://slidepdf.com/reader/full/03-data-types-variables-operators 55/66

Documentation

You should always precede your program with:

Your name

The date

The purpose of the program

Comments

8/10/2019 03 Data Types, Variables & Operators

http://slidepdf.com/reader/full/03-data-types-variables-operators 56/66

Comments

Comments are used to:Insert documentation

Clarify parts of code which may be complex.

Comments are ignored by the compiler but are useful to humans.

Comments

8/10/2019 03 Data Types, Variables & Operators

http://slidepdf.com/reader/full/03-data-types-variables-operators 57/66

Comments

The symbols // are used to indicate that the rest of a line arecomments.If comments span more than one line, the symbols /* and */ can beused, eg.:/* this is the beginning of the documentedcomments and it only ends here */

Variable names

8/10/2019 03 Data Types, Variables & Operators

http://slidepdf.com/reader/full/03-data-types-variables-operators 58/66

Variable names

Variable names shoud:follow the Java rules

be meaningful

For example,name , score, totalBeforeTaxes

You should almost never use names likea, b, c

Variable names

8/10/2019 03 Data Types, Variables & Operators

http://slidepdf.com/reader/full/03-data-types-variables-operators 59/66

Variable names

By convention:variable names start with a lowercase letter

class names start with an uppercase letter, eg. String, Scanner

8/10/2019 03 Data Types, Variables & Operators

http://slidepdf.com/reader/full/03-data-types-variables-operators 60/66

8/10/2019 03 Data Types, Variables & Operators

http://slidepdf.com/reader/full/03-data-types-variables-operators 61/66

Exercise

8/10/2019 03 Data Types, Variables & Operators

http://slidepdf.com/reader/full/03-data-types-variables-operators 62/66

Exercise

Write a program that asks the user to enter the length and width ofa rectangle and then display:

the area of the rectangle

the perimeter of the rectangle

The Math class: We can use pre-defined methods fromthe Math class to perform calculations.

8/10/2019 03 Data Types, Variables & Operators

http://slidepdf.com/reader/full/03-data-types-variables-operators 63/66

Exercise

8/10/2019 03 Data Types, Variables & Operators

http://slidepdf.com/reader/full/03-data-types-variables-operators 64/66

Write a Java program that asks the user to enter twonumbers, then:

find the absolute value of each of the numbers;determine which absolute value is largerfind the square root of the larger of the two absolute values

Sample run:Enter first number: -36Enter second number: 5

The absolute values of the two numbers are 36 and 5The larger absolute value is 36The square root of 36 is 6.0

Catch-up Exercise

8/10/2019 03 Data Types, Variables & Operators

http://slidepdf.com/reader/full/03-data-types-variables-operators 65/66

p

Write a Java program that asks the user to enter a double number.Then display:

the square root of the number.

Now test the program with the values:39.4

-30

We want to be able to make sure that the user cannot enternegative values!

Tugas Rumah

8/10/2019 03 Data Types, Variables & Operators

http://slidepdf.com/reader/full/03-data-types-variables-operators 66/66

g

NPM GanjilBuat program untuk menghitung volume balok.

NPM GenapBuat program untuk menghitung volume bola.

Input data dilakukan oleh user! Bukan programmer! Gunakan classScanner.

Buat flowchart-nya terlebih dulu.

Dikumpulkan via email