Download presentation
Presentation is loading. Please wait.
1
Advanced Programming in Java
Basic Concepts Mehdi Einali
2
agenda Review User input Strong type checking
Scanner Strong type checking Other flow-control structures switch break & continue Strings Arrays
3
review Variables Operators Methods Conditions Loops
Primitive data types Operators Methods Parameter passing Call by value Conditions If, else, else if Loops while do-while for
4
Variables Variables defined and initialized
5
Variables 2 types of variables There is no global variables
Class variables(Fields) Local variables Method Variable Method parameter Block Variable There is no global variables Java use static binding for variables Block variable can be defined only when there not upper scope variable in method
6
Variables A variable always refers to its nearest enclosing binding.(Scoping)
7
User Input Print on console How to read from console? Scanner Example:
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
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
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
Direct Type cast The arrows are transitive
All other conversions need an explicit cast boolean is not convertible char is a special type
11
Type Conversion Grid
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
Example floating-point types are approximations of numbers
i = ; //a big integer f = i; //f stores and approximation of i System.out.println(f);//output : E8 i = (int) f; System.out.println(i); //output : floating-point types are approximations of numbers They cannot always hold as many significant digits as the integer types
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
Numeric Assignments Numeric Suffix Assignment Overflow
Double d = d; Float f = 123f; Long l = 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
Operators and cast Division (“/”) operates differently on integers and on doubles!
17
Flow controls
18
Structured programming
Sequence Selection If-else switch-case Iteration for while do-while
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
Block Variable
21
If-else Braces is optional for single statement
Remember: place braces for clarify for indentation else will bind to last if
22
Short cut Boolean evaluation
&& vs & , || vs |
23
Loop-1 Constructs Initialize Step Termination condition
24
Watch out infinite loop
25
Switch statement switch (i) { case 1: System.out.println("1"); break;
default: System.out.println("default"); }
26
Break Jump out of loop block
27
Continue Stops the execution of the body of the loop and continues from the beginning of the loop
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
1 2 3 4 5 6 7 8 9 Switch without break
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
String
32
String A sequence of characters Character: Strings:
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
String String in C and C++ Some functions String in java is a class
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
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
String methods charAt concat plus (+) operator contains startsWith
endsWith indesxOf first index of sth lastIndexOf replace substring length split
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
example What is the output of this code? String str = "Gholi";
str.replaceAll("li", "lam"); System.out.println(str); String replaced = System.out.println(replaced);
38
Data Hierarchy Bit Byte Character Word
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
Arrays
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
43
samples char ch = array[n]; 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
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
Multidimensional Arrays
int[][] matrix = new int[3][4]; matrix[2][3] = 2; System.out.println(matrix[2][1]);
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
Quiz (5min) e)exception b
48
end
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.