introduction to oop with java - abu...
Post on 14-Apr-2018
260 Views
Preview:
TRANSCRIPT
Introduction to OOP with Java - AKF Sep 2017
AbuKhleiF - www.abukhleif.com 1
Introduction to OOP with Java
Instructor: AbuKhleif, Mohammad Noor
Sep 2017
www.abukhleif.com
Java Basics
Instructor: AbuKhleif, Mohammad Noor
Sep 2017
www.abukhleif.com
Lecture 02:
Introduction to OOP with Java - AKF Sep 2017
AbuKhleiF - www.abukhleif.com 2
Instructor
• AbuKhleif, ‘Mohammad Noor’• Studied Computer Engineer (JU 2012-2017)• Works as a Software Automation Engineer @ Atypon –
John Wiley and Sons Company - Jordan Branch
• Reach me at:• www.abukhleif.com• moh.noor94@gmail.com• facebook.com/moh.noor94• twitter.com/moh_noor94
Course
• Java SE Basics• Object Oriented Programming• Course Page:
www.abukhleif.com/courses/java-101-sep-2017• Or, go to: www.abukhleif.com Courses Java 101 Course
– Sep 2017• Course Facebook Group:
www.facebook.com/groups/AKF2017Java
Introduction to OOP with Java - AKF Sep 2017
AbuKhleiF - www.abukhleif.com 3
Let’s Start!
Primitive Datatypes
• Integers
• byte (1 byte, -128 to 127)
• short (2 bytes)
• int (4 bytes)
• long (8 bytes)
• Floating-point types
• float (4 bytes, 6-7 significant decimal digits)
• double (8 bytes, 15 significant decimal digits)
• char (2 byte, Unicode)
• boolean (true or false)
• Those are all the primitive types in Java. Everything else is an object.
Introduction to OOP with Java - AKF Sep 2017
AbuKhleiF - www.abukhleif.com 4
Identifiers
• Identifiers are the names of things that appear in the program.
• Names of variables, constants, methods, classes, packages…
• All identifiers must obey the following rules: • An identifier is a sequence of characters that consists of letters, digits,
underscores (_), and dollar sign ($).
• Cannot start with a digit.
• Cannot be a reserved word.
• Can be of any length.
• Examples of legal identifiers: $2, area, Area, S_3.
• Examples of illegal identifiers: 2A, d+4, S#6.
Statement
• A statement represents an action or a sequence of actions.
• The statement System.out.println("Welcome to Java!") is a statement to display the greeting "Welcome to Java!“.
• Every statement in Java ends with a semicolon (;).
Introduction to OOP with Java - AKF Sep 2017
AbuKhleiF - www.abukhleif.com 5
Variables
• Variables are used to represent values that may be changed in the program.
• The syntax for declaring a variable:
[datatype variableName]
• Examples of variable declarations: • int count;
• double rate;
• char letter;
• boolean found;
Variables
• Several variables can be declared together: • int count, limit, numberOfStudents;
• When a variable is declared, the compiler allocates memory space for the variable based on its data type.
Introduction to OOP with Java - AKF Sep 2017
AbuKhleiF - www.abukhleif.com 6
Assignment Statement
• An assignment statement designates a value for a variable.
• The equal sign (=) is used as the assignment operator.
• Examples: • x = 1;
• x = x+1;
• area = radius * radius * 3.14159;
• Right Side will be always evaluated before the left side.
Assignment Statement
• Variables can be declared and initialized in one step: • int count = 0;
• char letter = ‘a’;
• boolean found = false;
• int i = 1, j = 2;
• int count = 0; is equivalent to the following two statements: • int count;
• count = 0;
Introduction to OOP with Java - AKF Sep 2017
AbuKhleiF - www.abukhleif.com 7
Assignment Statement
• An assignment statement can be used as an expression in Java: • System.out.println(x=1);
• A value can be assigned to multiple variables: • i = j = k = 1;
• In an assignment statement the data type of the variable on the left must be compatible with the data type of the value on the right.
• Except if type casting is used.
Constants
• A constant is an identifier that represents a permanent value.
• The syntax for declaring a constant:
[final datatype CONSTANT_NAME = value;]
• Example: • final double PI = 3.14159;
Introduction to OOP with Java - AKF Sep 2017
AbuKhleiF - www.abukhleif.com 8
Numeric Literals
• A literal is a constant value that appears directly in a program.
• An integer literal can be assigned to an integer variable as long as it can fit into the variable.
• Otherwise a compile error occurs. • E.g. byte b = 128; will cause a compilation error.
• To denote an integer literal of the long type, append letter L or l to it. • E.g. 2147483648L
• To denote a floating point literal of the long type, append letter F or f to it.
• E.g. 100.2F • By default, 100.2 treated as a double value.
Character Literals• A character literal is a single character enclosed in single quotation
marks (‘ ‘).
• Escape characters are used to represent special characters.
• Can be written directly inside any String value.
Name Character
Backspace \b
TAB \t
newline \n
carriage control \r
double quote \”
single quote \’
backslash \\
Introduction to OOP with Java - AKF Sep 2017
AbuKhleiF - www.abukhleif.com 9
Keywords / Reserved Words
• Reserved words or keywords are words that have a specific meaning to the compiler and cannot be used for other purposes in the program.
• For example, when the compiler sees the word class, it understands that the word after class is the name for the class.
Special Symbols
Character Name Description
{}
()
[]
//
" "
;
Opening and closing
braces
Opening and closing
parentheses
Opening and closing
brackets
Double slashes
Opening and closing
quotation marks
Semicolon
Denotes a block to enclose statements.
Used with methods.
Denotes an array.
Precedes a comment line.
Enclosing a string (i.e., sequence of characters).
Marks the end of a statement.
Introduction to OOP with Java - AKF Sep 2017
AbuKhleiF - www.abukhleif.com 10
Let’s Code
• Write a Java program that print your name and address to the console like:
Name: AbuKhleifAge: 23 yearsAddress: Amman, Jordan
using variables and one print statement.
Java Operators
Introduction to OOP with Java - AKF Sep 2017
AbuKhleiF - www.abukhleif.com 11
Arithmetic Operators
Operator Description Example
+ (Addition) Adds values on either side of the operator. A + B will give 30
- (Subtraction)Subtracts right-hand operand from left-hand operand.
A - B will give -10
* (Multiplication)Multiplies values on either side of the operator.
A * B will give 200
/ (Division)Divides left-hand operand by right-hand operand.
B / A will give 2
% (Modulus)Divides left-hand operand by right-hand operand and returns remainder. B % A will give 0
++ (Increment Pre/Post) Increases the value of operand by 1. B++ gives 21
-- (Decrement Pre/Post) Decreases the value of operand by 1. B-- gives 19
Assume integer variable A holds 10 and variable B holds 20, then
Relational Operators
Operator Description Example
== (equal to)Checks if the values of two operands are equal or not, if yes then condition becomes true.
(A == B) is not true.
!= (not equal to)Checks if the values of two operands are equal or not, if values are not equal then condition becomes true.
(A != B) is true.
> (greater than)Checks if the value of left operand is greater than the value of right operand, if yes then condition becomes true.
(A > B) is not true.
< (less than)Checks if the value of left operand is less than the value of right operand, if yes then condition becomes true.
(A < B) is true.
>= (greater than or equal to)
Checks if the value of left operand is greater than or equal to the value of right operand, if yes then condition becomes true.
(A >= B) is not true.
Assume integer variable A holds 10 and variable B holds 20, then
Introduction to OOP with Java - AKF Sep 2017
AbuKhleiF - www.abukhleif.com 12
Logical Operators
Operator Description Example
&& (logical and)Called Logical AND operator. If both the operands are non-zero, then the condition becomes true.
(A && B) is false
|| (logical or)Called Logical OR Operator. If any of the two operands are non-zero, then the condition becomes true.
(A || B) is true
! (logical not)Called Logical NOT Operator. Use to reverses the logical state of its operand. If a condition is true then Logical NOT operator will make false.
!(A && B) is true
Assume Boolean variables A holds true and variable B holds false, then
Augmented Assignment Operators
Operator Description Example
=Simple assignment operator. Assigns values from right side operands to left side operand.
C = A + B will assign value of A + B into C
=+Add AND assignment operator. It adds right operand to the left operand and assign the result to left operand.
C += A is equivalent toC = C + A
-=Subtract AND assignment operator. It subtracts right operand from the left operand and assign the result to left operand.
C -= A is equivalent toC = C – A
=*Multiply AND assignment operator. It multiplies right operand with the left operand and assign the result to left operand.
C *= A is equivalent toC = C * A
=/Divide AND assignment operator. It divides left operand with the right operand and assign the result to left operand.
C /= A is equivalent toC = C / A
=%Modulus AND assignment operator. It takes modulus using two operands and assign the result to left operand.
C %= A is equivalent toC = C % A
Introduction to OOP with Java - AKF Sep 2017
AbuKhleiF - www.abukhleif.com 13
Operator Precedence in JavaOperator Description Associativity
++
--
unary post-incrementunary post-decrement
not associative
++
--
unary pre-incrementunary pre-decrement
not associative
()new
castobject creation
right to left
% / * multiplicative left to right
+-
+
additivestring concatenation
left to right
< <=> >=
relational not associative
==
=!equality left to right
&& logical AND left to right
|| logical OR left to right
?: ternary right to left
==+-=
=*=/=%assignment right to left
Operator Precedence in Java
• Example:
Introduction to OOP with Java - AKF Sep 2017
AbuKhleiF - www.abukhleif.com 14
Let’s Code
• Write a Java program that declares 2 numeric variables a =0 & b=10.5 and print:
• “a + b = RESULT“
• “a - b = RESULT“
• “a * b = RESULT“
• “a / b = RESULT“
• “a % b = RESULT“
• “Is a < b? RESULT”
• “Is a equals to b? RESULT”
• “Is both of and b equals to zero? RESULT”
• “Is there any non-zero value among a & B? RESULT”
Casting
Introduction to OOP with Java - AKF Sep 2017
AbuKhleiF - www.abukhleif.com 15
Casting
• Casting is an operation that (converts?) a value of one data type into a value of another data type.
• Widening a type is casting a type with a small range to a type with a larger range.
• E.g. Integer to floating point: 3 * 4.5 is same as 3.0 * 4.5.
• Narrowing a type is casting a type with a large range to a type with a smaller range.
• E.g. floating point to integer: System.out.println ( (int)1.7 );
• Java automatically widens a type, but you must narrow a type explicitly.
Casting
narrowing
widening
Introduction to OOP with Java - AKF Sep 2017
AbuKhleiF - www.abukhleif.com 16
Let’s Code
• Write a simple Java application with a class named ‘Casting’
• Let your code show that you understand the usefulness and the functionality in using casting in Java.
String Type
Introduction to OOP with Java - AKF Sep 2017
AbuKhleiF - www.abukhleif.com 17
String Type
• A string is a sequence of characters.
• To represent a string of characters, use the data type called String:• E.g. String message = “Welcome to Java”;
• String is a predefined class in the Java library.
• The String type is not a primitive type.
• A string literal must be enclosed on quotation marks (“ “ ).
String Type
• The plus sign (+) is the concatenation operator if at least one of the operands is a string.
• If one of the operands is a non string (e.g. a number), the non string value is converted into a string and concatenated with the string.
• Examples: • String message = “Welcome ” + “to “ + ”Java!”;
message becomes: Welcome to Java! • String s = “Chapter” + 2;
s becomes: Chapter2 • String appendix = “Appendix” + ‘B’;
appendix becomes: AppendixB
• If neither of the operands is a string, the plus sign (+) is the addition operator.
Introduction to OOP with Java - AKF Sep 2017
AbuKhleiF - www.abukhleif.com 18
Programming Style and Documentation
Appropriate Comments
• Include a summary at the beginning of the program to explain what the program does, its key features, its supporting data structures, and any unique techniques it uses.
• Include your name, class section, instructor, date, and a brief description at the beginning of the program.
• Document each method with useful information.
• Document methods, fields, classes with the comment /** …… */
• WHY is mush more important than WHAT.
Introduction to OOP with Java - AKF Sep 2017
AbuKhleiF - www.abukhleif.com 19
Naming Conventions
• Choose meaningful and descriptive names.
• Java Naming conventions• Java naming convention is a (rule?) to follow as you decide what to name your
identifiers such as class, package, variable, constant, method etc.
• But, it is not forced to follow. So, it is known as convention not rule.
• All the classes, interfaces, packages, methods and fields of java programming language are given according to java naming convention.
Naming Conventions
• Advantage of naming conventions in java• By using standard Java naming conventions, you make your code easier to
read for yourself and for other programmers. Readability of Java program is very important. It indicates that less time is spent to figure out what the code does.
• CamelCase in java naming conventions• Java follows camelCase syntax for naming the class, interface, method and
variable.• If name is combined with two words, second word will start with uppercase
letter always e.g. actionPerformed(), firstName, ActionEvent, ActionListener etc.
Introduction to OOP with Java - AKF Sep 2017
AbuKhleiF - www.abukhleif.com 20
Naming Conventions
Name Convention Examples
Class Name Should start with uppercase letter and be a noun String, Color, Button, System, Thread
Interface Name Should start with uppercase letter and be an adjective Runnable, Remote, ActionListener
Method Name Should start with lowercase letter and be a verb actionPerformed(), main(), print(), println()
Variable Name should start with lowercase letter firstName, orderNumber
Package Name Should be in lowercase letter java, lang, sql, util
Constant Name Should be in uppercase letter RED, YELLOW, MAX_PRIORITY, PI
Proper Indentation and Spacing
• Indentation• Indent four (two?) spaces.
• Spacing• Use blank line to separate segments of the code.
• Let IntelliJ IDEA help you!• CTRL + ALT + L
Introduction to OOP with Java - AKF Sep 2017
AbuKhleiF - www.abukhleif.com 21
Block Styles
• Use end-of-line style for braces.
public class Test
{
public static void main(String[] args)
{
System.out.println("Block Styles");
}
}
public class Test {
public static void main(String[] args) {
System.out.println("Block Styles");
}
}
End-of-line
style
Next-line
style
Programming Errors
Introduction to OOP with Java - AKF Sep 2017
AbuKhleiF - www.abukhleif.com 22
Programming Errors
• Detected by the compiler
• Result from errors in code construction
Syntax Errors
• Causes the program to abort
• Occur while the program is running if the environment detects an operation that is impossible to carry out
• Example: include input errors and division by zero.
Runtime Errors
• Produces incorrect result
• Occur when a program does not perform the way it is intended to
Logic (Errors?)
Reading from the Console
Introduction to OOP with Java - AKF Sep 2017
AbuKhleiF - www.abukhleif.com 23
Reading from the Console
import java.util.Scanner;public class AgeCalculater {
public static void main(String[] args) {Scanner scanner = new Scanner(System.in);System.out.println("Please enter your name: ");String name = scanner.nextLine();System.out.println("Please enter your birth year: ");int age = scanner.nextInt();System.out.println("Welcome " + name + ", you are " + (2017 - age) + " years
now :D");}
}
Let’s Code
• Write a Java program that declares 2 numeric variables a & b, read there values from the user and print:
• “a + b = RESULT“• “a - b = RESULT“• “a * b = RESULT“• “a / b = RESULT“• “a % b = RESULT“• “Is a < b? RESULT”• “Is a equals to b? RESULT”• “Is both of and b equals to zero? RESULT”• “Is there any non-zero value among a & B? RESULT”
• Document your code using appropriate comments, and use a tidy style.
Introduction to OOP with Java - AKF Sep 2017
AbuKhleiF - www.abukhleif.com 24
Command-Line Arguments
Command-Line Arguments
• A Java application can accept any number of (String) arguments from the command line.
• This allows the user to specify configuration information when the application is launched.
• Example Code:
public static void main(String[] args)
• All arguments are saved to the args (array?)
Introduction to OOP with Java - AKF Sep 2017
AbuKhleiF - www.abukhleif.com 25
Command-Line Arguments
• Example:
public class CmdArgs {
public static void main(String[] args) {
System.out.println("First command line argument:
" + args[0]);
System.out.println("Second command line
argument: " + args[1]);
}
}
Command-Line Arguments
• To add Program Argument from the IntelliJ IDEA IDE:• Go to ‘Run’ menu
• Click ‘Edit Configurations’
• Add your values to ‘Program Arguments’• Example: firstArgument secondArgument
• Click ‘Apply’ then ‘Ok’
• Run your program
• Or, you can run your application from the CMD / terminal as:java CmdArgs firstArgument secondArgument
Introduction to OOP with Java - AKF Sep 2017
AbuKhleiF - www.abukhleif.com 26
Command-Line Arguments
• Example Output:First command line argument: firstArgument
Second command line argument: firstArgument
Let’s Code
• Try the previous example on your machine.
Introduction to OOP with Java - AKF Sep 2017
AbuKhleiF - www.abukhleif.com 27
IntelliJ IDEA Shortcuts
CTRL + ALT + L
psvm soutALT +
ENTER
TasksAll tasks should be well-documented, well-designed, and well-styled.
Introduction to OOP with Java - AKF Sep 2017
AbuKhleiF - www.abukhleif.com 28
Task 01
• (Convert Celsius to Fahrenheit) Write a program that reads a Celsius degree in a double value from the console, then converts it to Fahrenheit and displays the result. The formula for the conversion is as follows:
fahrenheit = (9 / 5) * celsius + 32
• Hint: In Java, 9 / 5 is 1, but 9.0 / 5 is 1.8.
• Here is a sample run:• Enter a degree in Celsius: 43• 43 Celsius is 109.4 Fahrenheit
Task 02
• (Compute the volume of a cylinder) Write a program that reads in the radius and length of a cylinder and computes the area and volume using the following formulas:
area = radius * radius * p
volume = area * length
• Here is a sample run:• Enter the radius and length of a cylinder: 5.5 12• The area is 95.0331• The volume is 1140.4
Introduction to OOP with Java - AKF Sep 2017
AbuKhleiF - www.abukhleif.com 29
Task 03
• (Financial application: calculate tips) Write a program that reads the subtotal and the gratuity rate, then computes the gratuity and total. For example, if the user enters 10 for subtotal and 15% for gratuity rate, the program displays $1.5 as gratuity and $11.5 as total.
• Here is a sample run:• Enter the subtotal and a gratuity rate: 10 15
• The gratuity is $1.5 and total is $11.5
Task 04
• (Find the number of years) Write a program that prompts the user to enter the minutes (e.g., 1 billion), and displays the number of years and days for the minutes.
• For simplicity, assume a year has 365 days.
• Here is a sample run:• Enter the number of minutes: 1000000000
• 1000000000 minutes is approximately 1902 years and 214 days
Introduction to OOP with Java - AKF Sep 2017
AbuKhleiF - www.abukhleif.com 30
Task 05
• (Health application: computing BMI) Body Mass Index (BMI) is a measure of health on weight. It can be calculated by taking your weight in kilograms and dividing by the square of your height in meters.
• Write a program that prompts the user to enter a weight in kilogramsand height in centimeters and displays the BMI.
• Here is a sample run:• Enter weight in kilograms: 80• Enter height in centimeters: 176• BMI is 25.82644
Task 06
• (Financial application: calculate interest) If you know the balance and the annual percentage interest rate, you can compute the interest on the next monthly payment using the following formula:
interest = balance * (annualInterestRate/1200)
• Write a program that reads the balance and the annual percentage interest rate and displays the interest for the next month.
• Here is a sample run:• Enter balance and interest rate (e.g., 3 for 3%): 1000 3.5• The interest is 2.91667
Introduction to OOP with Java - AKF Sep 2017
AbuKhleiF - www.abukhleif.com 31
Tasks Submission• Submit a zipped file contains 6 .java files, 1 file for each task.
• Upload your zipped file to the Facebook group.
• Submission due: Thursday, Sep 14
• Late submission will not be reviewed by the instructor.
• Public solutions upload goal is to share knowledge, you can see other’s solutions, but, please, don’t cheat yourself!
• Don’t forget, all tasks should be well-documented, well-designed, and well-styled.
Test Yourself
• Answer all questions (exclude 2.10):
http://www.cs.armstrong.edu/liang/interactivequiz/public_html/Chapter2.html
Introduction to OOP with Java - AKF Sep 2017
AbuKhleiF - www.abukhleif.com 32
- Liang, Introduction to Java Programming 10/e- Eng. Asma Abdel Karim Computer Engineering Department, JU Slides.- www.tutorialspoint.com/java/java_basic_operators.htm- www.javatpoint.com/java-naming-conventions- docs.oracle.com/javase/tutorial/essential/environment/cmdLineArgs.html- en.wikibooks.org/wiki/Java_Programming/Literals
Instructor: AbuKhleif, Mohammad Noor
Sep 2017
www.abukhleif.com
References:
End of Lecture =D
top related