Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: "Introduction to JAVA Programming Basics PROGRAMMING STEPS  ANALISA MASALAHNYA  INPUT-NYA APA SAJA?  ALGORITMA PROSESNYA BAGAIMANA?  OUTPUT-NYA APA?"— Presentation transcript:

1

2 Introduction to JAVA Programming Basics

3 PROGRAMMING STEPS  ANALISA MASALAHNYA  INPUT-NYA APA SAJA?  ALGORITMA PROSESNYA BAGAIMANA?  OUTPUT-NYA APA?  KETIK SOURCE CODE-NYA  HEADER FILES  import  HEADER FILES  import  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

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

5 Running a Program  Typically, a program source code has to be compiled into machine language before it can be 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

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

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

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

9 Running a Java Program programmer public void test() { System.out.println(“Hi”); } Java source code (high level) Java compiler Machine language object code (low level) writes executed by computer Hi Byte-code interpreter Java byte-code Extra step that allows for portability

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

11 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); }

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

13 Sample Java Program public class CalcCircle { public static void main(String[ ] args) 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); }}

14 Elements of a Java Program  A Java Program is made up of:  Identifiers:  variables  constants  Literal values  Data types  Operators  Expressions

15 Identifiers/ Pengenal  The identifiers in the previous program consist of: public class CalcCircle { public static void main(String[] args) { int radius;// radius - variable final 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)

16 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 final double PI = 3.14159;// PI - constants … } radius adalah sebuah nilai integer (int) PI adalah sebuah nilai floating-point (double)

17 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; … } the variable radius stores the value 10

18 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; … } Operator perkalian (*) dipakai Untuk menghitung luas bidang Sebuah ekspresi yang menggunakan operators dan operands

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

20 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); } Teks dan data diantara tanda petik akan ditampilkan di layar monitor.

21 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 command javac 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 command java CalcCircle

22 Compiling and Runnng Buttons to compile and run the program

23 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); } class header main method

24 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 in-line comments name of the class statements to be executed

25 What is the result of execution? public class CalcCircle { public static void main(String[ ] args) 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); }}

26 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 System class 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.

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

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

29 Examples Code FragmentOutput 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

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

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

32 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 http://www.jcreator.com/download.htm

33 Data Types, Variables & Operators

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

35 Identifiers  Kita harus memberi nama untuk setiap kotak memori yang kita pakai 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 name The box is identified as subject and it stores the value “BIT106”

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

37 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

38 Examples  Examples of identifiers num1num2first_namelastName numberOfStudentsaccountNumber myProgramMYPROGRAM  Examples of reserved words publicifintdouble  see Appendix 1 in the text book for others.  Illegal identifiers 3rdValuemy programthis&that

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

40 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)

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

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

43 Primitive vs Reference Data Types  A data type can be a:  Primitive type  Reference type (or Class type)

44 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

45 Java Primitive Data Types  There are 8 primitive data types in Java Type name Kind of value Memory used byteinteger 1 byte shortinteger 2 bytes intinteger 4 bytes longinteger 8 bytes float floating-point number 4 bytes double floating-point number 8 bytes char single character 2 bytes boolean true or false 1 bit

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

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

48 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

49 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'; }

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

51 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'; }

52 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)

53 Arithmetic Operators  Example: using the + operator public static void main(String[] args) { // declaring two integer variables int num1 = 5, num2 = 8; // declaring a variable to store the total int total; // performing addition: total = num1 + num2; // display result System.out.println(“total = “ + total); }

54 Arithmetic Expressions  More examples of expressions: public static void main(String[] args) { // declaring variables int 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 division remainder = num1 % num2; // how to display the results? }

55 Operator Precedence  Operators follow precedence rules:  Thus you should use parentheses ( ) where necessary.  Generally according to algebraic rules:  ( ), *, /, %, +, -

56 Operator Precedence  Example:  The expressions  3 + 5 * 5 will evaluate to 28  (3 + 5) * 5 will evaluate to 40

57 Assignment Compatibilities  In an assignment statement, you can assign a value of one type into another type: int iVariable = 6; double dblVariable; dblVariable = iVariable; // assigning int to double

58 Assignment Compatibilities  However, you can not directly assign a double into an int double dblVariable = 6.75; int iVariable; iVariable = dblVariable; // assigning double to int Compiler error! Possible loss of precision

59 Type Casting  Generally, you can only assign a type to the type appearing further down the list: byte > short > int > long > float > double  However, if you wish to change a double type to an int, you must use type casting

60 Type Casting: Example  The value of iVariable is now 6  The value of dblVariable is truncated and assigned to iVariable.  The value of dblVariable remains 6.75 double dblVariable = 6.75; int iVariable; iVariable = (int) dblVariable; // assigning double to int by typecasting

61 Sample Program  Let'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; }

62 Displaying output  We 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

63 Displaying output  However, we should always make our output 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 }

64 Displaying output  We 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 }

