980 likes | 1.07k Views
Introduction to JAVA. Programming Basics. PROGRAMMING STEPS. ANALISA MASALAHNYA INPUT-NYA APA SAJA? ALGORITMA PROSESNYA BAGAIMANA? OUTPUT-NYA APA? KETIK SOURCE CODE-NYA HEADER FILES import < library > GLOBAL SECTIONS VARIABEL GLOBAL, FUNGSI BANTU
E N D
Introduction to JAVA Programming Basics
PROGRAMMING STEPS • ANALISA MASALAHNYA • INPUT-NYA APA SAJA? • ALGORITMA PROSESNYA BAGAIMANA? • OUTPUT-NYA APA? • KETIK SOURCE CODE-NYA • HEADER FILES import < library > • GLOBAL SECTIONS VARIABEL GLOBAL, FUNGSI BANTU • MAIN SECTIONS VARIABEL LOKAL, INPUT, PROSES, OUTPUT • COMPILE & RUN PROGRAMNYA ADA ERROR ? • TES HASILNYA SUDAH BENAR ? • BUAT ARSIP/ DOKUMENTASINYA
Computers and Programming • A computer is a machine that can process data by carrying out complex calculations quickly. • A program is a set of instructions for the computer to execute. • A program can be high-level (easy for humans to understand) or low-level (easy for the computer to understand). • In any case, programs have to be written following a strict language syntax.
void test() { println(“Hi”); } source code (high level) programmer compiler Hi machine language object code (low level) computer Running a Program • Typically, a program source code has to be compiled into machine language before it can be understood by a computer. writes executed by
Portability • Different makes of computers • speak different “languages” (machine language) • use different compilers. • This means that object code produced by one compiler may not work on another computer of a different make. • Thus the program is not portable. • Java is portable because it works in a different way.
History of Java • The Java programming language was developed at Sun Microsystems • It is meant to be a portable language that allows the same program code to be run on different computer makes. • Java program code is translated into byte-code that is interpreted into machine language that the computer can understand.
Java Byte-Code • Java source code is compiled by the Java compiler into byte-code. • Byte-code is the machine language for a ‘typical’ computer. • This ‘typical’ computer is known as the Java Virtual Machine. • A byte-code interpreter will translate byte-code into object code for the particular machine. • The byte-code is thus portable because an interpreter is simpler to write than a compiler.
public void test() { System.out.println(“Hi”); } Java source code (high level) Javacompiler Byte-code interpreter programmer Extra step thatallows for portability Hi Machine language object code (low level) computer Running a Java Program writes Javabyte-code executed by
Types of Java Programs • Console Applications: • Simple text input / output • This is what we will be doing for most of this course as we are learning how to program. public class ConsoleApp { public static void main(String[] args) { System.out.println("Hello World!"); } }
Types of Java Programs • GUI Applications: • Using 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); } }
Types of Java Programs • Applets • To 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>
Sample Java Program public class CalcCircle { public static void main(String[ ] args) { int radius; // radius - variable final double PI = 3.14159; // PI - constants radius = 10; double area = PI * radius * radius; double circumference = 2 * PI * radius; System.out.println(”For a circle with radius ” + radius + ”,”); System.out.print(”The circumference is ” + circumference); System.out.println(” and the area is ” + area); } }
Elements of a Java Program • A Java Program is made up of: • Identifiers: • variables • constants • Literal values • Data types • Operators • Expressions
identifier indicating name of the program(class name) identifier untuk menyimpan nilai tetap PI (constant) identifier untuk menyimpan nilai radius(variable) Identifiers/ Pengenal • The identifiers in the previous program consist of: public class CalcCircle { public static void main(String[] args) { int radius; // radius - variable finaldouble PI = 3.14159; // PI - constants … } }
PI adalah sebuah nilai floating-point (double) radius adalah sebuah nilai integer (int) Data Types/ Tipe Data • Data types indicate the type of storage required. public class CalcCircle { public static void main(String[ ] args) { int radius; // radius - variable finaldouble PI = 3.14159; // PI - constants … } }
the variable radius stores the value 10 Literal values • Literals are the actual values stored in variables or used in calculations. public class CalcCircle { public static void main(String[ ] args) { … radius = 10; … } }
Operator perkalian (*) dipakai Untuk menghitung luas bidang Operators and Expressions • Operators allow us to perform some calculations 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; … } } Sebuah ekspresi yang menggunakan operators dan operands
Program berupa definisi class. Gunakan nama class yang sama dengan nama file-nya.Misal CalcCircle.java Program harus memiliki method main sebagai titik awal eksekusi program. Kurung kurawal menunjukkan awal dan akhir.Gunakan indentasi supaya jelas dibaca. Java Program Structure • For the next few weeks, our Java programs 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 // } }
Teks dan data diantara tanda petik akan ditampilkan di layar monitor. Displaying Output • For console applications, we use the 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); } }
Compiling and Running • The preceding source code must be saved as CalcCircle.java • You must then use the Java Development Kit (JDK) to compile the program using the commandjavac CalcCircle.java • The byte-code file CalcCircle.class will be created by the compiler if there are no errors. • To run the program, use the commandjava CalcCircle
Compiling and Runnng Buttons to compile andrun the program
class header mainmethod Anatomy of a Java Class • A Java console application must consist of one 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 5 System.out.print("num1 has value "); System.out.println(num1); } }
multi-line comments name of the class in-linecomments statementsto be executed Anatomy of a Java Class • A Java console application must consist of one 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 5 System.out.print("num1 has value "); System.out.println(num1); } }
What is the result of execution? public class CalcCircle { public static void main(String[ ] args) { int radius; // radius - variable finaldouble PI = 3.14159; // PI - constants radius = 10; double area = PI * radius * radius; double circumference = 2 * PI * radius; System.out.println(”For a circle with radius ” + radius + ”,”); System.out.print(”The circumference is ” + circumference); System.out.println(” and the area is ” + area); } }
Displaying output • There are some predefined classes in Java that we can use for basic tasks such as: • reading input • displaying output • We use the Systemclass to display output to the screen for console applications. • System.out is an object that provides methods for displaying strings of characters to the console screen. • The methods we can use are print and println.
Example • Write a program that prints two lines: I love Java Programming 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"); } }
Print vs Println • What if you use System.out.print() instead? • System.out.println() advances the cursor to the next line after displaying the required output. • If you use System.out.print(), you might need to add spaces to format your output clearly.
Code Fragment Output Displayed System.out.println("First line"); System.out.println("Second line"); First line Second line System.out.print("First line"); System.out.print("Second line"); First lineSecond line Examples
Exercise • Write a Java program that displays your name and your studentID. // Sandy Lim // Lecture 1 // Printing name and student ID public class Information { public static void main (String[] args) { // your code here } }
Exercise • Write a Java program that prints out to 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 } }
Reminders • Get your computer accounts before next week's tutorial so that you can start programming ASAP. • Download JCreatorLE and J2SDK1.5.0, you can access both through the JCreator (3.50LE) website: http://www.jcreator.com/download.htm
Memory and Data • Salah 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 tersusun atas kotak-kotak/ laci untuk menyimpan data. • Ukuran kotak akan tergantung pada tipe data yang dipakai.
Identifiers • Kita harus memberi nama untuk setiap kotak memori yang kita pakai untuk menyimpan data. • Nama itulah yang dikenal sebagai namavariabel, atau identifiers. • Data asli adalah nilailiteral dari identifier. value of subject BIT106 The box is identified as subject and it stores the value “BIT106” subject identifier / variable name
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.
Identifier Rules • A single identifier must be one word only (no spaces) of any length. • Sebuah identifier harus berupa satu kata (tanpa spasi) dengan panjang 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
Examples • Examples of identifiers num1 num2 first_name lastName numberOfStudents accountNumber myProgram MYPROGRAM • Examples of reserved words public if int double • see Appendix 1 in the text book for others. • Illegal identifiers 3rdValue my program this&that
Exercise • Which of the following are valid identifier names? • my_granny’s_name • joesCar • integer • 2ndNum • Child3 • double • third value • mid2chars • PUBLIC
Types of Data • What kind of data can be collected for use in a computer system? • Data jenis apakah yang dapat dikumpulkan untuk pemakaian sebuah sistem komputer? • Consider data on: • College application form/ Formulir SPMB • Student transcript/ Transkrip mahasiswa • Role Playing Game (RPG)
Types of Data • We typically want to collect data which may be • numeric • characters • Strings • choice (Y/N)
Java Data Types • In 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) yang diperlukan untuk menyimpan data, maka kita perlu mendeklarasikan tipe data yang dipakai oleh identifier. • Integer data types are used to hold whole numbers • 0, -10, 99, 1001 • The Character data type is used to hold any single character from the computer keyboard • '>', 'h', '8' • Floating-point data types can hold numbers with a decimal point and a fractional part. • -2.3, 6.99992, 5e6, 1.5f • The Boolean data type can hold the values true or false.
Primitive vs Reference Data Types • A data type can be a: • Primitive type • Reference type (or Class type)
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
Java Primitive Data Types • There are 8 primitive data types in Java
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;
Declaring variables • Examples: • The following statements will declare • an 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 variables int studentNumber; double score; char letterGrade;
Assignment Statements • Once we have declared our variables, we can use the variables to hold data. • This is done by assigning literal values to the variables. • Syntax (for primitive types): VariableName = value; • This means that the value on the right hand side is evaluated and the variable on the left hand side is set to this value. • Masukkan value ke VariableName
Assignment Statements • Examples: • Setting the student number, score and lettergrade for the variables declared earlier: public static void main(String[] args) { // declaring variables int studentNumber; double score; char letterGrade; // assigning values to variables studentNumber = 100; score = 50.8; letterGrade = 'D';}
Initializing Variables • We 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 are undetermined.
Initializing Variables • Example: the variables are initialized as they are declared: public static void main(String[] args) { // declaring variables int studentNumber = 100; double score = 50.8; char letterGrade = 'D'; }