Top Banner
Introduction to Introduction to JAVA JAVA Programming Basics Programming Basics
97

Introduction to JAVA Programming Basics PROGRAMMING STEPS ANALISA MASALAHNYA INPUT-NYA APA SAJA? ALGORITMA PROSESNYA BAGAIMANA? OUTPUT-NYA APA?

Dec 11, 2015

Download

Documents

Frankie Deaton
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Introduction to JAVA Programming Basics PROGRAMMING STEPS  ANALISA MASALAHNYA  INPUT-NYA APA SAJA?  ALGORITMA PROSESNYA BAGAIMANA?  OUTPUT-NYA APA?

Introduction to JAVAIntroduction to JAVAProgramming BasicsProgramming Basics

Page 2: Introduction to JAVA Programming Basics PROGRAMMING STEPS  ANALISA MASALAHNYA  INPUT-NYA APA SAJA?  ALGORITMA PROSESNYA BAGAIMANA?  OUTPUT-NYA APA?

PROGRAMMING STEPSPROGRAMMING STEPS

ANALISA MASALAHNYAANALISA MASALAHNYA INPUT-NYA APA SAJA?INPUT-NYA APA SAJA? ALGORITMA PROSESNYA BAGAIMANA?ALGORITMA PROSESNYA BAGAIMANA? OUTPUT-NYA APA?OUTPUT-NYA APA?

KETIK SOURCE CODE-NYAKETIK SOURCE CODE-NYA HEADER FILES HEADER FILES import < library >import < library > GLOBAL SECTIONS GLOBAL SECTIONS VARIABEL GLOBAL, FUNGSI BANTU VARIABEL GLOBAL, FUNGSI BANTU MAIN SECTIONS MAIN SECTIONS VARIABEL LOKAL, INPUT, PROSES, VARIABEL LOKAL, INPUT, PROSES,

OUTPUTOUTPUT

COMPILE & RUN PROGRAMNYA COMPILE & RUN PROGRAMNYA ADA ERROR ? ADA ERROR ? TES HASILNYA TES HASILNYA SUDAH BENAR ? SUDAH BENAR ? BUAT ARSIP/ DOKUMENTASINYABUAT ARSIP/ DOKUMENTASINYA

Page 3: Introduction to JAVA Programming Basics PROGRAMMING STEPS  ANALISA MASALAHNYA  INPUT-NYA APA SAJA?  ALGORITMA PROSESNYA BAGAIMANA?  OUTPUT-NYA APA?

Computers and ProgrammingComputers and Programming

A computer is a machine that can process data A computer is a machine that can process data by carrying out complex calculations quickly.by carrying out complex calculations quickly.

A A programprogram is a set of instructions for the is a set of instructions for the computer to execute.computer to execute.

A program can be A program can be high-levelhigh-level (easy for humans (easy for humans to understand) or to understand) or low-levellow-level (easy for the (easy for the computer to understand).computer to understand).

In any case, programs have to be written In any case, programs have to be written following a strict language syntax.following a strict language syntax.

Page 4: Introduction to JAVA Programming Basics PROGRAMMING STEPS  ANALISA MASALAHNYA  INPUT-NYA APA SAJA?  ALGORITMA PROSESNYA BAGAIMANA?  OUTPUT-NYA APA?

Running a ProgramRunning a Program

Typically, a program source code has to be Typically, a program source code has to be compiledcompiled into machine language before it can be into machine language before it can be understood by a computer.understood by a computer.

programmer

void test(){ println(“Hi”);}

source code (high level)

compiler

machine language

object code (low level)

writes

executed by

computer

Hi

Page 5: Introduction to JAVA Programming Basics PROGRAMMING STEPS  ANALISA MASALAHNYA  INPUT-NYA APA SAJA?  ALGORITMA PROSESNYA BAGAIMANA?  OUTPUT-NYA APA?

PortabilityPortability

Different makes of computersDifferent makes of computers speak different “languages” (machine language)speak different “languages” (machine language) use different compilers. use different compilers.

This means that object code produced by one This means that object code produced by one compiler may not work on another computer of a compiler may not work on another computer of a different make.different make.

Thus the program is not Thus the program is not portableportable.. Java is Java is portableportable because it works in a different because it works in a different

way.way.

Page 6: Introduction to JAVA Programming Basics PROGRAMMING STEPS  ANALISA MASALAHNYA  INPUT-NYA APA SAJA?  ALGORITMA PROSESNYA BAGAIMANA?  OUTPUT-NYA APA?

History of JavaHistory of Java

The Java programming language was The Java programming language was developed at Sun Microsystemsdeveloped at Sun Microsystems

It is meant to be a It is meant to be a portableportable language that language that allows the same program code to be run allows the same program code to be run on different computer makes.on different computer makes.

Java program code is translated into Java program code is translated into byte-byte-codecode that is interpreted into machine that is interpreted into machine language that the computer can language that the computer can understand.understand.

Page 7: Introduction to JAVA Programming Basics PROGRAMMING STEPS  ANALISA MASALAHNYA  INPUT-NYA APA SAJA?  ALGORITMA PROSESNYA BAGAIMANA?  OUTPUT-NYA APA?

Java Byte-CodeJava Byte-Code

Java source code is compiled by the Java Java source code is compiled by the Java compiler into compiler into byte-codebyte-code..

Byte-code is the machine language for a ‘typical’ Byte-code is the machine language for a ‘typical’ computer.computer.

This ‘typical’ computer is known as the This ‘typical’ computer is known as the Java Java Virtual MachineVirtual Machine..

A byte-code A byte-code interpreter interpreter will translate byte-code will translate byte-code into object code for the particular machine.into object code for the particular machine.

The byte-code is thus The byte-code is thus portableportable because an because an interpreter is simpler to write than a compiler.interpreter is simpler to write than a compiler.

Page 8: Introduction to JAVA Programming Basics PROGRAMMING STEPS  ANALISA MASALAHNYA  INPUT-NYA APA SAJA?  ALGORITMA PROSESNYA BAGAIMANA?  OUTPUT-NYA APA?

Running a Java ProgramRunning a Java Program

programmer

public void test() { System.out.println(“Hi”);} Java source code (high level)

Javacompiler

Machine language

object code (low level)

writes

executed by

computer

HiByte-codeinterpreter

Java byte-code

Extra step thatallows forportability

Page 9: Introduction to JAVA Programming Basics PROGRAMMING STEPS  ANALISA MASALAHNYA  INPUT-NYA APA SAJA?  ALGORITMA PROSESNYA BAGAIMANA?  OUTPUT-NYA APA?

Types of Java ProgramsTypes of Java Programs

Console Applications:Console Applications: Simple text input / outputSimple text input / output This is what we will be doing for most of this This is what we will be doing for most of this

course as we are learning how to program.course as we are learning how to program.public class ConsoleApp{

public static void main(String[] args){

System.out.println("Hello World!");}

}

Page 10: Introduction to JAVA Programming Basics PROGRAMMING STEPS  ANALISA MASALAHNYA  INPUT-NYA APA SAJA?  ALGORITMA PROSESNYA BAGAIMANA?  OUTPUT-NYA APA?

Types of Java ProgramsTypes of Java Programs

