Presentation is loading. Please wait.

Presentation is loading. Please wait.

Introduction to Java Viska Mutiawani, M.Sc. Java: History Computers of the past.

Similar presentations


Presentation on theme: "Introduction to Java Viska Mutiawani, M.Sc. Java: History Computers of the past."— Presentation transcript:

1 Introduction to Java Viska Mutiawani, M.Sc

2 Java: History Computers of the past

3 Java: History (2) The invention of the microprocessor revolutionized computers Intel microprocessor Commodore Pet microcomputer

4 Java: History (3) It was believed that the logical next step for microprocessors was to have them run intelligent consumer electronics

5 Java History (4) Sun Microsystems funded an internal research project “Green” to investigate this opportunity. ◦ Result: A programming language called “Oak”

6 Java History (5) ◦ Problem: There was already a programming language called Oak. ◦ The “Green” team met at a local coffee shop to come up with another name...  Java!

7 Java: History (6) The concept of intelligent devices didn’t catch on. Project Green and work on the Java language was nearly canceled.

8 Java: History (7) The popularity of the Internet resulted in Sun’s re- focusing of Java on computers. Prior to the advent of Java, web pages allowed you to download only text and images. Your computer at home running a web browser User clicks on a link Images and text get downloaded Server containing a web page

9 Your computer at home running a web browser Server containing a web page Java: History (8) Java enabled web browsers allowed for the downloading of programs (Applets). Java is still used in this context today: ◦ Facebook (older version) ◦ Hotmail (older version) User clicks on a link Java Applet downloaded Java version of the Game of Life: Online checkers:

10 What is java? Developed by Sun Microsystems (James Gosling) A general-purpose object-oriented language Based on C/C++ Designed for easy Web/Internet applications Widespread acceptance

11 Java: Write Once, Run Anywhere Consequence of Java’s history: platform-independence Mac user running Safari Windows user running Internet Explorer Web page stored on Unix server Click on link to Applet Byte code is downloaded Virtual machine translates byte code to native Mac code and the Applet is run Byte code (part of web page)

12 Java: Write Once, Run Anywhere Consequence of Java’s history: platform-independent Mac user running Safari Windows user running Internet Explorer Web page stored on Unix server Click on link to AppletByte code is downloaded Virtual machine translates byte code to native Windows code and the Applet is run

13 Java: Write Once, Run Anywhere (2) But Java can also create standard (non- web based) programs Dungeon Master (Java version) Examples of mobile Java games: Kung Fu Panda 2: THQ

14 Java: Write Once, Run Anywhere (3) Java has been used by large and reputable companies to create serious stand-alone applications. Example: ◦ Eclipse 1 : started as a programming environment created by IBM for developing Java programs. The program Eclipse was itself written in Java. 1 For more information:

15 Compiled Programs With Different Operating Systems Windows compiler Executable (Windows) UNIX compiler Executable (UNIX) Mac OS compiler Executable (Mac) Computer program

16 A High Level View Of Translating/Executing Java Programs Java compiler (javac) Java program Filename.java Java bytecode (generic binary) Filename.class Stage 1: Compilation

17 A High Level View Of Translating/Executing Java Programs (2) Java interpreter (java) Java bytecode (generic binary) Filename.class Machine language instruction (UNIX) Machine language instruction (Windows) Machine language instruction (Apple) Stage 2: Interpreting and executing the byte code

18 Java Features (1) Simple ◦ fixes some clumsy features of C++ ◦ no pointers ◦ automatic garbage collection ◦ rich pre-defined class library html Object oriented ◦ focus on the data (objects) and methods manipulating the data ◦ all functions are associated with objects ◦ almost all datatypes are objects (files, strings, etc.) ◦ potentially better code organization and reuse

19 Java Features (2) Interpreted ◦ java compiler generate byte-codes, not native machine code ◦ the compiled byte-codes are platform-independent ◦ java bytecodes are translated on the fly to machine readable instructions in runtime (Java Virtual Machine) Portable ◦ same application runs on all platforms ◦ the sizes of the primitive data types are always the same ◦ the libraries define portable interfaces

20 Java Features (3) Reliable ◦ extensive compile-time and runtime error checking ◦ no pointers but real arrays. Memory corruptions or unauthorized memory accesses are impossible ◦ automatic garbage collection tracks objects usage over time Secure ◦ usage in networked environments requires more security ◦ memory allocation model is a major defense ◦ access restrictions are forced (private, public)

