1
Basic Concepts
Mehdi Einali
Advanced Programming in Java
2
agendaReviewUser input
ScannerStrong type checkingOther flow-control structures
switchbreak & continue
StringsArrays
3
reviewVariables
Primitive data typesOperatorsMethods
Parameter passingCall by value
ConditionsIf, else, else if
Loopswhiledo-whilefor
4
VariablesVariables defined and initialized
5
Variables2 types of variables
Class variables(Fields)Local variables
Method VariableMethod parameterBlock Variable
There is no global variablesJava use static binding for variables
6
VariablesA variable always refers to its nearest enclosing binding.(Scoping)
7
User InputPrint on console
System.out.printlnHow to read from console?ScannerExample:
Scanner scanner = new Scanner(System.in);int n = scanner.nextInt();double d = scanner.nextDouble();
8
ExampleScanner scanner = new Scanner(System.in);
int a = scanner.nextInt();int b = scanner.nextInt();long pow = power(a,b);System.out.println(pow);
9
Type CheckingJava has a strong type-checking mechanismSome assignment is not permitted
int intVal = 2;long longVal =12;
intVal = longVal;Syntax ErrorlongVal = intVal;OKintVal = (int)longVal; OK (Type Casting)
10
Direct Type castThe arrows are transitiveAll other conversions need an explicit castboolean is not convertiblechar is a special type
11
Type Conversion Grid
12
Type ConversionN : the conversion cannot be performedY : the conversion is performed automatically and implicitly by JavaC : the conversion is a narrowing conversion and requires an explicit castY* : 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
Examplei = 123456789; //a big integerf = i; //f stores and approximation of iSystem.out.println(f);//output : 1.23456792E8i = (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
ComparisonCompare doublesUsing == with float or double is an anti-patternAn infinite loop:
for (float f = 10f; f != 0; f -= 0.1) {System.out.println(f);
}
15
Numeric AssignmentsNumeric Suffix
Double d = 123.54d;Float f = 123f;Long l = 123123 l; byte b = 127;//Nothing
Assignment OverflowLarge long to int
Lower bits are usedNo runtime error
Large double to integerBrings a max int
16
Operators and castDivision (“/”) operates differently on integers and on doubles!
17
Flow controls
18
Structured programmingSequence
SelectionIf-elseswitch-case
Iterationforwhiledo-while
19
BlockSometimes a group of statements needed tobe executed in all ornothing 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 statementRemember: place braces for clarify for indentation
else will bind to last if
22
Short cut Boolean evaluation
&& vs & , || vs |
23
Loop-1Constructs
InitializeStepTermination condition
24
Loop-2
Watch out infinite loop
25
Switch statementswitch (i) {case 1:
System.out.println("1");break;
case 2:System.out.println("2");break;
default:System.out.println("default");
}
26
BreakJump out of loop block
27
ContinueStops the execution of the body of the loop and continues from the beginning of the loop
28
Nested loopouter: 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
Switch without break01234456789
30
CommentsComments are ignored by compilerOne-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
StringA sequence of charactersCharacter:
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
StringString in C and C++
char* and char[]\0 at the end of String
Some functionsstrlen, strcpy, …
String in java is a classString in java is not equal to char[]Constant strings
“salam!”“Hellow World!”
34
String and other typesString 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 methodscharAtconcat plus (+) operatorcontainsstartsWithendsWithindesxOf first index of sthlastIndexOfreplacesubstringlengthsplit
36
Immutable StringString in java is an immutable classAfter creating a string, you can not change itIf you want to change it, you should create a new stringThere 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
exampleWhat 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
Data HierarchyBitByteCharacterWord
39
Java CharactersSome characters are special charactersSpecial characters are shown using backslashExamples:
New line: \nTab : \tDouble-quote : \”Single-quote : \’Backslash : \\
40
Arrays
41
ArrayCollections of related data itemsrelated data items of the same typeArrays are fixed-length entities they remain the same length once they are createdAn array is a group of variables
called elementscontaining values that all have the same typeThe position number of the element is it’s indexArray elements are sequentially located in memory
42
43
samplesCreate an array of 10 integer elements
int[] array = new int[10]; int array[] = new
int[10];//equalCreate 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 Shortcutchar[] 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 Arraysint[][] 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)
a)-ab@db)-ab@d@c)-a@d@d)-abd@e)exception
48
end