GUI Applications:GUI Applications: Using the Java Swing libraryUsing the Java Swing library

import javax.swing.*; public class GuiApp{

public static void main(String[] args){

JOptionPane.showMessageDialog(null, "Hello World!","GUI Application", JOptionPane.INFORMATION_MESSAGE);System.exit(0);

}}

Page 11: Introduction to JAVA Programming Basics PROGRAMMING STEPS  ANALISA MASALAHNYA  INPUT-NYA APA SAJA?  ALGORITMA PROSESNYA BAGAIMANA?  OUTPUT-NYA APA?

Types of Java ProgramsTypes of Java Programs

Applets Applets To be viewed using a internet browserTo be viewed using a internet browser

import java.applet.*;import java.awt.*; public class AppletEg extends Applet{

public void paint(Graphics g){

g.drawString("Hello World!", 20, 20);}

}___________________________________________________<applet code="AppletEg.class" width=200 height=40></applet>

Page 12: Introduction to JAVA Programming Basics PROGRAMMING STEPS  ANALISA MASALAHNYA  INPUT-NYA APA SAJA?  ALGORITMA PROSESNYA BAGAIMANA?  OUTPUT-NYA APA?

Sample Java ProgramSample Java Programpublic class CalcCirclepublic class CalcCircle{{ public static void main(String[ ] args)public static void main(String[ ] args) {{

int radius;int radius; // radius - variable// radius - variablefinal double PI = 3.14159;final double PI = 3.14159; // PI - constants// PI - constants

  radius = 10;radius = 10;double area = PI * radius * radius;double area = PI * radius * radius;double circumference = 2 * PI * radius;double circumference = 2 * PI * radius;

  System.out.println(”For a circle with radius ” + radius + ”,”);System.out.println(”For a circle with radius ” + radius + ”,”);System.out.print(”The circumference is ” + circumference);System.out.print(”The circumference is ” + circumference);System.out.println(” and the area is ” + area);System.out.println(” and the area is ” + area);

}}} }

Page 13: Introduction to JAVA Programming Basics PROGRAMMING STEPS  ANALISA MASALAHNYA  INPUT-NYA APA SAJA?  ALGORITMA PROSESNYA BAGAIMANA?  OUTPUT-NYA APA?

Elements of a Java ProgramElements of a Java Program

A Java Program is made up of:A Java Program is made up of: Identifiers:Identifiers:

variablesvariables constantsconstants

Literal valuesLiteral values Data typesData types OperatorsOperators ExpressionsExpressions

Page 14: Introduction to JAVA Programming Basics PROGRAMMING STEPS  ANALISA MASALAHNYA  INPUT-NYA APA SAJA?  ALGORITMA PROSESNYA BAGAIMANA?  OUTPUT-NYA APA?

Identifiers/ PengenalIdentifiers/ Pengenal

The identifiers in the previous program The identifiers in the previous program consist of:consist of:

public class CalcCircle{ public static void main(String[] args) {

int radius; // radius - variablefinal double PI = 3.14159; // PI - constants

 …

}}

identifier indicating name of the program(class name)

identifier untuk menyimpan nilai radius(variable)

identifier untuk menyimpan nilai tetap PI (constant)

Page 15: Introduction to JAVA Programming Basics PROGRAMMING STEPS  ANALISA MASALAHNYA  INPUT-NYA APA SAJA?  ALGORITMA PROSESNYA BAGAIMANA?  OUTPUT-NYA APA?

Data Types/ Tipe DataData Types/ Tipe Data

Data types indicate the type of storage Data types indicate the type of storage required.required.

public class CalcCircle{ public static void main(String[ ] args) {

int radius; // radius - variablefinal double PI = 3.14159; // PI - constants

 …

}}

radius adalah sebuah nilai integer (int)

PI adalah sebuah nilai floating-point (double)

Page 16: Introduction to JAVA Programming Basics PROGRAMMING STEPS  ANALISA MASALAHNYA  INPUT-NYA APA SAJA?  ALGORITMA PROSESNYA BAGAIMANA?  OUTPUT-NYA APA?

Literal valuesLiteral values

Literals are the actual values stored in Literals are the actual values stored in variables or used in calculations.variables or used in calculations.

public class CalcCircle{ public static void main(String[ ] args) {

…radius = 10;…

}}

the variable radius stores the value 10

Page 17: Introduction to JAVA Programming Basics PROGRAMMING STEPS  ANALISA MASALAHNYA  INPUT-NYA APA SAJA?  ALGORITMA PROSESNYA BAGAIMANA?  OUTPUT-NYA APA?

Operators and ExpressionsOperators and Expressions

Operators allow us to perform some calculations Operators allow us to perform some calculations on the data by forming expressions.on the data by forming expressions.

public class CalcCircle{ public static void main(String[ ] args) {

…double area = PI * radius * radius;double circumference = 2 * PI * radius;…

}}

Operator perkalian (*) dipakaiUntuk menghitung luas bidang

Sebuah ekspresi yangmenggunakanoperators dan operands

Page 18: Introduction to JAVA Programming Basics PROGRAMMING STEPS  ANALISA MASALAHNYA  INPUT-NYA APA SAJA?  ALGORITMA PROSESNYA BAGAIMANA?  OUTPUT-NYA APA?

Java Program StructureJava Program Structure For the next few weeks, our Java programs For the next few weeks, our Java programs

will have the following structure:will have the following structure:

public class CalcCircle{ public static void main(String[ ] args) {

// This section consists of // program code consisting of // of Java statements //

}}

Program berupa definisi class. Gunakan nama class yang sama dengan nama file-nya.Misal CalcCircle.java

Program harus memiliki methodmain sebagai titik awal eksekusiprogram.

Kurung kurawal menunjukkan awal dan akhir.Gunakan indentasi supaya jelas dibaca.

Page 19: Introduction to JAVA Programming Basics PROGRAMMING STEPS  ANALISA MASALAHNYA  INPUT-NYA APA SAJA?  ALGORITMA PROSESNYA BAGAIMANA?  OUTPUT-NYA APA?

Displaying OutputDisplaying Output For console applications, we use the For console applications, we use the

System.out object to display output.System.out object to display output.

public class CalcCircle{ public static void main(String[ ] args) {

… System.out.println(”For a circle with radius ” + radius + ”,”);System.out.print(”The circumference is ” + circumference);System.out.println(” and the area is ” + area);

}}

Teks dan data diantara tanda petik akan ditampilkan di layar monitor.

Page 20: Introduction to JAVA Programming Basics PROGRAMMING STEPS  ANALISA MASALAHNYA  INPUT-NYA APA SAJA?  ALGORITMA PROSESNYA BAGAIMANA?  OUTPUT-NYA APA?

Compiling and RunningCompiling and Running

The preceding source code must be saved as The preceding source code must be saved as CalcCircle.javaCalcCircle.java

You must then use the Java Development Kit You must then use the Java Development Kit (JDK) to compile the program using the (JDK) to compile the program using the commandcommandjavac CalcCircle.javajavac CalcCircle.java

The byte-code file The byte-code file CalcCircle.classCalcCircle.class will be will be created by the compiler if there are no errors.created by the compiler if there are no errors.

To run the program, use the commandTo run the program, use the commandjava CalcCirclejava CalcCircle