21 Java Features (4) Multithreaded ◦ multiple concurrent threads of executions can run simultaneously ◦ utilizes a sophisticated set of synchronization primitives (based on monitors and condition variables paradigm) to achieve this Dynamic ◦ java is designed to adapt to evolving environment ◦ libraries can freely add new methods and instance variables without any effect on their clients ◦ interfaces promote flexibility and reusability in code by specifying a set of methods an object can perform, but leaves open how these methods should be implemented ◦ can check the class type in runtime

22 Java Disadvantages Slower than compiled language such as C ◦ an experiment in 1999 showed that Java was 3 or 4 times slower than C or C++ title of the article: “Comparing Java vs. C/C++ Efficiency Issues to Interpersonal Issues” (Lutz Prechelt) ◦ adequate for all but the most time-intensive programs

23 Which Java?

24 Java Platform, Standard Edition (Java SE) lets you develop and deploy Java applications ondesktops and servers, as well as in today's demanding embedded environments. Java offers the rich user interface, performance, versatility, portability, and security that today’s applicationsrequire.desktopsembedded

25 Which Java? Java 8+ (current is 8u20 version) JDK (Java Development Kit), Standard Edition includes: ◦ JDK (Java development kit) – for developing Java software (creating Java programs.) ◦ JRE (Java Runtime environment) – only good for running pre-created Java programs.  Java Plug-in – a special version of the JRE designed to run through web browsers.

26 Install Java TM 2 Platform on your machine Can be installed on different platforms: ◦ Unix/Linux ◦ Windows ◦ Mac OS Follow the on-line instructions:

