1 / 42

apds1

this is a test

guest97497
Download Presentation

apds1

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. Lesson Objectives • By the end of this lecture, you should understand • the following: • How to create, compile and run Java programs • Primitive data types • Write simple programs using primitive data • types, conditional statements, loops and • functions

  2. Introduction • Java programming language • Created by Sun Microsystems and released in 1995 • Features: • Object-oriented • Both complied and interpreted • Platform-independent

  3. What is Object -Oriented • Organising a program as a collection of discrete Objects • Objects in the problem domain are mapped to • objects in the program

  4. Development Software • Java Development Kit (JDK) • Freely available for most platforms • Consists of: • Compiler – javac • Interpreter – java • Utilities (debugger, …)

  5. Syntax of Java Program • Java programs are defined as classes • // import statements (if any) • public class ClassName { • public static void main(String[] args) { • // Statements • } } • All statements end with a semicolon ; • ClassName is an identifier • Identifiers can be composed of letters, numbers, ‘_’ and ‘$’ • Identifiers may only begin with a letter, ‘_’ or ‘$’ • Java is case-sensitive • Java program files are saved with their exact class name, • matching character case, and with extension “.java”

  6. Example of a Java Program public class WelcomeApp { public static void main(String [] args) { System.out.println(“Hello World!”); } }

  7. Variables • Variables can be considered as entities that have the following three properties – Name – Type – Value • Java has two types of variables – Native (primitive) types – Object types They have different behavior when passed as arguments to functions

  8. Variables • All variables must be declared before use • Syntax: • dataTypevariableName; • A variable name is an identifier; Spaces are not allowed • By convention, always begin your variable names with a letter, not “$” or “_” • Primitive data types: int, long, float, double, boolean, char, ...

  9. Question • Identify the legal identifiers and the illegal identifiers • Age • 123abc • $salary • -salary • _value • __1_value • legal identifiers:age, $salary, _value, __1_value • illegal identifiers : 123abc, -salary

  10. Operators

  11. Operators

  12. Operators Precedence

  13. Input Statement • Simple way of reading input with this object is to use it to create a Scanner object. First has to import the library • importjava.util.Scanner; • Scanner scanIn = new Scanner(System.in); • System.in means that input will be from the Java console window • Scanner class reads the input stream and divides it into tokens, which are contiguous strings of characters separated by delimiters (default delimeter– whitespace)

  14. Input statement next() • Scanner class has the following methods: • hasNext(): Returns true if there’s another token in the input stream • next(): Returns the next token string in the input stream; generated an error if there are no more tokens • Resulting tokens may also be converted into values of different types using the various next Methods • Example: nextInt() allows the user read a number from System.in

  15. Input sample code • import java.util.Scanner;public class SampleIO {        // Below is the main method.        public static void main(String[] args) {                String firstName;              Scanner s = new Scanner(System.in);                // Prompt the user for some inputSystem.out.println("What is your first name?");firstName = s.next();        }}

  16. Additional input • import java.util.Scanner;public class SampleIO {        public static void main(String[] args) {                String firstName;                String lastName;                Scanner s = new Scanner(System.in);System.out.println("What is your first name?");firstName = s.next();System.out.println("What is your last name?");lastName = s.next(); System.out.print("Your full name is " + firstName + " " + lastName);        }} Output with concatenation

  17. Inputting int value • public static void main(String[] args) { • int x; • Scanner s = new Scanner(System.in); • x=s.nextInt(); • }

  18. Conditional Statements • It tells your program to execute a certain section of code only if a particular test evaluates to true. • if..then statement • if..then..else statement • switch statement

  19. If statements if (condition) { // statements } Note: The curly brackets ‘{ }’ may be omitted if there is only one statement in the body of the if statement. Example: if(x > 10) { System.out.println(x + “ is greater than 10.”); }

  20. If..else statement • if (condition) { • // statements • } else { • // statements • } • Example: if(x > 10) System.out.println(x + “ is greater than 10.”); else System.out.println(x + “ is less than or equal to 10.”);

  21. Conditional Operator if (a > b) { max = a; } else { max = b; } • Equivalent statement using the conditional operator: • max = (a > b) ? a : b;

  22. Conditional operator example public class Test { public static void main(String args[]){ inta , b; a = 10; b = (a == 1) ? 20: 30; System.out.println( "Value of b is : " + b ); b = (a == 10) ? 20: 30; System.out.println( "Value of b is : " + b ); } } Value of b is : 30 Value of b is : 20

  23. Switch Statement switch (variableName) { case value1: // statements break; case value2: // statements break; ... default: // statements break; }

  24. Switch Example switch(num) { case 10: System.out.println(“You scored an ‘A’!!!”); break; case 9: System.out.println(“You scored a ‘B’!!!”); break; case 8: System.out.println(“You scored a ‘C’!!!”); break; default: System.out.println(“Invalid score!!!”); break; }

  25. If..else demo

  26. Loop statements • when we need to execute a block of code several number of times. Java has very flexible three looping mechanisms. • while loop • do..while loop • for loop

  27. While loop while (condition) { // statement(s) } Example: Scanner scanIn = new Scanner(System.in); num = scanIn.nextInt(); while (num != 0) { System.out.println(num*num); num = scanIn.nextInt(); }

  28. While loop example • public class Test { • public static void main(String args[]) • { int x = 10; • while( x < 20 ) { System.out.println("value of x : " + x ); • x++; } • } • } • value of x : 10 • value of x : 11 • value of x : 12 • value of x : 13 • value of x : 14 • value of x : 15 • value of x : 16 • value of x : 17 • value of x : 18 • value of x : 19

  29. Do while do { // statement(s) } while (expression); Note: The difference between do-while and while is that do-while evaluates its expression at the bottom of the loop instead of the top. Statements within the do block are always executed at least once. do { num = scanIn.nextInt(); System.out.println(num*num); } while (num != 0);

  30. Question • Rewrite the code on slide 24 using a do..while construct so that you get the same output. • public class Test { • public static void main(String args[]){ • int x = 10; • do{ • System.out.println("value of x : " + x ); • x++; • }while( x < 20 ); • } • }

  31. For loop • for (initialisation; condition; increment){ • // loop body • } • Notes: • initialisationexpression initialises the loop; it‘s executed once, as the loop begins. • When the expression evaluates to false, the loop terminates. • The increment expression is invoked after each iteration through the loop; it is perfectly acceptable for this expression to increment or decrement a value.

  32. Flow in for loop • The initialization step is executed first(only once). This step allows you to declare and initialize any loop control variables. • Next, the Boolean expression is evaluated. If it is true, the body of the loop is executed. If it is false, the body of the loop does not execute and flow of control jumps to the next statement past the for loop. • After the body of the for loop executes, the flow of control jumps back up to the update statement. This statement allows you to update any loop control variables. This statement can be left blank, as long as a semicolon appears after the Boolean expression. • The Boolean expression is now evaluated again. If it is true, the loop executes and the process repeats itself (body of loop, then update step,then Boolean expression). After the Boolean expression is false, the for loop terminates.

  33. For loop example • Example: for(int i = 0; i < 4; i++){ System.out.println(i); }

  34. Question • Rewrite the code on slide 24 using a for … construct so that you get the same output. public class Test { public static void main(String args[]) { for(intx = 10; x < 20; x = x+1) { System.out.println("value of x : " + x ); } } }

  35. Break • The break keyword is used to stop the entire loop, must be used inside any loop or a switch statement. • The break keyword will stop the execution of the innermost loop and start executing the next line of code after the block. public class Test { public static void main(String args[]) { for(int x=10;x<=50;x=x+10) { if( x == 30 ) { break; } System.out.println( x ); } } } Output: 10 20

  36. Continue • The continuekeyword causes the loop to immediately jump to the next iteration of the loop. • In a for loop, the continue keyword causes flow of control to immediately jump to the update statement. • In a while loop or do/while loop, flow of control immediately jumps to the Boolean expression. public class Test { public static void main(String args[]) { for(intx=10;x<=50;x=x+10) { if( x == 30 ) { continue; } System.out.println( x ); } } } Output: 10 20 40 50

  37. Method • A method definition consists of a method header and a method body. Here are all the parts of a method: • Modifiers: The modifier, which is optional, tells the compiler how to call the method. This defines the access type of the method. • Return Type: A method may return a value. The returnValueType is the data type of the value the method returns. Some methods perform the desired operations without returning a value. In this case, the returnValueType is the keyword void. • Method Name: This is the actual name of the method. The method name and the parameter list together constitute the method signature. • Parameters: A parameter is like a placeholder. When a method is invoked, you pass a value to the parameter. This value is referred to as actual parameter or argument. The parameter list refers to the type, order, and number of the parameters of a method. Parameters are optional; that is, a method may contain no parameters. • Method Body: The method body contains a collection of statements that define what the method does.

  38. Function/method public static returnTypemethodName(list of arguments and their type){ // body of method }

  39. Calling a method • In creating a method, you give a definition of what the method is to do. • To use a method, you have to call or invoke it. There are two ways to call a method; the choice is based on whether the method returns a value or not. • When a program calls a method, program control is transferred to the called method. A called method returns control to the caller when its return statement is executed or when its method-ending closing brace is reached. • If the method returns a value, a call to the method is usually treated as a value. • For example: • int larger = max(30, 40);

  40. Calling Method Example public class TestMax{ public static void main(String[] args) { inti = 5; int j = 2; intk = max(i, j); System.out.println("The maximum between " + i + " and " + j + " is " + k); } public static int max(int num1, int num2) { int result; if (num1 > num2) result = num1; else result = num2; return result; } }

  41. Void Keyword • public class TestVoidMethod { • public static void main(String[] args) { • printGrade(78.5); } • public static void printGrade(double score) { • if (score >= 90.0) { • System.out.println('A'); } • else if (score >= 80.0) • { System.out.println('B'); } • else if (score >= 70.0) { System.out.println('C'); } • else if (score >= 60.0) { System.out.println('D'); } • else { System.out.println('F'); } • } }

More Related