Page 21: Introduction to JAVA Programming Basics PROGRAMMING STEPS  ANALISA MASALAHNYA  INPUT-NYA APA SAJA?  ALGORITMA PROSESNYA BAGAIMANA?  OUTPUT-NYA APA?

Compiling and RunnngCompiling and Runnng

Buttons to compile andrun the program

Page 22: Introduction to JAVA Programming Basics PROGRAMMING STEPS  ANALISA MASALAHNYA  INPUT-NYA APA SAJA?  ALGORITMA PROSESNYA BAGAIMANA?  OUTPUT-NYA APA?

Anatomy of a Java ClassAnatomy of a Java Class

A Java console application must consist of one A Java console application must consist of one class that has the following structure: class that has the following structure:

/* This is a sample program only. Written by: Date: */public class SampleProgram{

public static void main(String [] args){

int num1 = 5; // num stores 5System.out.print("num1 has value ");

System.out.println(num1);}

}

class header

mainmethod

Page 23: Introduction to JAVA Programming Basics PROGRAMMING STEPS  ANALISA MASALAHNYA  INPUT-NYA APA SAJA?  ALGORITMA PROSESNYA BAGAIMANA?  OUTPUT-NYA APA?

Anatomy of a Java ClassAnatomy of a Java Class

A Java console application must consist of one A Java console application must consist of one class that has the following structure: class that has the following structure:

/* This is a sample program only. Written by: Date: */public class SampleProgram{

public static void main(String [] args){

int num1 = 5; // num stores 5System.out.print("num1 has value ");

System.out.println(num1);}

}

multi-line comments

in-linecomments

name of the class

statementsto be executed

Page 24: Introduction to JAVA Programming Basics PROGRAMMING STEPS  ANALISA MASALAHNYA  INPUT-NYA APA SAJA?  ALGORITMA PROSESNYA BAGAIMANA?  OUTPUT-NYA APA?

What is the result of execution?What is the result of execution?

public classpublic class CalcCircle CalcCircle{{ public static void main(String[ ] args)public static void main(String[ ] args) {{

intint radius; radius; // radius - variable// radius - variablefinalfinal doubledouble PI = 3.14159; PI = 3.14159; // PI - constants// PI - constants

  radius = 10;radius = 10;doubledouble area = PI * radius * radius; area = PI * radius * radius;doubledouble circumference = 2 * PI * radius; circumference = 2 * PI * radius;

  System.out.println(”For a circle with radius ” + radius + ”,”);System.out.println(”For a circle with radius ” + radius + ”,”);System.out.print(”The circumference is ” + circumference);System.out.print(”The circumference is ” + circumference);System.out.println(” and the area is ” + area);System.out.println(” and the area is ” + area);

}}}}

Page 25: Introduction to JAVA Programming Basics PROGRAMMING STEPS  ANALISA MASALAHNYA  INPUT-NYA APA SAJA?  ALGORITMA PROSESNYA BAGAIMANA?  OUTPUT-NYA APA?

Displaying outputDisplaying output

There are some predefined classes in Java that There are some predefined classes in Java that we can use for basic tasks such as:we can use for basic tasks such as: reading inputreading input displaying outputdisplaying output

We use the We use the SystemSystem classclass to display output to to display output to the screen for console applications.the screen for console applications.

System.out System.out is an is an objectobject that provides methods that provides methods for displaying strings of characters to the for displaying strings of characters to the console screen.console screen. The The methodsmethods we can use are we can use are printprint and and printlnprintln..

Page 26: Introduction to JAVA Programming Basics PROGRAMMING STEPS  ANALISA MASALAHNYA  INPUT-NYA APA SAJA?  ALGORITMA PROSESNYA BAGAIMANA?  OUTPUT-NYA APA?

ExampleExample

Write a program that prints two lines: Write a program that prints two lines: I love Java ProgrammingI love Java Programming

It is fun!It is fun!

public class PrintTwoLines{ public static void main(String[] args) { System.out.println("I love Java Programming"); System.out.println("It is fun"); }}

Page 27: Introduction to JAVA Programming Basics PROGRAMMING STEPS  ANALISA MASALAHNYA  INPUT-NYA APA SAJA?  ALGORITMA PROSESNYA BAGAIMANA?  OUTPUT-NYA APA?

Print vs PrintlnPrint vs Println

What if you use What if you use System.out.print()System.out.print() instead?instead?

System.out.println() advances the cursor System.out.println() advances the cursor to the next line after displaying the to the next line after displaying the required output. required output.

If you use System.out.print(), you might If you use System.out.print(), you might need to add spaces to format your output need to add spaces to format your output clearly.clearly.

Page 28: Introduction to JAVA Programming Basics PROGRAMMING STEPS  ANALISA MASALAHNYA  INPUT-NYA APA SAJA?  ALGORITMA PROSESNYA BAGAIMANA?  OUTPUT-NYA APA?

ExamplesExamples

Code Fragment Output Displayed

System.out.println("First line");System.out.println("Second line");

First lineSecond line

System.out.print("First line");System.out.print("Second line");

First lineSecond line

Page 29: Introduction to JAVA Programming Basics PROGRAMMING STEPS  ANALISA MASALAHNYA  INPUT-NYA APA SAJA?  ALGORITMA PROSESNYA BAGAIMANA?  OUTPUT-NYA APA?

ExerciseExercise

Write a Java program that displays your Write a Java program that displays your name and your studentID.name and your studentID.

// Sandy Lim// Lecture 1// Printing name and student IDpublic class Information{

public static void main (String[] args){

// your code here}

}

Page 30: Introduction to JAVA Programming Basics PROGRAMMING STEPS  ANALISA MASALAHNYA  INPUT-NYA APA SAJA?  ALGORITMA PROSESNYA BAGAIMANA?  OUTPUT-NYA APA?

ExerciseExercise

Write a Java program that prints out to Write a Java program that prints out to the screen the following tree:the screen the following tree: ** ****** ************************************** **********

// Sandy Lim// Lecture 1// Printing a tree using *public class tree{

public static void main (String[] args){

// your code here}

}

Page 31: Introduction to JAVA Programming Basics PROGRAMMING STEPS  ANALISA MASALAHNYA  INPUT-NYA APA SAJA?  ALGORITMA PROSESNYA BAGAIMANA?  OUTPUT-NYA APA?

RemindersReminders

Get your computer accounts before next Get your computer accounts before next week's tutorial so that you can start week's tutorial so that you can start programming ASAP.programming ASAP.

Download JCreatorLE and J2SDK1.5.0, Download JCreatorLE and J2SDK1.5.0, you can access both through the JCreator you can access both through the JCreator (3.50LE) website: (3.50LE) website: http://www.jcreator.com/download.htmhttp://www.jcreator.com/download.htm

Page 32: Introduction to JAVA Programming Basics PROGRAMMING STEPS  ANALISA MASALAHNYA  INPUT-NYA APA SAJA?  ALGORITMA PROSESNYA BAGAIMANA?  OUTPUT-NYA APA?

Data Types, Variables Data Types, Variables & Operators& Operators

Page 33: Introduction to JAVA Programming Basics PROGRAMMING STEPS  ANALISA MASALAHNYA  INPUT-NYA APA SAJA?  ALGORITMA PROSESNYA BAGAIMANA?  OUTPUT-NYA APA?

