1 / 97

Introduction to JAVA

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

Download Presentation

Introduction to JAVA

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Introduction to JAVA Programming Basics

  2. 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

  3. 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.

  4. 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

  5. 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.

  6. 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.

  7. 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.

  8. 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

  9. 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!"); } }

  10. 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); } }

  11. 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>

  12. 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); } }

  13. Elements of a Java Program • A Java Program is made up of: • Identifiers: • variables • constants • Literal values • Data types • Operators • Expressions

  14. 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 … } }

  15. 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 … } }

  16. 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; … } }

  17. 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

  18. 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 // } }

  19. 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); } }

  20. 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

  21. Compiling and Runnng Buttons to compile andrun the program

  22. 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); } }

  23. 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); } }

  24. 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); } }

  25. 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.

  26. 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"); } }

  27. 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.

  28. 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

  29. 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 } }

  30. 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 } }

  31. 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

  32. Data Types, Variables & Operators

  33. 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.

  34. 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

  35. 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.

  36. 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

  37. 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

  38. Exercise • Which of the following are valid identifier names? • my_granny’s_name • joesCar • integer • 2ndNum • Child3 • double • third value • mid2chars • PUBLIC

  39. 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)

  40. Types of Data • We typically want to collect data which may be • numeric • characters • Strings • choice (Y/N)

  41. 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.

  42. Primitive vs Reference Data Types • A data type can be a: • Primitive type • Reference type (or Class type)

  43. 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

  44. Java Primitive Data Types • There are 8 primitive data types in Java

  45. 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;

  46. 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;

  47. 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

  48. 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';}

  49. 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.

  50. 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'; }

More Related