27 Smallest Compilable And Executable Java Program The name of the online example is: Smallest.java (Important note: file name matches the word after the keyword ‘class’) Smallest.java public class Smallest { public static void main (String[] args) { }

28 Creating, Compiling And Running Java Programs On The Computer Science Network javac Java compiler Java byte code filename.class (UNIX file) To compile the program at the command line type "javac filename.java" To run the interpreter, at the command line type "java filename" java Java Interpreter Type it in with the text editor of your choice filename.java (Unix file) Java program

29 Compiling The Smallest Java Program public class Smallest { public static void main (String[] args) { } Smallest.java javac (Java byte code) : : Smallest.class Type “javac Smallest.java”

30 Running The Smallest Java Program (Java byte code) : : Smallest.class java Type “java Smallest” (Platform/Operating specific binary : :

31 Running The Java Compiler At Home After installing Java you will need to indicate to the operating system where the java compiler has been installed (‘setting the path’). For details of how to set your path variable for your particular operating system try the Sun or Java website. Example of how to set the path in Windows: ◦

32 Getting Started: (1) (1) Create the source file: ◦ open a text editor, type in the code which defines a class (HelloWorldApp) and then save it in a file (HelloWorldApp.java) ◦ file and class name are case sensitive and must be matched exactly (except the.java part) Example Code: HelloWorldApp.java /** * The HelloWorldApp class implements an application * that displays "Hello World!" to the standard output */ public class HelloWorldApp { public static void main(String[] args) { // Display "Hello World!" System.out.println("Hello World!"); }  Java is CASE SENSITIVE!

33 Getting Started: (2) (2) Compile the program: ◦ compile HelloWorldApp.java by using the following command: javac HelloWorldApp.java it generates a file named HelloWorldApp.class  ‘javac’ is not recognized as an internal or external command, operable program or hatch file. javac: Command not found if you see one of these errors, you have two choices: 1) specify the full path in which the javac program locates every time. For example: C:\j2sdk1.4.2_09\bin\javac HelloWorldApp.java 2) set the PATH environment variable

34 Getting Started: (3) (3) Run the program: ◦ run the code through: java HelloWorldApp ◦ Note that the command is java, not javac, and you refer to HelloWorldApp, not HelloWorldApp.java or HelloWorldApp.class  Exception in thread "main" java.lang.NoClassDefFoundError: HelloWorldApp if you see this error, you may need to set the environment variable CLASSPATH.

35 Documentation / Comments Multi-line documentation /* Start of documentation End of documentation */ Documentation for a single line //Everything until the end of the line is a comment

36 Doc secara otomatis Komentar yang dimulai dengan /** dan berakhir dengan */ akan menghasilkan doc secara otomatis. javadoc yang disediakan dalam java akan melakukan proses searching terhadap /** terhadap file program, jika ketemu maka akan dibuat file HTML untuk dokumentasi Contoh doc versi Java

37 Review: What Should You Document? Program (or that portion of the program) author What does the program as a while do e.g., tax program. What are the specific features of the program e.g., it calculates personal or small business tax. What are it’s limitations e.g., it only follows Canadian tax laws and cannot be used in the US. In Canada it doesn’t calculate taxes for organizations with yearly gross earnings over $1 billion. What is the version of the program ◦ If you don’t use numbers for the different versions of your program then consider using dates (tie versions with program features).

38 Important Note Each Java instruction must be followed by a semi-colon! General format Instruction1; Instruction2; Instruction3; : : Examples int num = 0; System.out.println(num); : :

39 Java Output Format: System.out.print( +..); OR System.out.println( +..); Examples public class OutputExample1 { public static void main (String [] args) { int num = 123; // More on this shortly System.out.println("Good-night gracie!"); System.out.print(num); System.out.println("num="+num); }

40 Output : Some Escape Sequences For Formatting Escape sequenceDescription \tHorizontal tab \rCarriage return \nNew line \”Double quote \\Backslash

41 Example Formatting Codes Example: FormattingExample.java public class FormattingExample { public static void main (String [] args) { System.out.print("lol\tz\n"); System.out.println("hello\rworld"); System.out.println("\"Geek\" talk slash (\\) com"); }

42 Language basics Data types ◦ 8 primitive types:  boolean, byte, short, int, long, float, double, char ◦ Class types, either provided by Java, or made by programmers  String, Integer, Array, Frame, Object, Person, Animal, … ◦ Array types Variables ◦ dataType identifier [ = Expression]: ◦ Example variable declarations and initializations: int x; x=5; boolean b = true; Frame win = new Frame(); String x = “how are you?”; int[] intArray; intArray = new int[2]; intArray[0] = 12; intArray[1] = 6; Person pArray = new Person[10];

43 Variables Variables must be declared before they can be used. Variable declaration: ◦ Creates a variable in memory. ◦ Specify the name of the variable as well as the type of information that it will store. ◦ E.g. int num ; ◦ Although requiring variables to be explicitly declared appears to be an unnecessary chore it can actually be useful for minimizing insidious logic errors. Using variables ◦ Only after a variable has been declared can it be used. ◦ E.g., num = 12;

44 Declaring Variables: Syntax Format: ; Example: char myFirstInitial; Variables can be initialized (set to a starting value) as they’re declared: char myFirstInitial = ‘j’; int age = 30;

45 Some Built-In Types Of Variables In Java TypeDescription byte8 bit signed integer short16 but signed integer int32 bit signed integer long64 bit signed integer float32 bit signed real number double64 bit signed real number char16 bit Unicode character (ASCII and beyond) boolean1 bit true or false value StringA sequence of characters between double quotes ( "" )

46 Location Of Variable Declarations public class { public static void main (String[] args) { // Local variable declarations occur here > : : }

47 Style Hint: Initializing Variables Always initialize your variables prior to using them! ◦ Do this whether it is syntactically required or not. Example how not to approach: public class OutputExample1 { public static void main (String [] args) { int num; System.out.print(num); } OutputExample1.java:7: error: variable num might not have been initialized System.out.print(num); ^

48 Boolean Tipe data boolean hanya bernilai true dan false. Digunakan untuk menguji ungkapan, dapat digunakan pada seleksi dan looping Dalam bahasa C tidak ada jenis data boolean. Biasanya 0 dan 1 (atau bukan nol) digunakan untuk mewakili nilai benar dan salah Dalam C++, jenis data bool digunakan

49 Boolean: contoh boolean lapar; lapar = true; while(lapar){ System.out.println(“Kasih Makan dong...”); lapar = false; } ◦ lapar hanya mungkin bernilai true/false. ◦ Looping while akan berhenti apabila nilai lapar bernilai false.

50 Explicit Casting Ada kalanya kita ingin menganggap variable bernilai double sebagai integer Contoh: ◦ double hasilBagi = ; ◦ int hasil = (int) hasilBagi; Nilai hasil adalah 20. Artinya terdapat data yang akan hilang.

51 Rounding/Pembulatan Dalam Java, kita bisa membulatkan suatu nilai double/float kepada integer terdekat, kita bisa menggunakan method Math.round ◦ double nilaiRata2 = ; ◦ int hasilPembulatan=(int) Math.round(nilaiRata2); Nilai hasilPembulatan ialah 21 setelah dibulatkan. Penggunaan casting (int) masih diperlukan karena nilai yang dikembalikan oleh method round berjenis long. Kita perlu tukarkan long kepada int, menggunakan casting.

52 Implicit Casting Java membolehkan penukaran hasil suatu tipe data tanpa menggunakan proses casting mengikuti urutan berikut: ◦ byte  short  int  long  float  double ◦ char  int **(dibaca: byte boleh ditukar kepada short short boleh ditukar kepada int.. dll) int x = 10; // occupies 4 bytes double y = x; // occupies 8 bytes System.out.println(y); // prints 10.0

53 Java Constants Reminder: constants are like variables in that they have a name and store a certain type of information but unlike variables they CANNOT change. Format: final = ; Example: final int SIZE = 100;

54 Location Of Constant Declarations public class { public static void main (String[] args) { // Local constant declarations occur here (more later) // Local variable declarations > : : }

55 Why Use Constants? 1. They make your program easier to read and understand populationChange = ( – ) * currentPopulation; Vs. final float BIRTH_RATE = 17.58; final float MORTALITY_RATE = ; int currentPopulation = ; populationChange = (BIRTH_RATE - MORTALITY_RATE) * currentPopulation;

56 Why Use Constants? (2) 2. It can make your program easier to maintain (update with changes). ◦ If the constant is referred to several times throughout the program, changing the value of the constant once will change it throughout the program.

57 Why Use Constants? (3) final float BIRTH_RATE = ; final float MORTALITY_RATE = ; float populationChange = 0; float currentPopulation = ; populationChange = (BIRTH_RATE - MORTALITY_RATE) * currentPopulation; if (populationChange > 0) System.out.println("Increase“) System.out.println("Birth rate:“+ BIRTH_RATE + " Mortality rate:“ + MORTALITY_RATE, " + Population change:“ + populationChange); else if (populationChange < 0) System.out.println("Decrease“); System.out.println("Birth rate:“+BIRTH_RATE, “+Mortality rate:“+ MORTALITY_RATE +"Population change:“+populationChange); else System.out.print("No change“); System.out.print("Birth rate:“+BIRTH_RATE, “+Mortality rate:“+ MORTALITY_RATE+ "Population change:“+populationChange);

58 Why Use Constants? (4) final float BIRTH_RATE = 0.5; final float MORTALITY_RATE = ; float populationChange = 0; float currentPopulation = ; populationChange = (BIRTH_RATE - MORTALITY_RATE) * currentPopulation; if (populationChange > 0) System.out.println("Increase“) System.out.println("Birth rate:“+ BIRTH_RATE + " Mortality rate:“ + MORTALITY_RATE, " + Population change:“ + populationChange); else if (populationChange < 0) System.out.println("Decrease“); System.out.println("Birth rate:“+BIRTH_RATE, “+Mortality rate:“+ MORTALITY_RATE +"Population change:“+populationChange); else System.out.print("No change“); System.out.print("Birth rate:“+BIRTH_RATE, “+Mortality rate:“+ MORTALITY_RATE+ "Population change:“+populationChange); One change in the initialization of the constant changes all references to that constant.

59 Variable Naming Conventions In Java Compiler requirements ◦ Can’t be a keyword nor can the names of the special constants: true, false or null be used ◦ Can be any combination of letters, numbers, underscore or dollar sign (first character must be a letter or underscore) Common stylistic conventions ◦ The name should describe the purpose of the variable ◦ Avoid using the dollar sign ◦ With single word variable names, all characters are lower case  e.g., double grades; ◦ Multiple words are separated by capitalizing the first letter of each word except for the first word  e.g., String firstName = “James”;

60 Java Keywords abstractbooleanbreakbytecasecatchchar classconstcontinuedefaultdodoubleelse extendsfinalfinallyfloatforgotoif implementsimportinstanceofintinterfacelongnative newpackageprivateprotectedpublicreturnshort staticsuperswitchsynchronizedthisthrowthrows transienttryvoidvolatilewhile

61 Operator **Sama seperti dalam C Operator dasar: ◦ +, -, /, *, % Contoh: ◦ bil += 5; setara dengan bil = bil + 5; (++ dan –-) ◦ Contoh: int i= 1; int x = i; //nilai x menjadi 3 //nilai i menjadi 2

62 Hubungan **Sama seperti dalam C Operator dasar: ◦ ==, !=,, = Apa bedanya? ◦ bil = 0; ◦ if(bil == 0)

63 Operator logik **Sama seperti dalam C Operator dasar: ◦ && : DAN ◦ ||: ATAU ◦ ! :BUKAN

64 Common Java Operators / Operator Precedence Precedence level OperatorDescriptionAssociativity 1expression++ expression-- Post-increment Post-decrement Right to left 2++expression --expression + - ! ~ (type) Pre-increment Pre-decrement Unary plus Unary minus Logical negation Bitwise complement Cast Right to left

65 Common Java Operators / Operator Precedence Precedence level OperatorDescriptionAssociativity 3*/%*/% Multiplication Division Remainder/modulus Left to right Addition or String concatenation Subtraction Left to right 5<< >> Left bitwise shift Right bitwise shift Left to right

66 Common Java Operators / Operator Precedence Precedence level OperatorDescriptionAssociativity 6< <= > >= Less than Less than, equal to Greater than Greater than, equal to Left to right 7= != Equal to Not equal to Left to right 8&Bitwise ANDLeft to right 9^Bitwise exclusive ORLeft to right

67 Common Java Operators / Operator Precedence Precedence level OperatorDescriptionAssociativity 10|Bitwise ORLeft to right 11&&Logical ANDLeft to right 12||Logical ORLeft to right

68 Common Java Operators / Operator Precedence Precedence level OperatorDescriptionAssociativity 13= += -= *= /= %= &= ^= |= <<= >>= Assignment Add, assignment Subtract, assignment Multiply, assignment Division, assignment Remainder, assignment Bitwise AND, assignment Bitwise XOR, assignment Bitwise OR, assignment Left shift, assignment Right shift, assignment Right to left

69 Post/Pre Operators The name of the example is: Order1.java public class Order1 { public static void main (String [] args) { int num = 5; System.out.println(num); num++; System.out.println(num); ++num; System.out.println(num); System.out.println(++num); System.out.println(num++); }

70 Post/Pre Operators (2) The name of the example is: Order2.java public class Order2 { public static void main (String [] args) { int num1; int num2; num1 = 5; num2 = ++num1 * num1++; System.out.println("num1=" + num1); System.out.println("num2=" + num2); }

71 Unary Operator/Order/Associativity The name of the example: Unary_Order3.java public class Unary_Order3.java { public static void main (String [] args) { int num = 5; float fl; System.out.println(num); num = num * -num; System.out.println(num); }

72 Accessing Pre-Created Java Libraries It’s accomplished by placing an ‘import’ of the appropriate library at the top of your program. Syntax: import ; Example: import java.util.Scanner;

73 Getting Text Input You can use the pre-written methods (functions) in the Scanner class. General structure: import java.util.Scanner; main (String [] args) { Scanner = new Scanner (System.in); =. (); } Creating a scanner object (something that can scan user input) Using the capability of the scanner object (actually getting user input)

74 Getting Text Input (2) The name of the example : MyInput.java import java.util.Scanner; public class MyInput { public static void main (String [] args) { String str1; int num1; Scanner in = new Scanner (System.in); System.out.print ("Type in an integer: "); num1 = in.nextInt (); System.out.print ("Type in a line: "); in.nextLine (); str1 = in.nextLine (); System.out.println ("num1:" +num1 +"\t str1:" + str1); }

75 Useful Methods Of Class Scanner 1 nextInt () nextLong () nextFloat () nextDouble () nextLine (); 1 Online documentation: docs.oracle.com/javase/7/docs/api/

76 Reading A Single Character Text menu driven programs may require this capability. Example: GAME OPTIONS (a)dd a new player (l)oad a saved game (s)ave game (q)uit game There’s different ways of handling this problem but one approach is to extract the first character from the string. Partial example: String s = "boo“; System.out.println(s.charAt(0));

77 Reading A Single Character Name of the (more complete example): MyInputChar.java import java.util.Scanner; public class MyInputChar { public static void main (String [] args) { final int FIRST = 0; String selection; Scanner in = new Scanner (System.in); System.out.println("GAME OPTIONS"); System.out.println("(a)dd a new player"); System.out.println("(l)oad a saved game"); System.out.println("(s)ave game"); System.out.println("(q)uit game"); System.out.print("Enter your selection: ");

78 Reading A Single Character (2) selection = in.nextLine (); System.out.println ("Selection: " + selection.charAt(FIRST)); }

79 Decision Making In Java Java decision making constructs ◦ if ◦ if, else ◦ if, else-if ◦ switch

80 Decision Making: Logical Operators Logical OperationJava AND&& OR|| NOT!

81 Decision Making: If Format: if (Boolean Expression) Body Example: if (x != y) System.out.println("X and Y are not equal"); if ((x > 0) && (y > 0)) { System.out.println("X and Y are positive"); } Indenting the body of the branch is an important stylistic requirement of Java. What distinguishes the body is either: 1.A semi colon (single statement branch) 2.Braces (a body that consists of multiple statements)

82 Decision Making: If, Else Format: if (Boolean expression) Body of if else Body of else Example: if (x < 0) System.out.println( " X is negative " ); else System.out.println( " X is non-negative " );

83 Example Program: If-Else Name of the example: BranchingExample1.java import java.util.Scanner; public class BranchingExample1 { public static void main (String [] args) { Scanner in = new Scanner(System.in); final int WINNING_NUMBER = ; int playerNumber = -1; System.out.print("Enter ticket number: "); playerNumber = in.nextInt(); if (playerNumber == WINNING_NUMBER) System.out.println("You're a winner!"); else System.out.println("Try again."); }

84 If, Else-If Format: if (Boolean expression) Body of if else if (Boolean expression) Body of first else-if : :: else if (Boolean expression) Body of last else-if else Body of else

85 If, Else-If (2) Name of the example: BranchingExample.java import java.util.Scanner; public class BranchingExample2 { public static void main (String [] args) { Scanner in = new Scanner(System.in); int gpa = -1; System.out.print("Enter letter grade: "); gpa = in.nextInt();

86 If, Else-If (3) if (gpa == 4) System.out.println("A"); else if (gpa == 3) System.out.println("B"); else if (gpa == 2) System.out.println("C"); else if (gpa == 1) System.out.println("D"); else if (gpa == 0) System.out.println("F"); else System.out.println("Invalid letter grade"); }

87 Branching: Common Mistakes Recall that for single bodies: what lies between the closing bracket of the Boolean expression and the next semi-colon is the body. if (Boolean Expression) instruction; if (Boolean Expression) instruction; if (Boolean Expression) instruction1; Instruction2; body

88 Branching: Now What Happens??? if (Boolean Expression): instruction1; instruction2;

89 Alternative To Multiple Else-If’s: Switch Format (character-based switch): switch (character variable name) { case ' ': Body break; case ' ': Body break; : default: Body } 1 The type of variable in the brackets can be a byte, char, short, int or long Important! The break is mandatory to separate Boolean expressions (must be used in all but the last)

90 Alternative To Multiple Else-If’s: Switch (2) Format (integer based switch): switch (integer variable name) { case : Body break; case : Body break; : default: Body } 1 The type of variable in the brackets can be a byte, char, short, int or long

91 Switch: When To Use/When Not To Use Benefit (when to use): ◦ It may produce simpler code than using an if- elseif (e.g., if there are multiple compound conditions)

92 Switch: When To Use/When Not To Use (2) Name of the example: SwitchExample.java import java.util.Scanner; public class SwitchExample { public static void main (String [] args) { final int FIRST = 0; String line; char letter; int gpa; Scanner in = new Scanner (System.in); System.out.print("Enter letter grade: ");

93 Switch: When To Use/When Not To Use (3) line = in.nextLine (); letter = line.charAt(FIRST); switch (letter) { case 'A': case 'a': gpa = 4; break; case 'B': case 'b': gpa = 3; break; case 'C': case 'c': gpa = 2; break;

94 Switch: When To Use/When Not To Use (4) case 'D': case 'd': gpa = 1; break; case 'F': case 'f': gpa = 0; break; default: gpa = -1; } System.out.println("Letter grade: " + letter); System.out.println("Grade point: " + gpa); }

95 Switch: When To Use/When Not To Use (5) When a switch can’t be used: ◦ For data types other than characters or integers ◦ Boolean expressions that aren’t mutually exclusive:  As shown a switch can replace an ‘if-elseif’ construct  A switch cannot replace a series of ‘if’ branches). ◦ Example when not to use a switch: if (x > 0) System.out.print(“X coordinate right of the origin”); If (y > 0) System.out.print(“Y coordinate above the origin”); ◦ Example of when not to use a switch: String name = in.readLine() switch (name) { }

96 Switch Example: Modified What happens if all the ‘ break ’ instructions have been removed?

97 STRUKTUR KAWALAN STRUKTUR PEMILIHAN ◦ if-else ◦ switch-break STRUKTUR PENGULANGAN ◦ while ◦ do-while ◦ for

98 STRUKTUR PEMILIHAN if-else if (ungkapan) kenyataan ◦ Contoh: if (skorPelajar >= 60) System.out.println(“LULUS”); ◦ Sintaksnya sama dengan C, kecuali dalam Java, ungkapan mesti bernilai boolean (true or false). ◦ Oleh itu penggalan berikut tidak dibenarkan dalam Java: int bilangan =10; if(bilangan) System.out.print(“*”);

99 STRUKTUR PEMILIHAN switch-case **sintaksnya sama seperti C ◦ Hanya boleh jenis integer dan aksara: byte, char, short, int atau long int pilihan =1; switch(pilihan){ case 1: … break; case 2:.. break; default: … break; }

100 STRUKTUR PENGULANGAN while, do-while dan for **sintaksnya sama seperti C ◦ Buatkan program Java dengan menggunakan while dan do-while bagi pseudokod di bawah: lapar = benar Selagi lapar benar tampilkan “beri makanan” lapar = false Tamat selagi

101 Loops Java Pre-test loops For While Java Post-test loop Do-while

102 While Loops Format: while (Boolean expression) Body Example: int i = 1; while (i <= 4) { // Call function createNewPlayer(); i = i + 1; }

103 For Loops Format: for (initialization; Boolean expression; update control) Body Example: for (i = 1; i <= 4; i++) { // Call function createNewPlayer(); i = i + 1; }

104 Post-Test Loop: Do-While Recall: Post-test loops evaluate the Boolean expression after the body of the loop has executed. This means that post test loops will execute one or more times. Pre-test loops generally execute zero or more times.

105 Do-While Loops Format: do Body while (Boolean expression); Example: char ch = 'A'; do { System.out.println(ch); ch++; } while (ch <= 'K');

106 Contrasting Pre Vs. Post Test Loops Although slightly more work to implement the while loop is the most powerful type of loop. Program capabilities that are implemented with either a ‘for’ or ‘do-while’ loop can be implemented with a while loop. Implementing a post test loop requires that the loop control be primed correctly (set to a value such that the Boolean expression will evaluate to true the first it’s checked).

107 Example: Post-Test Implementation Name of the example: PostTestExample.java public class PostTestExample { public static void main (String [] args) { final int FIRST = 0; Scanner in = new Scanner(System.in); char answer; String temp; do { System.out.println("JT's note: Pretend that we play our game"); System.out.print("Play again? Enter 'q' to quit: "); temp = in.nextLine(); answer = temp.charAt(FIRST); } while ((answer != 'q') && (answer != 'Q')); }

108 Example: Pre-Test Implementation Name of the example: PreTestExample.java public class PreTestExample { public static void main (String [] args) { final int FIRST = 0; Scanner in = new Scanner(System.in); char answer = ' '; String temp; while ((answer != 'q') && (answer != 'Q')) { System.out.println("JT's note: Pretend that we play our game"); System.out.print("Play again? Enter 'q' to quit: "); temp = in.nextLine(); answer = temp.charAt(FIRST); }

109 Now What Happens??? import java.util.Scanner; public class PreTestExample { public static void main (String [] args) { final int FIRST = 0; Scanner in = new Scanner(System.in); char answer = ' '; String temp; while ((answer != 'q') && (answer != 'Q')) System.out.println("JT's note: Pretend that we play our game"); System.out.print("Play again? Enter 'q' to quit: "); temp = in.nextLine(); answer = temp.charAt(FIRST); }

110 Array Sintaks ◦ Tipe_data[] nama_variable = new tipe_data[ukuran]; Contoh : ATAU int[] tts = new int[100]; ATAU int[] tts; ATAU tts = new int[100]; ATAU int tts[]= new int[100];

111 Array (2) Memberi nilai kepada array: int[] nilai = {2, 3, 4, 5}; char[] abjad= {a, b, c, d}; Kita juga bisa membuat array tanpa nama : new int[]{2, 3, 5, 7, 11}; menyediakan satu array baru dengan nilai-nilai tersebut. Sering dipakai untuk mengirim parameter ke method.

112 Array (3) Digunakan apabila kita ingin mengirimkan array sebagai parameter pada method. cetakLimaPrima(new int[] {2,3,5,7,11} ); int[] nomPrima = {2,3,5,7,11}; cetakLimaPrima(nomPrima); ATAU

113 Array Sebagai Objek Apabila ia dianggap sebagai objek, maka ia mempunyai atribut dan method Atribut length ◦ Menentukan ukuran suatu array: nama_array.length int nomPrima={2, 3, 5, 7, 11}; for(int i=0; i

114 Method arraycopy() ◦ Mengcopy dari satu array ke array yang lain. Sintaksnya: ◦ System.arraycopy(sumber,indekSumber,sasaran, indekSasaran,bil); sumber : nama array yang hendak dicopy indekSumber : permulaan kedudukan array yang akan di copy dari sumber sasaran : array baru yang akan menyimpan kandungan array sumber indekSasaran : permulaan kedudukan pada array sasaran untuk menyimpan nilai yang dicopy bil : jumlah nilai yang dicopy

115 Metod arraycopy() int[] nomGanjil ={1, 3, 5, 7, 9}; int[] nomPositif={10, 20, 30, 40, 50, 60}; System.arraycopy(nomGanjil, 1, nomPositif, 2, 3); for(int i=0; i

116 System.arraycopy(nomGanjil, 1, nomPositif, 2, 3); Sebelum copy Selepas copy

117 String Berbeda dengan C, Java mempunyai kelas String. Kita tidak perlu tipe data array char untuk menyimpan rentetan aksara. Tipe data berjenis String akan menyimpan aksara di antara tanda “ “, termasuk ruang kosong ◦ Contoh: String kosong=“”; //suatu rentetan kosong ◦ String namaSaya = “Mohammad Muktasim”;

118 Operasi Terhadap String Menggabung string ◦ Menggunakan operator ‘+’ String judul = “OO”; String buku = “.Java”; String judulBuku = judul + buku; System.out.println(judulBuku); OUTPUT OO.Java //tanpa spasi

119 Operasi Terhadap String Substring ◦ Mendapatkan sebahagian daripada string yang lengkap ◦ Metod substring() digunakan String senikata = “Puji dan syukur kepada Ilahi”; String s = senikata.substring(0,4); System.out.println(“Subrentetan bernilai ”+s); Java mengira subrentetan bermula dari 0 hingga 4 0: kedudukan ‘P’ 4: kedudukan ‘i’ OUTPUT Subrentetan bernilai Puji

120 Operasi Terhadap String Panjang string ◦ Mendapatkan panjang suatu string ◦ Metod length() digunakan String kata = “Salam Sejahtera”; int panjang = kata.length(); // panjang bernilai 15 Membanding string ◦ Menguji apakah dua string mempunyai nilai yang sama ◦ Metod equals() digunakan “salam”.equals(kata); // bernilai false “Salam sejahtera”.equalIgnoreCase(kata); // bernilai true

121 Method parser Contoh: weight = Integer.parseInt(kilo); Nilai yang berjenis String yang disimpan dalam kilo akan ditukar menjadi integer dan disimpan dalam weight Jenis parser yang lain: ◦ parseInt(), parseFloat(), parseLong(), parseDouble, parseShort(), parseByte().

122 Many Pre-Created Classes Have Been Created Rule of thumb: Before writing new program code to implement the features of your program you should check to see if a class has already been written with the features that you need. The Java API is Sun Microsystems's collection of pre-built Java classes: ◦ docs.oracle.com/javase/7/docs/api/ docs.oracle.com/javase/7/docs/api/

123 I hear, I forget I write, I remember I do, I understand.. so.. just do it! :-)

124 Supplemental reading Getting Started Nuts and bolts of the Java Language Compiling and Running a Simple Program ava1/compile.html


Download ppt "Introduction to Java Viska Mutiawani, M.Sc. Java: History Computers of the past."

Similar presentations


Ads by Google