Memory and DataMemory and Data Salah satu komponen penting komputer Salah satu komponen penting komputer

adalah adalah memorymemory.. Memori komputer menyimpan:Memori komputer menyimpan:

data yang akan diprosesdata yang akan diproses data hasil dari sebuah prosesdata hasil dari sebuah proses

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

Ukuran kotak akan tergantung pada tipe Ukuran kotak akan tergantung pada tipe data yang dipakai.data yang dipakai.

Page 34: Introduction to JAVA Programming Basics PROGRAMMING STEPS  ANALISA MASALAHNYA  INPUT-NYA APA SAJA?  ALGORITMA PROSESNYA BAGAIMANA?  OUTPUT-NYA APA?

IdentifiersIdentifiers

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

Nama itulah yang dikenal sebagai Nama itulah yang dikenal sebagai namanama variabelvariabel, atau , atau identifiersidentifiers..

Data asli adalah Data asli adalah nilainilai literalliteral dari identifier. dari identifier.

subject

BIT106 value of subject

identifier / variable name

The box is identified assubject and it stores the value “BIT106”

Page 35: Introduction to JAVA Programming Basics PROGRAMMING STEPS  ANALISA MASALAHNYA  INPUT-NYA APA SAJA?  ALGORITMA PROSESNYA BAGAIMANA?  OUTPUT-NYA APA?

Java Spelling RulesJava Spelling Rules

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

Letters/ huruf (A – Z, a – z) Letters/ huruf (A – Z, a – z) Digits/ angka (0 to 9) Digits/ angka (0 to 9) the characters/ karakter _ and $the characters/ karakter _ and $

The first character cannot be a digit.The first character cannot be a digit. Karakter pertama tidak boleh sebuah Karakter pertama tidak boleh sebuah

angka.angka.

Page 36: Introduction to JAVA Programming Basics PROGRAMMING STEPS  ANALISA MASALAHNYA  INPUT-NYA APA SAJA?  ALGORITMA PROSESNYA BAGAIMANA?  OUTPUT-NYA APA?

Identifier RulesIdentifier Rules

A single identifier must be one word only A single identifier must be one word only (no spaces) of any length.(no spaces) of any length.

Sebuah identifier harus berupa satu kata Sebuah identifier harus berupa satu kata (tanpa spasi) dengan panjang berapapun.(tanpa spasi) dengan panjang berapapun.

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

These are words which have a special meaning These are words which have a special meaning in Javain Java

Kata-kata yang telah memiliki makna khusus Kata-kata yang telah memiliki makna khusus dalam bahasa Javadalam bahasa Java

Page 37: Introduction to JAVA Programming Basics PROGRAMMING STEPS  ANALISA MASALAHNYA  INPUT-NYA APA SAJA?  ALGORITMA PROSESNYA BAGAIMANA?  OUTPUT-NYA APA?

ExamplesExamples Examples of Examples of identifiersidentifiers

num1num1 num2num2 first_namefirst_name lastNamelastNamenumberOfStudentsnumberOfStudents accountNumberaccountNumbermyProgrammyProgram MYPROGRAMMYPROGRAM

Examples of Examples of reservedreserved words wordspublicpublic ifif intint doubledouble

see Appendix 1 in the text book for others.see Appendix 1 in the text book for others. IllegalIllegal identifiers identifiers

3rdValue3rdValue my programmy program this&that this&that

Page 38: Introduction to JAVA Programming Basics PROGRAMMING STEPS  ANALISA MASALAHNYA  INPUT-NYA APA SAJA?  ALGORITMA PROSESNYA BAGAIMANA?  OUTPUT-NYA APA?

ExerciseExercise

Which of the following are Which of the following are validvalid identifier names? identifier names? my_granny’s_namemy_granny’s_name joesCarjoesCar integerinteger 2ndNum2ndNum Child3Child3 doubledouble third valuethird value mid2charsmid2chars PUBLICPUBLIC

Page 39: Introduction to JAVA Programming Basics PROGRAMMING STEPS  ANALISA MASALAHNYA  INPUT-NYA APA SAJA?  ALGORITMA PROSESNYA BAGAIMANA?  OUTPUT-NYA APA?

Types of DataTypes of Data

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

Data jenis apakah yang dapat dikumpulkan Data jenis apakah yang dapat dikumpulkan untuk pemakaian sebuah sistem komputer?untuk pemakaian sebuah sistem komputer?

Consider data on:Consider data on: College application form/ College application form/ Formulir SPMBFormulir SPMB Student transcript/ Student transcript/ Transkrip mahasiswaTranskrip mahasiswa Role Playing Game (RPG)Role Playing Game (RPG)

Page 40: Introduction to JAVA Programming Basics PROGRAMMING STEPS  ANALISA MASALAHNYA  INPUT-NYA APA SAJA?  ALGORITMA PROSESNYA BAGAIMANA?  OUTPUT-NYA APA?

Types of DataTypes of Data

We typically want to collect data which may beWe typically want to collect data which may be numericnumeric characterscharacters StringsStrings choice (Y/N)choice (Y/N)

Page 41: Introduction to JAVA Programming Basics PROGRAMMING STEPS  ANALISA MASALAHNYA  INPUT-NYA APA SAJA?  ALGORITMA PROSESNYA BAGAIMANA?  OUTPUT-NYA APA?

Java Data TypesJava Data Types In order to determine the sizes of storage (boxes) required to In order to determine the sizes of storage (boxes) required to

hold data, we have to hold data, we have to declaredeclare the the data typesdata types of the of the identifiers used.identifiers used.

Untuk menetukan ukuran penyimpanan (kotak) yang Untuk menetukan ukuran penyimpanan (kotak) yang diperlukan untuk menyimpan data, maka kita perlu diperlukan untuk menyimpan data, maka kita perlu mendeklarasikan tipe data yang dipakai oleh identifier.mendeklarasikan tipe data yang dipakai oleh identifier.

Integer data types are used to hold whole Integer data types are used to hold whole numbersnumbers 0, -10, 99, 10010, -10, 99, 1001

The Character data type is used to hold any The Character data type is used to hold any single charactersingle character from the computer keyboardfrom the computer keyboard '>', 'h', '8''>', 'h', '8'

Floating-point data types can hold numbers with a Floating-point data types can hold numbers with a decimaldecimal point and a point and a fractionalfractional part. part. -2.3, 6.99992, 5e6, 1.5f-2.3, 6.99992, 5e6, 1.5f

The Boolean data type can hold the values The Boolean data type can hold the values truetrue or or falsefalse..

Page 42: Introduction to JAVA Programming Basics PROGRAMMING STEPS  ANALISA MASALAHNYA  INPUT-NYA APA SAJA?  ALGORITMA PROSESNYA BAGAIMANA?  OUTPUT-NYA APA?

Primitive vs Primitive vs Reference Data TypesReference Data Types

A data type can be a:A data type can be a: Primitive typePrimitive type Reference type (or Class type)Reference type (or Class type)

Page 43: Introduction to JAVA Programming Basics PROGRAMMING STEPS  ANALISA MASALAHNYA  INPUT-NYA APA SAJA?  ALGORITMA PROSESNYA BAGAIMANA?  OUTPUT-NYA APA?

