Presentation is loading. Please wait.

Presentation is loading. Please wait.

Basic Concepts Mehdi Einali Advanced Programming in Java 1.

Similar presentations


Presentation on theme: "Basic Concepts Mehdi Einali Advanced Programming in Java 1."— Presentation transcript:

1 Basic Concepts Mehdi Einali Advanced Programming in Java 1

2 2 agenda Review User input Scanner Strong type checking Other flow-control structures switch break & continue Strings Arrays

3 3 review Variables Primitive data types Operators Methods Parameter passing Call by value Conditions If, else, else if Loops while do-while for

4 4 Variables Variables defined and initialized

5 5 Variables 2 types of variables Class variables(Fields) Local variables Method Variable Method parameter Block Variable There is no global variables Java use static binding for variables

6 6 Variables A variable always refers to its nearest enclosing binding.(Scoping)

7 7 User Input Print on console System.out.println How to read from console? Scanner Example: Scanner scanner = new Scanner(System.in); int n = scanner.nextInt(); double d = scanner.nextDouble();

8 8 Example Scanner scanner = new Scanner(System.in); int a = scanner.nextInt(); int b = scanner.nextInt(); long pow = power(a,b); System.out.println(pow);

9 9 Type Checking Java has a strong type-checking mechanism Some assignment is not permitted int intVal = 2; long longVal =12; intVal = longVal;  Syntax Error longVal = intVal;  OK intVal = (int)longVal;  OK (Type Casting)

10 10 Direct Type cast The arrows are transitive All other conversions need an explicit cast boolean is not convertible char is a special type

11 11 Type Conversion Grid

12 12 Type Conversion N : the conversion cannot be performed Y : the conversion is performed automatically and implicitly by Java C : the conversion is a narrowing conversion and requires an explicit cast Y* : the conversion is an automatic widening conversion, but that some of the least significant digits of the value may be lost by the conversion

13 13 Example i = 123456789; //a big integer f = i; //f stores and approximation of i System.out.println(f);//output : 1.23456792E8 i = (int) f; System.out.println(i); //output : 123456792 floating-point types are approximations of numbers They cannot always hold as many significant digits as the integer types

14 14 Comparison Compare doubles Using == with float or double is an anti- pattern An infinite loop: for (float f = 10f; f != 0; f -= 0.1) { System.out.println(f); }

15 15 Numeric Assignments Numeric Suffix Double d = 123.54d; Float f = 123f; Long l = 123123 l; byte b = 127;//Nothing Assignment Overflow Large long to int Lower bits are used No runtime error Large double to integer Brings a max int

16 16 Operators and cast Division (“/”) operates differently on integers and on doubles!

17 17 Flow controls

18 18 Structured programming Sequence Selection If-else switch-case Iteration for while do-while

19 19 Block Sometimes a group of statements needed to be executed in all or nothing manner It is same as single statement and can be replaced with a method

20 20 Block Variable

21 21 If-else Braces is optional for single statement Remember: place braces for clarify for indentation else will bind to last if

22 22 Short cut Boolean evaluation && vs &, || vs |

23 23 Loop-1 Constructs Initialize Step Termination condition

24 24 Loop-2 Watch out infinite loop

25 25 Switch statement switch (i) { case 1: System.out.println("1"); break; case 2: System.out.println("2"); break; default: System.out.println("default"); }

26 26 Break Jump out of loop block

27 27 Continue Stops the execution of the body of the loop and continues from the beginning of the loop

28 28 Nested loop outer: for (int i = 0; i < 10; i++){ inner: for (int j = 0; j < 10; j++) { if (j == 2){ break outer; } else { System.out.println(i); System.out.println(j); continue inner; }

29 29 Switch without break 0123445678901234456789

30 30 Comments Comments are ignored by compiler One-line comment //nextInt = scanner.nextInt(); Multiple-line comment /*nextInt = scanner.nextInt(); for(int i=0;i<nextInt;i++){ System.out.println(i); } */ Javadoc comments /** *... text... */

31 31 String

32 32 String A sequence of characters Character: char ch = ‘a’; char ch = ‘1’; char ch = ‘#’; Strings: String st = “Ali”; String st = “123”; String st = “1”; String st = “”; String is not a primitive type

33 33 String String in C and C++ char* and char[] \0 at the end of String Some functions strlen, strcpy, … String in java is a class String in java is not equal to char[] Constant strings “salam!” “Hellow World!”

34 34 String and other types String input = "Nader and Simin, A Separation"; char ch = input.charAt(0); int i = input.indexOf("Nader"); int j = input.lastIndexOf("Simin"); String newS = input.replace("Separation", "Reconciliation"); String sth = newS + ch + i + j; System.out.println(sth);

35 35 String methods charAt concat  plus (+) operator contains startsWith endsWith indesxOf  first index of sth lastIndexOf replace substring length split

36 36 Immutable String String in java is an immutable class After creating a string, you can not change it If you want to change it, you should create a new string There is no such methods for strings: setCharAt(int) setValue(String) Methods like replace and replaceAll, do not change the value They return a new String

37 37 example What is the output of this code? String str = "Gholi"; str.replaceAll("li", "lam"); System.out.println(str); String str = "Gholi"; String replaced = str.replaceAll("li", "lam"); System.out.println(replaced);

38 38 Data Hierarchy Bit Byte Character Word

39 39 Java Characters Some characters are special characters Special characters are shown using backslash Examples: New line: \n Tab : \t Double-quote : \” Single-quote : \’ Backslash : \\

40 40 Arrays

41 41 Array Collections of related data items related data items of the same type Arrays are fixed-length entities they remain the same length once they are created An array is a group of variables called elements containing values that all have the same type The position number of the element is it’s index Array elements are sequentially located in memory

42 42

43 43 samples Create an array of 10 integer elements int[] array = new int[10]; int array[] = new int[10];//equal Create an array of n characters char[] characters = new char[n]; Change value of 5’th element array[5] = 12; Retrieving value of n’th element char ch = array[n];

44 44 Array Creation Shortcut char[] array = new char[3]; array[0] = 'a'; array[1] = 's'; array[2] = 't'; The above code can be rewritten as: char[] array = {'a','s','t'}; Other examples: int[] numbers = {1,2,3,5,9,123}; boolean[] b = {true, true, false, true};

45 45 Multidimensional Arrays int[][] matrix = new int[3][4]; matrix[2][3] = 2; System.out.println(matrix[2][1]);

46 46 Unbalanced Multidimensional Array int[][] matrix = new int[3][]; matrix[0] = new int[2]; matrix[1] = new int [5]; matrix[2] = new int [4]; matrix[2][3] = 2; System.out.println(matrix[2][1]); matrix[0][3] = 2;//Runtime Error ArrayIndexOutOfBoundsException

47 47 Quiz (5 min ) a)-ab@d b)-ab@d@ c)-a@d@ d)-abd@ e)exception

48 48 end


Download ppt "Basic Concepts Mehdi Einali Advanced Programming in Java 1."

Similar presentations


Ads by Google