65 Displaying output  We can combine Strings and data using the 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 }

66 Concatenation +  The symbol '+' has two meanings in Java  Addition plus, which adds two numbers  Concatenation plus, which joins Strings or text together.

67 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

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

69 Exercise  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 / 2 System.out.print("The average of "); System.out.print(score1); System.out.print("and"); System.out.println(score2); System.out.println("is " + average); }

70 The Char data type  Another 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: ''

71 The Char data type  Invalid character literals:  "a" – this is a string  'aB' – these are two characters  ''' – three consecutive single quotes:  what does it mean?

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

73 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

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

75 The String Data Type  A String type is an example of a reference data type.  A string is defined as a sequence of characters.

76 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"

77 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”;

78 Exercise  Write a program to print out the following, using String variables: Subject code: BIT106 Subject name: Java Programming Student name: Lee Ah Yew Assignment 1 Score (out of 25): 24.0 Assignment 2 Score (out of 25): 23.5 Exam Raw Score (out of 50) : 48.90 Lee Ah Yew's Total Score for BIT106 (Java Programming): 96.40

79 Keyboard Input  Java 5.0 has reasonable facilities for handling keyboard input.  These facilities are provided by the Scanner class in the java.util package.  A package is a library of classes.

80 Using the Scanner Class  Near the beginning of your program, insert import java.util.*  Create an object of the Scanner class Scanner sc = new Scanner (System.in)  Read data (an int or a double, for example) int n1 = sc.nextInt(); double d1 = sc.nextDouble();

81 Keyboard Input Demonstration  class ScannerDemo

82 Some Scanner Class Methods  syntax Int_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: “);

83 Interactive Input  You should always prompt the user when obtaining data: Please enter your name: Sandy Lim Please enter your age: 25 Please enter your score: 87.9 Please enter your grade: A

84 Exercise  Write a program that asks the user to enter the name of an item, the price and the quantity purchased. The program must calculate the total price and display the following: ItemUnitQty Total widget RM5.3010 RM53.00

85 Pseudocode  When we want to write a computer program, we should always:  Think  Plan  Code  We can write out our planning using pseudocode – writing out the steps in simple English and not strict programming language syntax.

86 Documentation  A computer programmer generally spends more time reading and modifying programs than writing new ones.  It is therefore important that your programs are documented:  clearly  neatly  meaningfully

87 Documentation  You should always precede your program with:  Your name  The date  The purpose of the program

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

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

90 Variable names  Variable names shoud:  follow the Java rules  be meaningful  For example, name, score, totalBeforeTaxes  You should almost never use names like a, b, c

91 Variable names  By convention:  variable names start with a lowercase letter  class names start with an uppercase letter, eg. String, Scanner

92 Indentation  Programs are also indented for clarity  Indentation shows the levels of nesting for the 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; } }

93 Exercise  Write a program that asks the user for their name and the year they were born. Then display their age this year. What is your name? Kelly What is your year of birth? 1982 Wow, Kelly, this year you will be 21 years old!

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

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

96 Exercise  Write a Java program that asks the user to enter two numbers, then:  find the absolute value of each of the numbers;  determine which absolute value is larger  find the square root of the larger of the two absolute values Sample run: Enter first number: -36 Enter second number: 5 The absolute values of the two numbers are 36 and 5 The larger absolute value is 36 The square root of 36 is 6.0

97 Catch-up Exercise  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 enter negative values!

98 Tugas Rumah  NPM Ganjil  Buat program untuk menghitung volume balok.  NPM Genap  Buat program untuk menghitung volume bola.  Input data dilakukan oleh user! Bukan programmer! Gunakan class Scanner.  Buat flowchart-nya terlebih dulu.  Dikumpulkan maks. Jumat 1/10/2010 pukul 24.00 WIB. Di kertas atau kirim lewat email bluejundi@yahoo.com.


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

Similar presentations


Ads by Google