Primitive vs Reference Data Primitive vs Reference Data TypesTypes

A Primitive type is one that holds a A Primitive type is one that holds a simple, simple, indecomposable valueindecomposable value, such as:, such as: a single numbera single number a single charactera single character

A Reference type is a type for a A Reference type is a type for a classclass:: it can hold it can hold objectsobjects that have that have datadata and and

methodsmethods

Page 44: Introduction to JAVA Programming Basics PROGRAMMING STEPS  ANALISA MASALAHNYA  INPUT-NYA APA SAJA?  ALGORITMA PROSESNYA BAGAIMANA?  OUTPUT-NYA APA?

Java Primitive Data TypesJava Primitive Data Types

There are 8 There are 8 primitiveprimitive data types in Java data types in JavaType nameType name Kind of valueKind of value Memory usedMemory used

bytebyte integerinteger 1 byte1 byte

shortshort integerinteger 2 bytes2 bytes

intint integerinteger 4 bytes4 bytes

longlong integerinteger 8 bytes8 bytes

floatfloat floating-point numberfloating-point number 4 bytes4 bytes

double double floating-point numberfloating-point number 8 bytes8 bytes

charchar single charactersingle character 2 bytes2 bytes

booleanboolean true or falsetrue or false 1 bit1 bit

Page 45: Introduction to JAVA Programming Basics PROGRAMMING STEPS  ANALISA MASALAHNYA  INPUT-NYA APA SAJA?  ALGORITMA PROSESNYA BAGAIMANA?  OUTPUT-NYA APA?

Declaring variablesDeclaring variables

When we want to store some data in a When we want to store some data in a variable,variable, we must first we must first declaredeclare that variable. that variable. to prepare to prepare memory storagememory storage for that data. for that data.

Syntax:Syntax:Type VariableName;Type VariableName;

Page 46: Introduction to JAVA Programming Basics PROGRAMMING STEPS  ANALISA MASALAHNYA  INPUT-NYA APA SAJA?  ALGORITMA PROSESNYA BAGAIMANA?  OUTPUT-NYA APA?

Declaring variablesDeclaring variables

Examples:Examples: The following statements will declareThe following statements will declare

an integer variable called studentNumber to store an integer variable called studentNumber to store a student number: a student number:

a double variable to store the score for a studenta double variable to store the score for a student a character variable to store the lettergradea character variable to store the lettergrade

public static void main(String[] args){

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

Page 47: Introduction to JAVA Programming Basics PROGRAMMING STEPS  ANALISA MASALAHNYA  INPUT-NYA APA SAJA?  ALGORITMA PROSESNYA BAGAIMANA?  OUTPUT-NYA APA?

Assignment StatementsAssignment Statements Once we have declared our variables, we can Once we have declared our variables, we can

use the variables to hold data.use the variables to hold data. This is done by This is done by assigningassigning literal values to the literal values to the

variables.variables. Syntax (for primitive types):Syntax (for primitive types):

VariableName = value;VariableName = value; This means that the value on the right hand side is This means that the value on the right hand side is

evaluated and the variable on the left hand side is evaluated and the variable on the left hand side is set to this value.set to this value.

Masukkan Masukkan valuevalue ke ke VariableNameVariableName

Page 48: Introduction to JAVA Programming Basics PROGRAMMING STEPS  ANALISA MASALAHNYA  INPUT-NYA APA SAJA?  ALGORITMA PROSESNYA BAGAIMANA?  OUTPUT-NYA APA?

Assignment StatementsAssignment Statements Examples:Examples:

Setting the student number, score and lettergrade for the Setting the student number, score and lettergrade for the variables declared earlier:variables declared earlier:

public static void main(String[] args){

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

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

}

Page 49: Introduction to JAVA Programming Basics PROGRAMMING STEPS  ANALISA MASALAHNYA  INPUT-NYA APA SAJA?  ALGORITMA PROSESNYA BAGAIMANA?  OUTPUT-NYA APA?

Initializing VariablesInitializing Variables We may also We may also initialize initialize variables when declaring variables when declaring

them.them. Syntax:Syntax:

Type VariableName = value;Type VariableName = value;

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

This is to protect against using variables whose This is to protect against using variables whose values are undetermined.values are undetermined.

Page 50: Introduction to JAVA Programming Basics PROGRAMMING STEPS  ANALISA MASALAHNYA  INPUT-NYA APA SAJA?  ALGORITMA PROSESNYA BAGAIMANA?  OUTPUT-NYA APA?

Initializing VariablesInitializing Variables Example: the variables are initialized as they are Example: the variables are initialized as they are

declared:declared:

public static void main(String[] args){

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

}

Page 51: Introduction to JAVA Programming Basics PROGRAMMING STEPS  ANALISA MASALAHNYA  INPUT-NYA APA SAJA?  ALGORITMA PROSESNYA BAGAIMANA?  OUTPUT-NYA APA?

Arithmetic OperatorsArithmetic Operators

We can use arithmetic operators in our We can use arithmetic operators in our assignment statements.assignment statements.

The Java arithmetic operators are:The Java arithmetic operators are: addition, +addition, + (integer and floating-point)(integer and floating-point) subtraction, -subtraction, - (integer and floating-point)(integer and floating-point) multiplication, * multiplication, * (integer and floating-point)(integer and floating-point) division, / division, / (integer and floating-point) (integer and floating-point) modulus, %modulus, % (integer division to find remainder)(integer division to find remainder)

Page 52: Introduction to JAVA Programming Basics PROGRAMMING STEPS  ANALISA MASALAHNYA  INPUT-NYA APA SAJA?  ALGORITMA PROSESNYA BAGAIMANA?  OUTPUT-NYA APA?

Arithmetic OperatorsArithmetic Operators

Example: using the + operatorExample: using the + operatorpublic static void main(String[] args){

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

// declaring a variable to store the totalint total;

// performing addition:total = num1 + num2;

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

}

Page 53: Introduction to JAVA Programming Basics PROGRAMMING STEPS  ANALISA MASALAHNYA  INPUT-NYA APA SAJA?  ALGORITMA PROSESNYA BAGAIMANA?  OUTPUT-NYA APA?

Arithmetic ExpressionsArithmetic Expressions

More examples of expressions:More 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 division

quotient = num1 / num2; //integer divisionremainder = num1 % num2;

// how to display the results?}

Page 54: Introduction to JAVA Programming Basics PROGRAMMING STEPS  ANALISA MASALAHNYA  INPUT-NYA APA SAJA?  ALGORITMA PROSESNYA BAGAIMANA?  OUTPUT-NYA APA?

Operator PrecedenceOperator Precedence

Operators follow Operators follow precedence rulesprecedence rules:: Thus you should use parentheses ( ) Thus you should use parentheses ( )

where necessary.where necessary. Generally according to algebraic rules:Generally according to algebraic rules:

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

Page 55: Introduction to JAVA Programming Basics PROGRAMMING STEPS  ANALISA MASALAHNYA  INPUT-NYA APA SAJA?  ALGORITMA PROSESNYA BAGAIMANA?  OUTPUT-NYA APA?

Operator PrecedenceOperator Precedence

Example:Example: The expressionsThe expressions

3 + 5 * 5 will evaluate to 283 + 5 * 5 will evaluate to 28 (3 + 5) * 5 will evaluate to 40(3 + 5) * 5 will evaluate to 40

Page 56: Introduction to JAVA Programming Basics PROGRAMMING STEPS  ANALISA MASALAHNYA  INPUT-NYA APA SAJA?  ALGORITMA PROSESNYA BAGAIMANA?  OUTPUT-NYA APA?

Assignment CompatibilitiesAssignment Compatibilities In an assignment statement, you can In an assignment statement, you can

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

Page 57: Introduction to JAVA Programming Basics PROGRAMMING STEPS  ANALISA MASALAHNYA  INPUT-NYA APA SAJA?  ALGORITMA PROSESNYA BAGAIMANA?  OUTPUT-NYA APA?

Assignment CompatibilitiesAssignment Compatibilities However, you can not directly assign However, you can not directly assign

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

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

Page 58: Introduction to JAVA Programming Basics PROGRAMMING STEPS  ANALISA MASALAHNYA  INPUT-NYA APA SAJA?  ALGORITMA PROSESNYA BAGAIMANA?  OUTPUT-NYA APA?

Type CastingType Casting Generally, you can only assign a type Generally, you can only assign a type

to the type appearing further down the to the type appearing further down the list:list:byte > short > int > long > float > doublebyte > short > int > long > float > double

However, if you wish to change a However, if you wish to change a doubledouble type to an type to an intint, you must use , you must use type castingtype casting

Page 59: Introduction to JAVA Programming Basics PROGRAMMING STEPS  ANALISA MASALAHNYA  INPUT-NYA APA SAJA?  ALGORITMA PROSESNYA BAGAIMANA?  OUTPUT-NYA APA?

Type Casting: ExampleType Casting: Example

The value of iVariable is now 6The value of iVariable is now 6 The value of The value of dblVariabledblVariable is truncated and is truncated and

assigned to assigned to iVariableiVariable..

The value of The value of dblVariabledblVariable remains 6.75 remains 6.75

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

// assigning double to int by typecasting

Page 60: Introduction to JAVA Programming Basics PROGRAMMING STEPS  ANALISA MASALAHNYA  INPUT-NYA APA SAJA?  ALGORITMA PROSESNYA BAGAIMANA?  OUTPUT-NYA APA?

Sample ProgramSample Program Let's have a look at the following Let's have a look at the following

program. What does it do?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;

}}

