LECTURE 1: JAVA BASICS INF 2105: Software Application Development LECTURER :MR. AKRAM ALI OMAR EMAIL: akram.ali.omar@gmail.com Mobile: 0778695626 1
LECTURE 1: JAVA BASICS Write Once, Run Everywhere 2
Java’s origins  Work on java started in 1991  The goal: a new portable language  Original name: Oak  Original tagline: Write Once, Run Everywhere 3
The history of java 4
The History of Java 5
Runtime Architecture  Java is an interpreted language  It compiles to bytecode instead of machine language  The compiled application is portable between platforms without recompiling  Byte code is interpreted, Java code can be executed anywhere an interpreter is available.  The "Interpreter" is call the Java Virtual Machine 6
 Traditionally, source code had to be compiled for the target hardware and OS platform: The Java Virtual Machine. 7
The Java Virtual Machine.  Java source files (.java) are compiled to Java bytecode (.class)  Bytecode is interpreted on the target platform within a Java Virtual Machine  The Java VM does more than interpret bytecode:  The class loader loads appropriate java classes  All classes are verified to contain only legal bytecodes and not permitted any illegal stack or register usage 8
How it works…! 9
Java Editions  Java Platform, Standard Edition(SE) Standard for core language and runtime environment(JRE)  Java Platform, Enterprise Edition(EE) Standard for building industrial-strength web applications  Java Platform, Micro Edition (ME) Micro-controllers, sensors, and mobile devices 10
Java SE Development Kit(JDK)  Availablee at no cost from Oracle  Includes tools for compilation and packaging  java: runtime  javac: compiler  javadoc: docs builder  jar: archive builder 11
Choosing a Development Environment  Any text editor will do it  But many java IDEs are available  On OS X  BDEdit and TextWrangler: not a java “specialis”t IDE • On windows:  TextPad  JCreator 12
Top Cross- Platform IDEs  NetBeans  Excellent support for JEE development  Also supports C, C++, and PHP  Eclipse with Java Developer tools  Free and open source  Distributions for many languages and platform  IntelliJ IDEA  Free “community” edition, paid “pro” edition  Foundation of Google’s Android Studio 13
Java Basic Syntax JAVA CLASSES: • All code is defined in classes • Classes are defined in source code files with .java extension • The javac command compiles Java code into bytecode • The java command runs compiled bytecode files. 14
Java Basic Syntax Simple Java Program: – Let us look at a simple code that would print the words ”I rule!”. public class MyFirstApp { public static void main(String []args) { System.out.println("I rule!"); } } Class declaration Main method Executable code 15
16
how to save the file, compile and run the program. • Let's look at how to save the file, compile and run the program. Please follow the steps given below: • Open notepad and add the code as above. • Save the file as: MyFirstApp.java. 17
how to save the file, compile and run the program. • Open a command prompt window and go o the directory where you saved the class. Assume it's C:. • Type ' javac MyFirstApp.java ' and press enter to compile your code. If there are no errors in your code, the command prompt will take you to the next line (Assumption : The path variable is set). 18
how to save the file, compile and run the program. • Now, type ' java MyFirstApp' to run your program. • You will be able to see ‘I rule!' printed on the window. 19
Parsing Arguments to a console application public class MyFirstApp { public static void main(String []args) { System.out.println("I rule!"); System.out.println(args[0]); } } 20
COMMENTS IN JAVA – Comments start with: // • Comments ignored during program execution • Document and describe code • Provides code readability – Multiple line comments: /* ... */ /* This is a multiple line comment. It can be split over many lines */ – Another line of comments – Note: line numbers not part of program, added for reference 21
Basic Syntax: • About Java programs, it is very important to keep in mind the following points. • Case Sensitivity – Java is case sensitive, which means identifier Hello and hello would have different meaning in Java. • White space – white space doesn’t affect interpretation of code – space, tabs, and line feeds are “collapsed” by compiler – All statements must end with must end with semicolon(;). 22
Basic Syntax: • Class Names – For all class names the first letter should be in Upper Case. – If several words are used to form a name of the class, each inner word's first letter should be in Upper Case. – Example class MyFirstApp 23
Basic Syntax: • Method Names – All method names should start with a Lower Case letter. – If several words are used to form the name of the method, then each inner word's first letter should be in Upper Case. Example public void myMethodName() • public static void main(String args[]) – Java program processing starts from the main() method which is a mandatory part of every Java program. • Constants are all uppercase 24
Basic Syntax: • Program File Name – Name of the program file should exactly match the class name. – When saving the file, you should save it using the class name (Remember Java is case sensitive) and append '.java' to the end of the name (if the file name and the class name do not match your program will not compile). – Example : Assume 'MyFirstApp' is the class name. Then the file should be saved as' MyFirstApp.java' 25
Java Identifiers: • All Java components require names. Names used for classes, variables and methods are called identifiers. • In Java, there are several points to remember about identifiers. They are as follows: • All identifiers should begin with a letter (A to Z or a to z), currency character ($) or an underscore (_). 26
Java Identifiers: • After the first character identifiers can have any combination of characters. • A key word cannot be used as an identifier. https://docs.oracle.com/javase/tutorial/java/nutsandbolts/_keywords.html • Most importantly identifiers are case sensitive. • Examples of legal identifiers: age, $salary, _value, __1_value • Examples of illegal identifiers: 123abc, -salary 27
Using Character Escape Codes • There are some characters that will cause problems in your code if typed explicitly, such as the carriage return or double • Quotation mark. Typing these directly into your code where you want them to print is problematic and would most likely cause compiler errors. • For example System.out.println(“Some people call me “Joey”.”); //compile error 28
CHARACTER ESCAPE CODES System.out.println(“Some people call me ”Joey”.”); //no error 29
Primitive Types and Variables • Boolean, char, byte, short, int, long, float, double etc. • These basic (or primitive) types are the only types that are not objects (due to performance issues). • This means that you don’t use the new operator to create a primitive variable • Declaring primitive variables: float initVal; int retVal = 2; double gamma = 1.2; boolean valueOk = false; 30
Primitive Types and Variables 31
Primitive Variable & Reference Variable • When you think of java variable, think of a container that holds something. • This container (java variable) has size and a type. • Primitive containers (variables) have different sizes and those sizes have names. • Each primitive variable has a fixed number of bits (container size). • A cups´size analogy of the six numeric primitives variables in Java are shown below 32
Primitive Variable & Reference Variable • Java cares about types, you can´t put different things in a different type of a container. E.g. Rabbit b = new Giraffe(); Don´t expect this to compile!!! • You can´t put a large value into a small byte b = 1500; // this will never work. 33
Primitive Variable & Reference Variable • You know how to declare a primitive variable and assign it a value. • But now what about non-primitive variables? In other words, what about objects? • There is actually no such thing as an object variable, there's only an object reference variable. • It doesn't hold the object itself, It holds bits that represent a way to access an object • You can't put (store) an object into a variable. 34
35
Initialisation • If no value is assigned prior to use, then the compiler will give an error • Java sets primitive variables to zero or false in the case of a Boolean variable • All object references are initially set to null • An array of anything is an object – Set to null on declaration – Elements to zero false or null on creation 36
MEMORY MANAGEMENT AND GARBAGE COLLECTION • Objects are born and objects die. You're in charge of an object's Iifecycle. • You decide when and how to construct it.You decide when to destroy It. • Except you don't actually destroy the object yourself, you simply abandon it. But once it 's abandoned, the heartless Garbage Collector, can vaporize it, reclaiming the memory that object was using . • When writing java programs, you will be creating objects. Sooner or later, you´ve to let some of them go, or risk running out of RAM. 37
The Stack and the Heap: Where things live • When a JVM starts up, it gets a chunk of memory from the underlying OS, and uses it to run your Java program. • In java, we (programmers) care about two areas of memory – The one where objects live (the heap), and the one where method invocations and local variables live (the stack). 38
MATHEMATICAL OPERATORS: • INTEGER MATH • FLOATING POINT MATH 39
Operator Precedence • Operator precedence determines the order in which operations are applied to numbers. • In general, multiplication (*), division (/), and modulus (%) have precedence over addition (+) and subtraction (–). • This means that multiplication, division, and modulus operations are evaluated before addition and subtraction. When operator precedence is the same, operations occur from left to right 40
Operator Precedence Example int x = 10 – 4 + 14 / 2; • The value of x will be 10 if it evaluated strictly left to right. 10 – 4 = 6; 6 + 14 = 20; 20 / 2 = 10. • Because the division operator is evaluated first, the value of this expression is 13. (10 – 4 + 7 = 13). • Therefore the correct value of x is 13; 41
Enforcing operator precedence • There is a way to force operator precedence using parentheses (like in Algebra). • The operations within parentheses have precedence int y = (10 – 4 + 14) / 2; 42
43 Relational and Conditional Operators • Compares two values and determines the relationship between them Operator Use Returns true if > op1 > op2 op1 is greater than op2 >= op1 >= op2 op1 is greater than or equal to op2 < op1 < op2 op1 is less than op2 <= op1 <= op2 op1 is less than or equal to op2 == op1 == op2 op1 and op2 are equal != op1 != op2 op1 and op2 are not equal
44 Relational and Conditional Operators • Used to construct decision making expressions Operator Use Returns true if && op1 && op2 op1 and op2 are both true, conditionally evaluates op2 || op1 || op2 either op1 or op2 is true, conditionally evaluates op2 ! ! op op is false & op1 & op2 op1 and op2 are both true, always evaluates op1 and op2 | op1 | op2 either op1 or op2 is true, always evaluates op1 and op2 ^ op1 ^ op2 if op1 and op2 are different--that is if one or the other of the operands is true but not both
45 Assignment Operators • Basic assignment operator (=) is used to assign one value to another • Shortcut Assignment Operators Operator Use Equivalent to += op1 += op2 op1 = op1 + op2 -= op1 -= op2 op1 = op1 - op2 *= op1 *= op2 op1 = op1 * op2 /= op1 /= op2 op1 = op1 / op2 %= op1 %= op2 op1 = op1 % op2 &= op1 &= op2 op1 = op1 & op2
Working with primitives values • NOTE: When you are working with primitives you can make a copy of the values but you can not create a reference to the original values • In this example we have two copies of the values int intValue1 =5; int intValue2 = intValue1; 46
Converting numeric values • Two types of conversion: – Widening conversion: conversion of the value from a type that uses small amount of memory to a type the uses large amount of memory int intValue1 =5; long longValue2 = intValue1;//widening conversion 47
Converting numeric values • Narrowing conversion – Is the conversion of the value from a type that uses large amount of memory to a type the uses small amount of memory – Use type casting to narrowing type – Work fine if the original value is compatible with both types – But wont’s work if the original value in not compatible with new type int intValue1 =5; shot shortValue2 = (short)intValue1;//narrowing conv. int intValue1 =1500; byte byteValue2 = (short)intValue1;//narrowing conv. 48
Interactive programs • We have written programs that print console output, but it is also possible to read input from the console. – The user types input into the console. We capture the input and use it in our program. – Such a program is called an interactive program. • Interactive programs can be challenging. – Computers and users think in very different ways. – Users misbehave. 49
Input and System.in • System.out – An object with methods named println and print • System.in – not intended to be used directly – We use a second object, from a class Scanner, to help us. • Constructing a Scanner object to read console input: Scanner name = new Scanner(System.in); – Example: Scanner console = new Scanner(System.in); 50
Java class libraries, import • Java class libraries: Classes included with Java's JDK. – organized into groups named packages – To use a package, put an import declaration in your program. • Syntax:// put this at the very top of your program import packageName.*; • Scanner is in a package named java.util import java.util.*; – To use Scanner, you must place the above line at the top of your program (before the public class header). 51
Java class libraries, import • Java class libraries: Classes included with Java's JDK. – organized into groups named packages – To use a package, put an import declaration in your program. • Syntax: // put this at the very top of your program import packageName.*; • Scanner is in a package named java.util import java.util.*; – To use Scanner, you must place the above line at the top of your program (before the public class header). 52
Example Scanner usage • Output (user input underlined): How old are you? 14 14... That's quite old! import java.util.*; // so that I can use Scanner public class ReadSomeInput { public static void main(String[] args) { Scanner console = new Scanner(System.in); System.out.print("How old are you? "); int age = console.nextInt(); System.out.println(age + "... That's quite old!"); } } 53
Another Scanner example • Output (user input underlined): Please type three numbers: 8 6 13 The sum is 27 – The Scanner can read multiple values from one line. import java.util.*; // so that I can use Scanner public class ScannerSum { public static void main(String[] args) { Scanner console = new Scanner(System.in); System.out.print("Please type three numbers: "); int num1 = console.nextInt(); int num2 = console.nextInt(); int num3 = console.nextInt(); int sum = num1 + num2 + num3; System.out.println("The sum is " + sum); } } 54
Other Scanner Class Methods • Scanner keyboard = new Scanner(System.in); Method Example nextShort short num1; num1=keyboard.nextShort(); nextInt int num2; num2=keyboard.nextInt(); nextLong long num3; num3=keyboard.nextLong(); 55
Other Scanner Class Methods nextByte byte x; x=keyboard.nextByte(); nextFloat float num4; num4=keyboard.nextFloat(); nextDouble double num5; num5=keyboard.nextDouble(); nextLine String name; name=keyboard.nextLine(); 56
Flow of control • Java executes one statement after the other in the order they are written • Many Java statements are flow control statements: Alternation: if, if else, switch Looping: for, while, do while Escapes: break, continue, return 57
If-Else Statement • The if … else statement evaluates an expression and performs one action if that evaluation is true or a different action if it is false • if (expression) { statement(s) } else { statement(s) } • Eg 1. if (x<y) { System.out.println(“y is greater than x”); } else if (x>y) { System.out.println(“x is greater than y”); } else { System.out.println(“x and y are equal”); } 58
If-Else Statement • Eg 2. if (x<y) { System.out.println(“y is greater than x”); } else if (x>y) { System.out.println(“x is greater than y”); } else { System.out.println(“x and y are equal”); } 59
If-Else Statement • Exercise – Write a program to calculate the grade of a student given the average • Marks < 0 or Marks > 100 give Error Message • 0 <= Marks < 40 – Grade = C • 40 <= Marks < 70 – Grade = B • 70 <= Marks <= 100 – Grade = A – Hints • Write a class with a main method 60
Nested if … else if ( person ==“student” ) { if ( education ==“primary”) { System.out.println(“he/she is primary student”); } else { System.out.println(“he/she is not primary student”); } } else { System.out.print(“he/she is not student”); } 61
A Warning… WRONG! CORRECT! if( i == j ) if ( j == k ) System.out.print(“i equals k”); else System.out.print( “i is not equal to j”); if( i == j ) { if ( j == k ) System.out.print(“i equals k”); } else System.out.print(“i is not equal to j”); // Correct! 62
Ternary operator (op1 ? op2 : op3 ) • Shortcut if-else statement • op1 ? op2 : op3 returns op2 if op1 is true or returns op3 if op1 is false Example: variable x = (expression) ? value if true: value if false int a, b; a = 10; b = (a == 1) ? 20: 30; System.out.println( "Value of b is : " + b ); 63
Switch Statement • Evaluates a variable and executes statements according to it’s value switch (variable) { case value1: statement(s); break; case valueN: statement(s); break; case default: statement(s); break; } 64
Switch Statement • Eg. Exercise Write a program to output the following – Grade = A – ‘Very Good’ – Grade = B – ‘Good’ – Grade = C – ‘Bad switch (day) { case 1: System.out.println(“Sunday”); break; case 2: System.out.println(“Monday”); break; case 3: System.out.println(“Tuesday”); break; case 4: System.out.println(“Wednesday”); break; case 5: System.out.println(“Thursday”); break; case 6: System.out.println(“Friday”); break; case 7: System.out.println(“Saturday”); break; default: System.out.println(“Invalid Day”); break; } 65
For loop • To repeat an operation several times for (initialization; termination; increment) { statement(s) } • Eg • Loop n times for ( j = 0; j < 10; j++ ) { for ( i = 0; i < 20; i++ ){ // this code body will execute 200 times } } for ( i = 0; i < n; n++ ) { // this code body will execute n times // ifrom 0 to n-1 } 66
For loop • Nested for: for ( j = 0; j < 10; j++ ) { for ( i = 0; i < 20; i++ ){ // this code body will execute 200 times } } 67
For loop Exercise Write a program to calculate the factorial of a given integer 68
While and Do-While Statements • Continuously executes some statements while a condition remain true while (expression) { statement(s) } do { statement(s) } while (expression); 69
While and Do-While Statements • Eg. int x=0; while (x<5) { System.out.println(“Iteration ” + x); x++; } int x=0; do { System.out.println(“Iteration ” + x); x++; } while (x<5); 70
While and Do-While Statements Exercise • Write a method to calculate the factorial of a positive integer – Using a While Loop – Using a Do-While Loop 71
Branching Statements • break – Used to terminate a switch statement or a loop – Eg. int x=0; while (true) { System.out.println(“Iteration ” + x); x++; if (x==5) { break; } } 72
Branching Statements continue – Used to skip a part of an iteration in a loop – Eg. int x=0; while (x<5) { x++; if (x==2) { continue; } System.out.println(“Iteration ” + x); } 73
Arrays • Am array is a list of similar things • An array has a fixed: – name – type – length • These must be declared when the array is created. • Arrays sizes cannot be changed during the execution of the code – myArray has room for 8 elements – the elements are accessed by their index – in Java, array indices start at 0 74
Declaring Arrays int myArray[]; declares myArray to be an array of integers myArray = new int[8]; sets up 8 integer-sized spaces in memory, labelled myArray[0] to myArray[7] int myArray[] = new int[8]; combines the two statements in one line 75
Assigning Values • Refer to the array elements by index to store values in them. myArray[0] = 3; myArray[1] = 6; myArray[2] = 3; ... • Can create and initialise in one step: int myArray[] = {3, 6, 3, 1, 6, 3, 4, 1}; • Access an Array System.out.println(myArray[2]); 76
Iterating Through Arrays • for loops are useful when dealing with arrays: for (int i = 0; i < myArray.length; i++) { System.out.println(myArray[i]); } 77
The foreach Loops(jdk 1.5) • for loops are useful when dealing with arrays: for (int element: myArray) { System.out.println(element); } 78
Arrays - Multidimensional • Here, a is a two-dimensional (2d) array. The array can hold maximum of 12 elements of type int. int [][]arr=new int[3][4] arr[0][0] =1; arr[0][1] =5; arr[0][2] =7; arr[0][3] =6; arr[1][0] =34; arr[1][1] =41; arr[1][2] =4; arr[1][3] =-7; arr[2][0] =3; arr[2][1] =9; arr[2][3] =2; arr[2][3] =8; 79
initialize a 2d array in Java? int[][] a = { {1, 2, 3}, {4, 5, 6, 9}, {7}, }; 80
Print all elements of 2d array Using Loop class MultidimensionalArray { public static void main(String[] args) { int[][] a = { {1, -2, 3}, {-4, -5, 6, 9}, {7}, }; for (int i = 0; i < a.length; ++i) { for(int j = 0; j < a[i].length; ++j) { System.out.println(a[i][j]); } } } } 81
END 82

LECTURE 2 -Object oriented Java Basics.pptx

  • 1.
    LECTURE 1: JAVABASICS INF 2105: Software Application Development LECTURER :MR. AKRAM ALI OMAR EMAIL: akram.ali.omar@gmail.com Mobile: 0778695626 1
  • 2.
    LECTURE 1: JAVABASICS Write Once, Run Everywhere 2
  • 3.
    Java’s origins  Workon java started in 1991  The goal: a new portable language  Original name: Oak  Original tagline: Write Once, Run Everywhere 3
  • 4.
  • 5.
  • 6.
    Runtime Architecture  Javais an interpreted language  It compiles to bytecode instead of machine language  The compiled application is portable between platforms without recompiling  Byte code is interpreted, Java code can be executed anywhere an interpreter is available.  The "Interpreter" is call the Java Virtual Machine 6
  • 7.
     Traditionally, sourcecode had to be compiled for the target hardware and OS platform: The Java Virtual Machine. 7
  • 8.
    The Java VirtualMachine.  Java source files (.java) are compiled to Java bytecode (.class)  Bytecode is interpreted on the target platform within a Java Virtual Machine  The Java VM does more than interpret bytecode:  The class loader loads appropriate java classes  All classes are verified to contain only legal bytecodes and not permitted any illegal stack or register usage 8
  • 9.
  • 10.
    Java Editions  JavaPlatform, Standard Edition(SE) Standard for core language and runtime environment(JRE)  Java Platform, Enterprise Edition(EE) Standard for building industrial-strength web applications  Java Platform, Micro Edition (ME) Micro-controllers, sensors, and mobile devices 10
  • 11.
    Java SE DevelopmentKit(JDK)  Availablee at no cost from Oracle  Includes tools for compilation and packaging  java: runtime  javac: compiler  javadoc: docs builder  jar: archive builder 11
  • 12.
    Choosing a DevelopmentEnvironment  Any text editor will do it  But many java IDEs are available  On OS X  BDEdit and TextWrangler: not a java “specialis”t IDE • On windows:  TextPad  JCreator 12
  • 13.
    Top Cross- PlatformIDEs  NetBeans  Excellent support for JEE development  Also supports C, C++, and PHP  Eclipse with Java Developer tools  Free and open source  Distributions for many languages and platform  IntelliJ IDEA  Free “community” edition, paid “pro” edition  Foundation of Google’s Android Studio 13
  • 14.
    Java Basic Syntax JAVACLASSES: • All code is defined in classes • Classes are defined in source code files with .java extension • The javac command compiles Java code into bytecode • The java command runs compiled bytecode files. 14
  • 15.
    Java Basic Syntax SimpleJava Program: – Let us look at a simple code that would print the words ”I rule!”. public class MyFirstApp { public static void main(String []args) { System.out.println("I rule!"); } } Class declaration Main method Executable code 15
  • 16.
  • 17.
    how to savethe file, compile and run the program. • Let's look at how to save the file, compile and run the program. Please follow the steps given below: • Open notepad and add the code as above. • Save the file as: MyFirstApp.java. 17
  • 18.
    how to savethe file, compile and run the program. • Open a command prompt window and go o the directory where you saved the class. Assume it's C:. • Type ' javac MyFirstApp.java ' and press enter to compile your code. If there are no errors in your code, the command prompt will take you to the next line (Assumption : The path variable is set). 18
  • 19.
    how to savethe file, compile and run the program. • Now, type ' java MyFirstApp' to run your program. • You will be able to see ‘I rule!' printed on the window. 19
  • 20.
    Parsing Arguments toa console application public class MyFirstApp { public static void main(String []args) { System.out.println("I rule!"); System.out.println(args[0]); } } 20
  • 21.
    COMMENTS IN JAVA –Comments start with: // • Comments ignored during program execution • Document and describe code • Provides code readability – Multiple line comments: /* ... */ /* This is a multiple line comment. It can be split over many lines */ – Another line of comments – Note: line numbers not part of program, added for reference 21
  • 22.
    Basic Syntax: • AboutJava programs, it is very important to keep in mind the following points. • Case Sensitivity – Java is case sensitive, which means identifier Hello and hello would have different meaning in Java. • White space – white space doesn’t affect interpretation of code – space, tabs, and line feeds are “collapsed” by compiler – All statements must end with must end with semicolon(;). 22
  • 23.
    Basic Syntax: • ClassNames – For all class names the first letter should be in Upper Case. – If several words are used to form a name of the class, each inner word's first letter should be in Upper Case. – Example class MyFirstApp 23
  • 24.
    Basic Syntax: • MethodNames – All method names should start with a Lower Case letter. – If several words are used to form the name of the method, then each inner word's first letter should be in Upper Case. Example public void myMethodName() • public static void main(String args[]) – Java program processing starts from the main() method which is a mandatory part of every Java program. • Constants are all uppercase 24
  • 25.
    Basic Syntax: • ProgramFile Name – Name of the program file should exactly match the class name. – When saving the file, you should save it using the class name (Remember Java is case sensitive) and append '.java' to the end of the name (if the file name and the class name do not match your program will not compile). – Example : Assume 'MyFirstApp' is the class name. Then the file should be saved as' MyFirstApp.java' 25
  • 26.
    Java Identifiers: • AllJava components require names. Names used for classes, variables and methods are called identifiers. • In Java, there are several points to remember about identifiers. They are as follows: • All identifiers should begin with a letter (A to Z or a to z), currency character ($) or an underscore (_). 26
  • 27.
    Java Identifiers: • Afterthe first character identifiers can have any combination of characters. • A key word cannot be used as an identifier. https://docs.oracle.com/javase/tutorial/java/nutsandbolts/_keywords.html • Most importantly identifiers are case sensitive. • Examples of legal identifiers: age, $salary, _value, __1_value • Examples of illegal identifiers: 123abc, -salary 27
  • 28.
    Using Character EscapeCodes • There are some characters that will cause problems in your code if typed explicitly, such as the carriage return or double • Quotation mark. Typing these directly into your code where you want them to print is problematic and would most likely cause compiler errors. • For example System.out.println(“Some people call me “Joey”.”); //compile error 28
  • 29.
    CHARACTER ESCAPE CODES System.out.println(“Somepeople call me ”Joey”.”); //no error 29
  • 30.
    Primitive Types andVariables • Boolean, char, byte, short, int, long, float, double etc. • These basic (or primitive) types are the only types that are not objects (due to performance issues). • This means that you don’t use the new operator to create a primitive variable • Declaring primitive variables: float initVal; int retVal = 2; double gamma = 1.2; boolean valueOk = false; 30
  • 31.
    Primitive Types andVariables 31
  • 32.
    Primitive Variable &Reference Variable • When you think of java variable, think of a container that holds something. • This container (java variable) has size and a type. • Primitive containers (variables) have different sizes and those sizes have names. • Each primitive variable has a fixed number of bits (container size). • A cups´size analogy of the six numeric primitives variables in Java are shown below 32
  • 33.
    Primitive Variable &Reference Variable • Java cares about types, you can´t put different things in a different type of a container. E.g. Rabbit b = new Giraffe(); Don´t expect this to compile!!! • You can´t put a large value into a small byte b = 1500; // this will never work. 33
  • 34.
    Primitive Variable &Reference Variable • You know how to declare a primitive variable and assign it a value. • But now what about non-primitive variables? In other words, what about objects? • There is actually no such thing as an object variable, there's only an object reference variable. • It doesn't hold the object itself, It holds bits that represent a way to access an object • You can't put (store) an object into a variable. 34
  • 35.
  • 36.
    Initialisation • If novalue is assigned prior to use, then the compiler will give an error • Java sets primitive variables to zero or false in the case of a Boolean variable • All object references are initially set to null • An array of anything is an object – Set to null on declaration – Elements to zero false or null on creation 36
  • 37.
    MEMORY MANAGEMENT AND GARBAGECOLLECTION • Objects are born and objects die. You're in charge of an object's Iifecycle. • You decide when and how to construct it.You decide when to destroy It. • Except you don't actually destroy the object yourself, you simply abandon it. But once it 's abandoned, the heartless Garbage Collector, can vaporize it, reclaiming the memory that object was using . • When writing java programs, you will be creating objects. Sooner or later, you´ve to let some of them go, or risk running out of RAM. 37
  • 38.
    The Stack andthe Heap: Where things live • When a JVM starts up, it gets a chunk of memory from the underlying OS, and uses it to run your Java program. • In java, we (programmers) care about two areas of memory – The one where objects live (the heap), and the one where method invocations and local variables live (the stack). 38
  • 39.
    MATHEMATICAL OPERATORS: • INTEGERMATH • FLOATING POINT MATH 39
  • 40.
    Operator Precedence • Operatorprecedence determines the order in which operations are applied to numbers. • In general, multiplication (*), division (/), and modulus (%) have precedence over addition (+) and subtraction (–). • This means that multiplication, division, and modulus operations are evaluated before addition and subtraction. When operator precedence is the same, operations occur from left to right 40
  • 41.
    Operator Precedence Example int x= 10 – 4 + 14 / 2; • The value of x will be 10 if it evaluated strictly left to right. 10 – 4 = 6; 6 + 14 = 20; 20 / 2 = 10. • Because the division operator is evaluated first, the value of this expression is 13. (10 – 4 + 7 = 13). • Therefore the correct value of x is 13; 41
  • 42.
    Enforcing operator precedence •There is a way to force operator precedence using parentheses (like in Algebra). • The operations within parentheses have precedence int y = (10 – 4 + 14) / 2; 42
  • 43.
    43 Relational and ConditionalOperators • Compares two values and determines the relationship between them Operator Use Returns true if > op1 > op2 op1 is greater than op2 >= op1 >= op2 op1 is greater than or equal to op2 < op1 < op2 op1 is less than op2 <= op1 <= op2 op1 is less than or equal to op2 == op1 == op2 op1 and op2 are equal != op1 != op2 op1 and op2 are not equal
  • 44.
    44 Relational and ConditionalOperators • Used to construct decision making expressions Operator Use Returns true if && op1 && op2 op1 and op2 are both true, conditionally evaluates op2 || op1 || op2 either op1 or op2 is true, conditionally evaluates op2 ! ! op op is false & op1 & op2 op1 and op2 are both true, always evaluates op1 and op2 | op1 | op2 either op1 or op2 is true, always evaluates op1 and op2 ^ op1 ^ op2 if op1 and op2 are different--that is if one or the other of the operands is true but not both
  • 45.
    45 Assignment Operators • Basicassignment operator (=) is used to assign one value to another • Shortcut Assignment Operators Operator Use Equivalent to += op1 += op2 op1 = op1 + op2 -= op1 -= op2 op1 = op1 - op2 *= op1 *= op2 op1 = op1 * op2 /= op1 /= op2 op1 = op1 / op2 %= op1 %= op2 op1 = op1 % op2 &= op1 &= op2 op1 = op1 & op2
  • 46.
    Working with primitivesvalues • NOTE: When you are working with primitives you can make a copy of the values but you can not create a reference to the original values • In this example we have two copies of the values int intValue1 =5; int intValue2 = intValue1; 46
  • 47.
    Converting numeric values •Two types of conversion: – Widening conversion: conversion of the value from a type that uses small amount of memory to a type the uses large amount of memory int intValue1 =5; long longValue2 = intValue1;//widening conversion 47
  • 48.
    Converting numeric values •Narrowing conversion – Is the conversion of the value from a type that uses large amount of memory to a type the uses small amount of memory – Use type casting to narrowing type – Work fine if the original value is compatible with both types – But wont’s work if the original value in not compatible with new type int intValue1 =5; shot shortValue2 = (short)intValue1;//narrowing conv. int intValue1 =1500; byte byteValue2 = (short)intValue1;//narrowing conv. 48
  • 49.
    Interactive programs • Wehave written programs that print console output, but it is also possible to read input from the console. – The user types input into the console. We capture the input and use it in our program. – Such a program is called an interactive program. • Interactive programs can be challenging. – Computers and users think in very different ways. – Users misbehave. 49
  • 50.
    Input and System.in •System.out – An object with methods named println and print • System.in – not intended to be used directly – We use a second object, from a class Scanner, to help us. • Constructing a Scanner object to read console input: Scanner name = new Scanner(System.in); – Example: Scanner console = new Scanner(System.in); 50
  • 51.
    Java class libraries,import • Java class libraries: Classes included with Java's JDK. – organized into groups named packages – To use a package, put an import declaration in your program. • Syntax:// put this at the very top of your program import packageName.*; • Scanner is in a package named java.util import java.util.*; – To use Scanner, you must place the above line at the top of your program (before the public class header). 51
  • 52.
    Java class libraries,import • Java class libraries: Classes included with Java's JDK. – organized into groups named packages – To use a package, put an import declaration in your program. • Syntax: // put this at the very top of your program import packageName.*; • Scanner is in a package named java.util import java.util.*; – To use Scanner, you must place the above line at the top of your program (before the public class header). 52
  • 53.
    Example Scanner usage •Output (user input underlined): How old are you? 14 14... That's quite old! import java.util.*; // so that I can use Scanner public class ReadSomeInput { public static void main(String[] args) { Scanner console = new Scanner(System.in); System.out.print("How old are you? "); int age = console.nextInt(); System.out.println(age + "... That's quite old!"); } } 53
  • 54.
    Another Scanner example •Output (user input underlined): Please type three numbers: 8 6 13 The sum is 27 – The Scanner can read multiple values from one line. import java.util.*; // so that I can use Scanner public class ScannerSum { public static void main(String[] args) { Scanner console = new Scanner(System.in); System.out.print("Please type three numbers: "); int num1 = console.nextInt(); int num2 = console.nextInt(); int num3 = console.nextInt(); int sum = num1 + num2 + num3; System.out.println("The sum is " + sum); } } 54
  • 55.
    Other Scanner ClassMethods • Scanner keyboard = new Scanner(System.in); Method Example nextShort short num1; num1=keyboard.nextShort(); nextInt int num2; num2=keyboard.nextInt(); nextLong long num3; num3=keyboard.nextLong(); 55
  • 56.
    Other Scanner ClassMethods nextByte byte x; x=keyboard.nextByte(); nextFloat float num4; num4=keyboard.nextFloat(); nextDouble double num5; num5=keyboard.nextDouble(); nextLine String name; name=keyboard.nextLine(); 56
  • 57.
    Flow of control •Java executes one statement after the other in the order they are written • Many Java statements are flow control statements: Alternation: if, if else, switch Looping: for, while, do while Escapes: break, continue, return 57
  • 58.
    If-Else Statement • Theif … else statement evaluates an expression and performs one action if that evaluation is true or a different action if it is false • if (expression) { statement(s) } else { statement(s) } • Eg 1. if (x<y) { System.out.println(“y is greater than x”); } else if (x>y) { System.out.println(“x is greater than y”); } else { System.out.println(“x and y are equal”); } 58
  • 59.
    If-Else Statement • Eg2. if (x<y) { System.out.println(“y is greater than x”); } else if (x>y) { System.out.println(“x is greater than y”); } else { System.out.println(“x and y are equal”); } 59
  • 60.
    If-Else Statement • Exercise –Write a program to calculate the grade of a student given the average • Marks < 0 or Marks > 100 give Error Message • 0 <= Marks < 40 – Grade = C • 40 <= Marks < 70 – Grade = B • 70 <= Marks <= 100 – Grade = A – Hints • Write a class with a main method 60
  • 61.
    Nested if …else if ( person ==“student” ) { if ( education ==“primary”) { System.out.println(“he/she is primary student”); } else { System.out.println(“he/she is not primary student”); } } else { System.out.print(“he/she is not student”); } 61
  • 62.
    A Warning… WRONG! CORRECT! if( i== j ) if ( j == k ) System.out.print(“i equals k”); else System.out.print( “i is not equal to j”); if( i == j ) { if ( j == k ) System.out.print(“i equals k”); } else System.out.print(“i is not equal to j”); // Correct! 62
  • 63.
    Ternary operator (op1? op2 : op3 ) • Shortcut if-else statement • op1 ? op2 : op3 returns op2 if op1 is true or returns op3 if op1 is false Example: variable x = (expression) ? value if true: value if false int a, b; a = 10; b = (a == 1) ? 20: 30; System.out.println( "Value of b is : " + b ); 63
  • 64.
    Switch Statement • Evaluatesa variable and executes statements according to it’s value switch (variable) { case value1: statement(s); break; case valueN: statement(s); break; case default: statement(s); break; } 64
  • 65.
    Switch Statement • Eg. Exercise Writea program to output the following – Grade = A – ‘Very Good’ – Grade = B – ‘Good’ – Grade = C – ‘Bad switch (day) { case 1: System.out.println(“Sunday”); break; case 2: System.out.println(“Monday”); break; case 3: System.out.println(“Tuesday”); break; case 4: System.out.println(“Wednesday”); break; case 5: System.out.println(“Thursday”); break; case 6: System.out.println(“Friday”); break; case 7: System.out.println(“Saturday”); break; default: System.out.println(“Invalid Day”); break; } 65
  • 66.
    For loop • Torepeat an operation several times for (initialization; termination; increment) { statement(s) } • Eg • Loop n times for ( j = 0; j < 10; j++ ) { for ( i = 0; i < 20; i++ ){ // this code body will execute 200 times } } for ( i = 0; i < n; n++ ) { // this code body will execute n times // ifrom 0 to n-1 } 66
  • 67.
    For loop • Nestedfor: for ( j = 0; j < 10; j++ ) { for ( i = 0; i < 20; i++ ){ // this code body will execute 200 times } } 67
  • 68.
    For loop Exercise Write aprogram to calculate the factorial of a given integer 68
  • 69.
    While and Do-WhileStatements • Continuously executes some statements while a condition remain true while (expression) { statement(s) } do { statement(s) } while (expression); 69
  • 70.
    While and Do-WhileStatements • Eg. int x=0; while (x<5) { System.out.println(“Iteration ” + x); x++; } int x=0; do { System.out.println(“Iteration ” + x); x++; } while (x<5); 70
  • 71.
    While and Do-WhileStatements Exercise • Write a method to calculate the factorial of a positive integer – Using a While Loop – Using a Do-While Loop 71
  • 72.
    Branching Statements • break –Used to terminate a switch statement or a loop – Eg. int x=0; while (true) { System.out.println(“Iteration ” + x); x++; if (x==5) { break; } } 72
  • 73.
    Branching Statements continue – Usedto skip a part of an iteration in a loop – Eg. int x=0; while (x<5) { x++; if (x==2) { continue; } System.out.println(“Iteration ” + x); } 73
  • 74.
    Arrays • Am arrayis a list of similar things • An array has a fixed: – name – type – length • These must be declared when the array is created. • Arrays sizes cannot be changed during the execution of the code – myArray has room for 8 elements – the elements are accessed by their index – in Java, array indices start at 0 74
  • 75.
    Declaring Arrays int myArray[]; declaresmyArray to be an array of integers myArray = new int[8]; sets up 8 integer-sized spaces in memory, labelled myArray[0] to myArray[7] int myArray[] = new int[8]; combines the two statements in one line 75
  • 76.
    Assigning Values • Referto the array elements by index to store values in them. myArray[0] = 3; myArray[1] = 6; myArray[2] = 3; ... • Can create and initialise in one step: int myArray[] = {3, 6, 3, 1, 6, 3, 4, 1}; • Access an Array System.out.println(myArray[2]); 76
  • 77.
    Iterating Through Arrays •for loops are useful when dealing with arrays: for (int i = 0; i < myArray.length; i++) { System.out.println(myArray[i]); } 77
  • 78.
    The foreach Loops(jdk1.5) • for loops are useful when dealing with arrays: for (int element: myArray) { System.out.println(element); } 78
  • 79.
    Arrays - Multidimensional •Here, a is a two-dimensional (2d) array. The array can hold maximum of 12 elements of type int. int [][]arr=new int[3][4] arr[0][0] =1; arr[0][1] =5; arr[0][2] =7; arr[0][3] =6; arr[1][0] =34; arr[1][1] =41; arr[1][2] =4; arr[1][3] =-7; arr[2][0] =3; arr[2][1] =9; arr[2][3] =2; arr[2][3] =8; 79
  • 80.
    initialize a 2darray in Java? int[][] a = { {1, 2, 3}, {4, 5, 6, 9}, {7}, }; 80
  • 81.
    Print all elementsof 2d array Using Loop class MultidimensionalArray { public static void main(String[] args) { int[][] a = { {1, -2, 3}, {-4, -5, 6, 9}, {7}, }; for (int i = 0; i < a.length; ++i) { for(int j = 0; j < a[i].length; ++j) { System.out.println(a[i][j]); } } } } 81
  • 82.

Editor's Notes

  • #53 It's also useful to write a program that prompts for multiple values, both on the same line or each on its own line.
  • #54 It's also useful to write a program that prompts for multiple values, both on the same line or each on its own line.