Page 61: Introduction to JAVA Programming Basics PROGRAMMING STEPS  ANALISA MASALAHNYA  INPUT-NYA APA SAJA?  ALGORITMA PROSESNYA BAGAIMANA?  OUTPUT-NYA APA?

Displaying outputDisplaying output

We must use display the results obtainedWe 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 the value stored in the variable sum

Page 62: Introduction to JAVA Programming Basics PROGRAMMING STEPS  ANALISA MASALAHNYA  INPUT-NYA APA SAJA?  ALGORITMA PROSESNYA BAGAIMANA?  OUTPUT-NYA APA?

Displaying outputDisplaying output However, we should always make our output However, we should always make our output

meaningful and clear.meaningful and 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

}}

Page 63: Introduction to JAVA Programming Basics PROGRAMMING STEPS  ANALISA MASALAHNYA  INPUT-NYA APA SAJA?  ALGORITMA PROSESNYA BAGAIMANA?  OUTPUT-NYA APA?

Displaying outputDisplaying output We can use the System.out.print() We can use the System.out.print()

method: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

}}

Page 64: Introduction to JAVA Programming Basics PROGRAMMING STEPS  ANALISA MASALAHNYA  INPUT-NYA APA SAJA?  ALGORITMA PROSESNYA BAGAIMANA?  OUTPUT-NYA APA?

Displaying outputDisplaying output

We can combine Strings and data using the We can combine Strings and data using the concatenation operator +concatenation 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}

}

Page 65: Introduction to JAVA Programming Basics PROGRAMMING STEPS  ANALISA MASALAHNYA  INPUT-NYA APA SAJA?  ALGORITMA PROSESNYA BAGAIMANA?  OUTPUT-NYA APA?

Concatenation + Concatenation +

The symbol '+' has two meanings in JavaThe symbol '+' has two meanings in Java Addition plus, which adds two numbersAddition plus, which adds two numbers Concatenation plus, which joins Strings or text Concatenation plus, which joins Strings or text

together.together.

Page 66: Introduction to JAVA Programming Basics PROGRAMMING STEPS  ANALISA MASALAHNYA  INPUT-NYA APA SAJA?  ALGORITMA PROSESNYA BAGAIMANA?  OUTPUT-NYA APA?

Concatenation + Concatenation +

'+' will be used for '+' will be used for additionaddition if: if: both operands are numericboth 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 '+' will be used to concatenateconcatenate if: if: if either operand is a String or textif either operand is a String or text

Page 67: Introduction to JAVA Programming Basics PROGRAMMING STEPS  ANALISA MASALAHNYA  INPUT-NYA APA SAJA?  ALGORITMA PROSESNYA BAGAIMANA?  OUTPUT-NYA APA?

ExerciseExercise

Write a Java program that sets the values Write a Java program that sets the values of three integer-valued assignment scores of three integer-valued assignment scores and then calculates and displays:and then calculates and displays: the total of the three scoresthe total of the three scores the average of the three scoresthe average of the three scores

Page 68: Introduction to JAVA Programming Basics PROGRAMMING STEPS  ANALISA MASALAHNYA  INPUT-NYA APA SAJA?  ALGORITMA PROSESNYA BAGAIMANA?  OUTPUT-NYA APA?

ExerciseExercise What is wrong with the following program?What 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);

}}

Page 69: Introduction to JAVA Programming Basics PROGRAMMING STEPS  ANALISA MASALAHNYA  INPUT-NYA APA SAJA?  ALGORITMA PROSESNYA BAGAIMANA?  OUTPUT-NYA APA?

The The CharChar data type data type Another primitive data type is Another primitive data type is charchar The The charchar data type can hold values of the data type can hold values of the

following character literals:following character literals: the letters of the alphabet, eg.: the letters of the alphabet, eg.: 'A', 'b''A', 'b' the digits, eg. : the digits, eg. : '0' , '3''0' , '3' other special symbols, eg.: other special symbols, eg.: '(', '&', '+' '(', '&', '+' the null (empty) character: the null (empty) character: ''''

Page 70: Introduction to JAVA Programming Basics PROGRAMMING STEPS  ANALISA MASALAHNYA  INPUT-NYA APA SAJA?  ALGORITMA PROSESNYA BAGAIMANA?  OUTPUT-NYA APA?

The The CharChar data type data type Invalid character literals:Invalid character literals:

"a""a" – this is a string – this is a string 'aB''aB' – these are two characters – these are two characters '''''' – three consecutive single quotes: – three consecutive single quotes:

what does it mean?what does it mean?

Page 71: Introduction to JAVA Programming Basics PROGRAMMING STEPS  ANALISA MASALAHNYA  INPUT-NYA APA SAJA?  ALGORITMA PROSESNYA BAGAIMANA?  OUTPUT-NYA APA?

Escape SequenceEscape Sequence

Sometimes it is necessary to represent Sometimes it is necessary to represent symbols:symbols: which already have special meanings in the which already have special meanings in the

Java language, such as ' or "Java language, such as ' or " other characters such as a tab or return.other characters such as a tab or return.

Page 72: Introduction to JAVA Programming Basics PROGRAMMING STEPS  ANALISA MASALAHNYA  INPUT-NYA APA SAJA?  ALGORITMA PROSESNYA BAGAIMANA?  OUTPUT-NYA APA?

Escape SequenceEscape Sequence

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

charactercharacter '\\' '\\' to represent a backslash character. to represent a backslash character. '\t''\t' to represent a tab to represent a tab '\n''\n' to create a new line to create a new line

Page 73: Introduction to JAVA Programming Basics PROGRAMMING STEPS  ANALISA MASALAHNYA  INPUT-NYA APA SAJA?  ALGORITMA PROSESNYA BAGAIMANA?  OUTPUT-NYA APA?

ExerciseExercise

Write a program that will display the Write a program that will display the following:following: She said "Hello!" to me!She said "Hello!" to me!

Page 74: Introduction to JAVA Programming Basics PROGRAMMING STEPS  ANALISA MASALAHNYA  INPUT-NYA APA SAJA?  ALGORITMA PROSESNYA BAGAIMANA?  OUTPUT-NYA APA?

The The StringString Data Type Data Type

A A String String type is an example of a reference type is an example of a reference data type.data type.

A string is defined as a sequence of A string is defined as a sequence of characters.characters.

Page 75: Introduction to JAVA Programming Basics PROGRAMMING STEPS  ANALISA MASALAHNYA  INPUT-NYA APA SAJA?  ALGORITMA PROSESNYA BAGAIMANA?  OUTPUT-NYA APA?

The The StringString Data Type Data Type

Examples of String literals:Examples of String literals: " " (space, not the character ' ')" " (space, not the character ' ') "" (empty String)"" (empty String) "a""a" "HELLO" "HELLO" "This is a String""This is a String" "\tThis is also a String\n""\tThis is also a String\n"

Page 76: Introduction to JAVA Programming Basics PROGRAMMING STEPS  ANALISA MASALAHNYA  INPUT-NYA APA SAJA?  ALGORITMA PROSESNYA BAGAIMANA?  OUTPUT-NYA APA?

Declaring a StringDeclaring a String

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

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

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

Page 77: Introduction to JAVA Programming Basics PROGRAMMING STEPS  ANALISA MASALAHNYA  INPUT-NYA APA SAJA?  ALGORITMA PROSESNYA BAGAIMANA?  OUTPUT-NYA APA?

ExerciseExercise

Write a program to print out the following, Write a program to print out the following, using String variables:using String variables:Subject code: BIT106Subject code: BIT106Subject name: Java ProgrammingSubject name: Java ProgrammingStudent name: Lee Ah YewStudent name: Lee Ah YewAssignment 1 Score (out of 25): 24.0 Assignment 1 Score (out of 25): 24.0 Assignment 2 Score (out of 25): 23.5Assignment 2 Score (out of 25): 23.5Exam Raw Score (out of 50) : 48.90Exam Raw Score (out of 50) : 48.90

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

Page 78: Introduction to JAVA Programming Basics PROGRAMMING STEPS  ANALISA MASALAHNYA  INPUT-NYA APA SAJA?  ALGORITMA PROSESNYA BAGAIMANA?  OUTPUT-NYA APA?

Keyboard InputKeyboard Input

Java 5.0 has reasonable facilities for Java 5.0 has reasonable facilities for handling keyboard input.handling keyboard input.

These facilities are provided by the These facilities are provided by the ScannerScanner class in the class in the java.utiljava.util package.package. A A packagepackage is a library of classes. is a library of classes.

Page 79: Introduction to JAVA Programming Basics PROGRAMMING STEPS  ANALISA MASALAHNYA  INPUT-NYA APA SAJA?  ALGORITMA PROSESNYA BAGAIMANA?  OUTPUT-NYA APA?

Using the Scanner ClassUsing the Scanner Class

Near the beginning of your program, insertNear the beginning of your program, insert

import java.util.*import java.util.* Create an object of the Create an object of the ScannerScanner class class

Scanner sc = new Scanner Scanner sc = new Scanner (System.in)(System.in)

Read data (an Read data (an intint or a or a doubledouble, for example), for example)

int n1 = sc.nextInt();int n1 = sc.nextInt();

double d1 = sc.nextDouble();double d1 = sc.nextDouble();

Page 80: Introduction to JAVA Programming Basics PROGRAMMING STEPS  ANALISA MASALAHNYA  INPUT-NYA APA SAJA?  ALGORITMA PROSESNYA BAGAIMANA?  OUTPUT-NYA APA?

Keyboard Input DemonstrationKeyboard Input Demonstration

class ScannerDemoclass ScannerDemo

Page 81: Introduction to JAVA Programming Basics PROGRAMMING STEPS  ANALISA MASALAHNYA  INPUT-NYA APA SAJA?  ALGORITMA PROSESNYA BAGAIMANA?  OUTPUT-NYA APA?

Some Some ScannerScanner Class Methods Class Methods

syntaxsyntax

Int_Variable = Object_NameInt_Variable = Object_Name.nextInt();.nextInt();

Double_Variable = Object_NameDouble_Variable = Object_Name.nextDouble();.nextDouble();

String_Variable = Object_NameString_Variable = Object_Name.next();.next();

String_Variable = Object_NameString_Variable = Object_Name.nextLine();.nextLine();

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

Page 82: Introduction to JAVA Programming Basics PROGRAMMING STEPS  ANALISA MASALAHNYA  INPUT-NYA APA SAJA?  ALGORITMA PROSESNYA BAGAIMANA?  OUTPUT-NYA APA?

Interactive InputInteractive Input

You should always You should always promptprompt the user when the user when obtaining data:obtaining data:

Please enter your name: Sandy Lim

Please enter your age: 25

Please enter your score: 87.9Please enter your grade: A

Page 83: Introduction to JAVA Programming Basics PROGRAMMING STEPS  ANALISA MASALAHNYA  INPUT-NYA APA SAJA?  ALGORITMA PROSESNYA BAGAIMANA?  OUTPUT-NYA APA?

ExerciseExercise

Write a program that asks the user to enter Write a program that asks the user to enter the name of an item, the price and the the name of an item, the price and the quantity purchased. The program must quantity purchased. The program must calculate the total price and display the calculate the total price and display the following:following:

ItemItem UnitUnit QtyQty Total Total

widget widget RM5.30RM5.30 1010 RM53.00 RM53.00

Page 84: Introduction to JAVA Programming Basics PROGRAMMING STEPS  ANALISA MASALAHNYA  INPUT-NYA APA SAJA?  ALGORITMA PROSESNYA BAGAIMANA?  OUTPUT-NYA APA?

PseudocodePseudocode When we want to write a computer program, we When we want to write a computer program, we

should always:should always: ThinkThink PlanPlan CodeCode

We can write out our planning using We can write out our planning using pseudocodepseudocode – writing out the steps in simple English and not – writing out the steps in simple English and not strict programming language syntax.strict programming language syntax.

Page 85: Introduction to JAVA Programming Basics PROGRAMMING STEPS  ANALISA MASALAHNYA  INPUT-NYA APA SAJA?  ALGORITMA PROSESNYA BAGAIMANA?  OUTPUT-NYA APA?

DocumentationDocumentation

A computer programmer generally spends more A computer programmer generally spends more time time readingreading and modifying programs than and modifying programs than writing new ones.writing new ones.

It is therefore important that your programs are It is therefore important that your programs are documented:documented: clearlyclearly neatlyneatly meaningfullymeaningfully

Page 86: Introduction to JAVA Programming Basics PROGRAMMING STEPS  ANALISA MASALAHNYA  INPUT-NYA APA SAJA?  ALGORITMA PROSESNYA BAGAIMANA?  OUTPUT-NYA APA?

DocumentationDocumentation

You should always precede your program with:You should always precede your program with: Your nameYour name The dateThe date The purpose of the programThe purpose of the program

Page 87: Introduction to JAVA Programming Basics PROGRAMMING STEPS  ANALISA MASALAHNYA  INPUT-NYA APA SAJA?  ALGORITMA PROSESNYA BAGAIMANA?  OUTPUT-NYA APA?

CommentsComments

Comments are used to:Comments are used to: Insert documentationInsert documentation Clarify parts of code which may be complex.Clarify parts of code which may be complex.

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

Page 88: Introduction to JAVA Programming Basics PROGRAMMING STEPS  ANALISA MASALAHNYA  INPUT-NYA APA SAJA?  ALGORITMA PROSESNYA BAGAIMANA?  OUTPUT-NYA APA?

CommentsComments

The symbols // are used to indicate that the rest The symbols // are used to indicate that the rest of a line are comments.of a line are comments.

If comments span more than one line, the If comments span more than one line, the symbols /* and */ can be used, eg.:symbols /* and */ can be used, eg.:/* this is the beginning of the documented /* this is the beginning of the documented comments and it only ends here */comments and it only ends here */

Page 89: Introduction to JAVA Programming Basics PROGRAMMING STEPS  ANALISA MASALAHNYA  INPUT-NYA APA SAJA?  ALGORITMA PROSESNYA BAGAIMANA?  OUTPUT-NYA APA?

Variable namesVariable names

Variable names shoud:Variable names shoud: follow the Java rulesfollow the Java rules be be meaningfulmeaningful

For example, For example, namename, , score, totalBeforeTaxesscore, totalBeforeTaxes You should almost never use names likeYou should almost never use names likea, b, ca, b, c

Page 90: Introduction to JAVA Programming Basics PROGRAMMING STEPS  ANALISA MASALAHNYA  INPUT-NYA APA SAJA?  ALGORITMA PROSESNYA BAGAIMANA?  OUTPUT-NYA APA?

Variable namesVariable names

By convention:By convention: variable names start with a lowercase lettervariable names start with a lowercase letter class names start with an uppercase letter, class names start with an uppercase letter,

eg. eg. String, ScannerString, Scanner

Page 91: Introduction to JAVA Programming Basics PROGRAMMING STEPS  ANALISA MASALAHNYA  INPUT-NYA APA SAJA?  ALGORITMA PROSESNYA BAGAIMANA?  OUTPUT-NYA APA?

IndentationIndentation

Programs are also Programs are also indentedindented for clarity for clarity Indentation shows the levels of nesting for Indentation shows the levels of nesting for

the program.the program.public class CalcCircle{

public static void main(String[] args){

int radius; // radius - variablefinal double PI = 3.14159; // PI - constants

 radius = 10;double area = PI * radius * radius;double circumference = 2 * PI * radius;

}}

Page 92: Introduction to JAVA Programming Basics PROGRAMMING STEPS  ANALISA MASALAHNYA  INPUT-NYA APA SAJA?  ALGORITMA PROSESNYA BAGAIMANA?  OUTPUT-NYA APA?

ExerciseExercise

Write a program that asks the user for Write a program that asks the user for their name and the year they were born. their name and the year they were born. Then display their age this year.Then display their age this year.

What is your name? KellyWhat is your year of birth? 1982Wow, Kelly, this year you will be 21 years old!

Page 93: Introduction to JAVA Programming Basics PROGRAMMING STEPS  ANALISA MASALAHNYA  INPUT-NYA APA SAJA?  ALGORITMA PROSESNYA BAGAIMANA?  OUTPUT-NYA APA?

ExerciseExercise

Write a program that asks the user to Write a program that asks the user to enter the length and width of a rectangle enter the length and width of a rectangle and then display:and then display: the area of the rectanglethe area of the rectangle the perimeter of the rectanglethe perimeter of the rectangle

Page 94: Introduction to JAVA Programming Basics PROGRAMMING STEPS  ANALISA MASALAHNYA  INPUT-NYA APA SAJA?  ALGORITMA PROSESNYA BAGAIMANA?  OUTPUT-NYA APA?

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

Page 95: Introduction to JAVA Programming Basics PROGRAMMING STEPS  ANALISA MASALAHNYA  INPUT-NYA APA SAJA?  ALGORITMA PROSESNYA BAGAIMANA?  OUTPUT-NYA APA?

ExerciseExercise Write a Java program that asks the user to enter two Write a Java program that asks the user to enter two

numbers, then:numbers, then: find the absolute value of each of the numbers;find the absolute value of each of the numbers; determine which absolute value is largerdetermine which absolute value is larger find the square root of the larger of the two absolute valuesfind the square root of the larger of the two absolute valuesSample run:Sample run:Enter first number: Enter first number: -36-36Enter second number: Enter second number: 55The absolute values of the two numbers are 36 and 5The absolute values of the two numbers are 36 and 5The larger absolute value is 36The larger absolute value is 36The square root of 36 is 6.0The square root of 36 is 6.0

Page 96: Introduction to JAVA Programming Basics PROGRAMMING STEPS  ANALISA MASALAHNYA  INPUT-NYA APA SAJA?  ALGORITMA PROSESNYA BAGAIMANA?  OUTPUT-NYA APA?

Catch-up ExerciseCatch-up Exercise

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

Now test the program with the values:Now test the program with the values: 39.439.4 -30-30

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

Page 97: Introduction to JAVA Programming Basics PROGRAMMING STEPS  ANALISA MASALAHNYA  INPUT-NYA APA SAJA?  ALGORITMA PROSESNYA BAGAIMANA?  OUTPUT-NYA APA?

Tugas RumahTugas Rumah

NPM GanjilNPM Ganjil Buat program untuk menghitung volume balok.Buat program untuk menghitung volume balok.

NPM GenapNPM Genap Buat program untuk menghitung volume bola.Buat program untuk menghitung volume bola.

Input data dilakukan oleh user! Bukan Input data dilakukan oleh user! Bukan programmer! Gunakan class Scanner.programmer! Gunakan class Scanner.

Buat flowchart-nya terlebih dulu.Buat flowchart-nya terlebih dulu. Dikumpulkan maks. Jumat 1/10/2010 pukul Dikumpulkan maks. Jumat 1/10/2010 pukul

24.00 WIB. Di kertas atau kirim lewat email 24.00 WIB. Di kertas atau kirim lewat email [email protected]@yahoo.com.