SlideShare a Scribd company logo
Let’s dive
more more in
java
Hello!
I am Mohamed Essam !
You can find me at
mohamedessam.cs@gmail.com
2
“
“Talk is cheap. Show me the
code.”
― Linus Torvalds
3
Last time
Let’s start with the first set of slides
1
Simple java Program
public class Welcome {
public static void main(String[] args) {
// Display message Welcome to Java! A class Block
System.out.println("Welcome to Java!"); a method block
}
}
5
Welcome to Java!
Output
Special Characters
6
Numeric Operators
The operators for numeric data types include the standard arithmetic
operators:
○ addition (+),
○ subtraction (–),
○ multiplication (*),
○ division (/),
○ and remainder (%),
The operands are the values operated by an operator.
7
perform mathematical
computations
○ Listing 1.3 gives an example of evaluating.
8
public class ComputeExpression
{ public static void main(String[] args)
{
System.out.println((10.5 + 2 * 3) / (45 – 3.5));
}
}
Output
0.39759036144578314
Programing Expectation VS Reality
9
What bug is
The terms "bug" and "debugging" are popularly attributed to Admiral
Grace Hopper in the 1940s. While she was working on a Mark II computer
at Harvard University, her associates discovered a moth stuck in a relay
and thereby impeding operation, whereupon she remarked that they
were "debugging" the system. However, the term "bug", in the sense of
"technical error"
10
Types of errors
1. Syntax error:
Errors that are detected by the compiler are called syntax errors or
compile errors. Syntax errors result from errors in code construction,
such as mistyping a keyword, omitting some necessary punctuation,
or using an opening brace without a corresponding closing brace.
These errors are usually easy to detect because the compiler tells
you where they are and what caused them.
11
Types of errors
2. Runtime error:
Another example of runtime errors is division by zero. This happens
when the divisor is zero for integer divisions.
public class ShowRuntimeErrors {
public static void main(String[] args) {
System.out.println(1 / 0);
}
}
12
Types of errors
3. Logic Errors:
Logic errors occur when a program does not perform the way it was
intended to. Errors of this kind occur for many different reasons.
For example if we have a program prompt a user for input and
detect if the input is negative or positive we will notice that the
program will print the zero as a negative number because it’s less
than one.
public class LogicErrors {
public static void main(String[] args) {
int x=0;
if(x>=1)
{
System.out.println("positive");
}
else if(x<1)
{System.out.println("negative");
}
}
} 13
Augmented Assignment
Operators
○ The operators +, -, *, /, and % can be combined with the assignment operator to
form augmented operators.
○ Very often the current value of a variable is used, modified, and then
reassigned back to the same variable.
○ For example, the following statement increases the variable count by 1:
count = count + 1;
○ Java allows you to combine assignment and addition operators using
an augmented (or compound) assignment operator.
○ For example, the preceding statement can be written as count += 1; The
+= is called the addition assignment operator.
14
Augmented Assignment
Operators
15
Augmented Assignment
Operators
16
○ The augmented assignment operator is performed last after all the
other operators in the expression are evaluated. For example,
○ x /= 4 + 5.5 * 1.5;
○ is same as x = x / (4 + 5.5 * 1.5);
Increment and Decrement Operators
○ The ++ and —— are two shorthand operators for incrementing and decrementing a variable
by
○ These are handy because that’s often how much the value needs to be changed in many
programming tasks.
○ For example, the following code increments i by 1 and decrements j by 1. int i = 3, j = 3; i++;
○ // i becomes 4
○ j——;
○ // j becomes 2
○ These operators can also be placed before the variable.
○ For example, int i = 3, j = 3; ++i;
○ // i becomes 4 ——j;
○ // j becomes 2 ++i increments i by 1 and ——j decrements j by 1.
○ These operators are known as prefix increment (or preincrement) and prefix decrement (or
predecrement). As you see, the effect of i++ and ++i or i—— and ——i are the same in the
preceding examples. However, their effects are different when they are used in statements
that do more than just increment and decrement.
17
18
Let’s build a Gas station
system
Gas station system
We have a gas station wanted to build a
program to count the final price after fueling
the car with the gasoline.
Hint
the price of the fueling for
○ Gasoline 95 is 8 $.
○ Gasoline 92 is 7 $
○ Gasoline 80 is 5 $
○ We need a program to get the type of the
gasoline and the number of liters ,
calculate the total price and print it on the
screen.
19
Gas station pseudocode
○ get the input(Price ,Liters) from the user.
maybe from the machine itself or an admin for the system who can change the
price for liters when it increase.
○ Store it in two variables.
○ multiply the price in the liters and store it in a variable.
○ Print the number of liters and the price on the screen.
20
Variables
○ According to the integer and floating
variables in the last lecture we have six kinds
with different sizes
○ byte 1 byte -128 to 127
○ short 2 bytes -32,768 to 32,767
○ int 4 bytes -2,147,483,648 to 2,147,483,647
○ long 8 bytes -9,223,372,036,854,775,808 to 9,223,372,036,854,775,80.
○ float 4 bytes 7 decimal digits.
○ double 8 bytes 16 decimal digits.
21
In your opinion ?
○ Liters
○ The number liters for cars lies between 30 to 65 and can be a floating
number .
○ Hint :I have to put f in the end of the number of float like float x=3.1f. or use
double instead .
○ Gasoline price per liter
○ because the price of it is between 5 to 8 dollars and byte variable can
store up to 127
○ Also I don’t need to use short which up to 32,767 or int which are up to
2,147,483,647
○ Total cost
○ if we predict that there is a person can fuel his car 65 liters with gasoline
95 which are 8$ will liter the price will be 520 which already can store in
float which are up to 2,147,483,647.
22
○ Which types of variables I can use for my three variables Liters ,
Gasoline price and Total cost.
public class gasstation {
public static void main(String[] args) {
float x=30.55f;
byte y=8;
float z=x*y;
System.out.println(z);
//system.out.println(liters*gasolineprice);
}
}
23
244.4
Output
public class gasstation {
public static void main(String[] args) { Bad Design
float x=30.55f;
byte y=8;
float z=x*y;
System.out.println(z);
//system.out.println(liters*gasolineprice);
}
}
24
244.4
Output
25
How YOU can start writing clean code?
1.Use Descriptive Names
○ 1. What are variables, classes, and functions? There are many ways
to answer that, but when you really think about it, those things are
nothing more than the interface between a programmer and the
underlying logic of an application.
○ So when you use unclear and non-descript names for variables,
classes, and functions, you’re essentially obfuscating the
application logic from any programmer who reads the code,
including yourself.
○ “I’m not a great programmer; I’m just a good programmer with
great habits.”
— Kent Beck
○ What does a variable named x actually mean? Who knows. You’d
probably have to read the entire chunk of code to reverse
engineer its meaning. On the other hand, the meaning of a
variable like gasolineLiters is instantly recognizable. 26
public class gasstation {
public static void main(String[] args) {
float gasLiters=30.55f;
byte gasLiterPrice=8;
float totalCost=gasLiters*gasLiterPrice;
System.out.println(totalCost);
}
}
27
244.4
Output
How YOU can start writing clean code?
2.Write Good Comments
○ Write good comments” is the oldest piece of advice in the world of
programming. In fact, as soon as newbies are introduced to
comments, they’re pretty much encouraged to comment as often
as they can.
○ But it almost feels like we’ve swung too far in the opposite
direction. Newbies, in particular, tend to over-comment –
describing things that don’t need to be described and missing the
point of what a “good comment” actually is.
○ “Always code as if the guy who ends up maintaining your code will
be a violent psychopath who knows where you live.”
— John Woods
○ Here’s a good rule of thumb: comments exist to explain WHY a
piece of code exists rather than WHAT the code actually does. If
the code is written cleanly enough, it should be self-explanatory as
to what it does — the comment should shed light on the intention
behind why it was written. 28
29
2. Write Good Comments
public class gasstation {
public static void main(String[] args) {
float gasLiters=30.55f;
// For Gasoline 95
byte gasLiterPrice=8;
//the total cost of gasLiter which are the multiply of gasLiters * gasLiterPrice
float totalCost=gasLiters*gasLiterPrice;
System.out.println(totalCost);
}
}
30
244.4
Output
Prompting the user
for input in java
Enter your name:
31
Prompting the user
for input in java
○ To use a different gasLiters, you have to
modify the source code and recompile it. Obviously, this is not
convenient, so instead you can use the Scanner class for console
input.
○ Scanner reader= new Scanner(System.in);
The syntax new Scanner(System.in) creates an object of the Scanner
type. The syntax Scanner input declares that reader is a variable whose
type is Scanner.
○ So Scanner is class is something similar to the dog class that we
create last lecture to be as a template for us and to take an objects
from it to create multiple kinds of dogs with just one class template,
32
Football Video game use Object
oriented programing for create
players
○ what happening in Football games indeed they create one
class player and take objects for from it for all players
instead to create class for every player.
33
Prompting the user
for input in java
○ To invoke a method on an object is to ask the object to perform a
task. You can invoke the nextFloat() method to read a double value
as follows:
float gasLiters=reader.nextFloat();
○ This statement reads a number from the keyboard and assigns the
number to gasLiters variables.
import java.util.Scanner; // Scanner is in the java.util package
○ But don’t forget to import the class.
34
Reading Numbers from the
Keyboard
○ You know how to use the nextDouble() method in the Scanner class
to read a double value from the keyboard. You can also use the
methods listed in Table 2.2 to read a number of the byte, short, int,
long, and float type
35
Prompting the user
for input in java
import java.util.Scanner;
public class gasstation {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in); // Reading from System.in
int gasLiters= reader.nextFloat(); // Scans the next token of the input as an int.
36
import java.util.Scanner;
public class gasstation {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in); // Reading from System.in
// Prompt the user to enter the liters number
System.out.print("Enter the number of liters: ");
float gasLiters=reader.nextFloat();
// Prompt the user to enter a gas price
System.out.print("Enter the gas price : ");
byte gasLiterPrice=reader.nextByte();
float totalCost=gasLiters*gasLiterPrice;
System.out.println("the total cost is: "+totalCost);
}
} 37
if Statements
○ An if-else statement decides the execution path based on
whether the condition is true or false. A one-way if statement
performs an action if the specified condition is true. If the condition
is false, nothing is done. But what if you want to take alternative
actions when the condition is false? You can use a two-way if-else
statement. The actions that a two-way if-else statement specifies
differ based on whether the condition is true or false. Here is the
syntax for a two-way if-else statement:
○ if (boolean-expression)
○ {
○ statement(s)-for-the-true-case; }
○ else
○ {
○ statement(s)-for-the-false-case;
○ }
38
SimpleIfDemo.java
The program can decide which statements to execute based on a
condition. If you enter a negative value for radius in Listing 2.2,
ComputeAreaWithConsoleInput.java, the program displays an invalid
result. If the radius is negative, you don’t want the program to compute
the area. How can you deal with this situation? Like all high-level
programming languages, Java provides selection statements: statements
that let you choose actions with alternative courses. You can use
selection statement.
if (radius < 0) {
System.out.println("Incorrect input"); }
else {
area = radius * radius * 3.14159;
System.out.println("Area is " + area);
}
39
boolean Data Type
○ The boolean data type declares a variable with the value either
true or false. How do you compare two values, such as whether a
radius is greater than 0, equal to 0, or less than 0? Java provides six
relational operators (also known as comparison operators), shown
in Table 3.1, which can be used to compare two values (assume
radius is 5 in the table).
40
SimpleIfDemo.java 1
import java.util.Scanner;
public class SimpleIfDemo
{
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter your grade: ");
byte grade = input.nextByte();
if (grade > =50) System.out.println(“Passed");
else if (grade <50) System.out.println(“failed");
}
}
41
SimpleIfDemo.java 2
import java.util.Scanner;
public class SimpleIfDemo
{
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter an integer: ");
int number = input.nextInt();
if (number % 2 == 0) System.out.println(“Even");
else System.out.println(“odd");
}
}
42
SimpleIfDemo.java 4
if (score >= 90.0) System.out.print("A");
else if (score >= 80.0) System.out.print("B");
else if (score >= 70.0) System.out.print("C");
else if (score >= 60.0) System.out.print("D");
else System.out.print("F");
43
Build a program check the Pump
number using if statement before
calculating the total price
44
import java.util.Scanner;
public class Gasstation {
public static void main(String[] args) {
Scanner input =new Scanner(System.in);
System.out.print("Enter the pumpnumber:");
byte pumpnumber=input.nextByte();
if(pumpnumber==80)
{
System.out.print("Enter the number of gasliters:");
byte pumpprice=5;
float gasliters=input.nextFloat();
float totalcost=gasliters*pumpprice;
System.out.println("The total cost is :"+totalcost);
}
45
else if(pumpnumber==92)
{
byte pumpprice=7;
System.out.print("Enter the number of gasliters:");
float gasliters=input.nextFloat();
float totalcost=gasliters*pumpprice;
System.out.println("The total cost is :"+totalcost);
}
else if(pumpnumber==95)
{
byte pumpprice=8;
System.out.print("Enter the number of gasliters:");
float gasliters=input.nextFloat();
float totalcost=gasliters*pumpprice;
System.out.println("The total cost is :"+totalcost);
}
}
}
46
How YOU can start writing clean code?
3. Delete Unnecessary Code
We ascribe beauty to that which is simple; which has no superfluous
parts; which exactly answers its end...
— Ralph Waldo Emerson
Less is more. It’s a trite maxim, but sometimes it really is true.
Some of the most exciting improvements I remember making to code
involved removing vast chunks of it. Let me tell you, it’s a good feeling.
47
Logical Operators
○ The logical operators !, &&, ||, and ^ can be used to create a compound
Boolean expression. Sometimes, whether a statement is executed is
determined by a combination of several conditions. You can use logical
operators to combine these conditions to form a compound Boolean
expression. Logical operators, also known as Boolean operators, operate
on Boolean values to create a new Boolean value.
○ the not (!) operator, which negates true to false and false to true. Defines
○ (&&) operator. The and (&&) of two Boolean operands is true if and only if
both operands are true.
○ (||) operator. The or (||) of two Boolean operands is true if at least one of the
operands is true.
48
Naming Conventions
○ Sticking with the Java naming conventions makes your programs easy to read and avoids
errors.
○ Make sure that you choose descriptive names with straightforward
meanings for the variables, constants, classes, and methods in your
program. As mentioned earlier, names are case sensitive. Listed below
are the conventions for naming variables, methods, and classes.
○ ■ Use lowercase for variables and methods. If a name consists of
several words, concatenate them into one, making the first word
lowercase and capitalizing the first letter of each subsequent word—
for example, the variables radius and area and the method print.
○ ■ Capitalize the first letter of each word in a class name—for example,
the class names ComputeArea and System.
○ ■ Capitalize every letter in a constant, and use underscores between
words—for example, the constants PI and MAX_VALUE. It is important to
follow the naming conventions to make your programs easy to read.
49
Named Constants
○ A named constant is an identifier that represents a permanent value.
○ The value of a variable may change during the execution of a program, but a
named constant, or simply constant, represents permanent data that never
changes. In our ComputeArea program, p is a constant. If you use it frequently,
you don’t want to keep typing 3.14159; instead, you can declare a constant for p.
Here is the syntax for declaring a constant:
○ final datatype CONSTANTNAME = value;
○ A constant must be declared and initialized in the same statement. The word
final is a Java keyword for declaring a constant. For example, you can declare p
as a constan
50
ComputeAreaWithConstant.java
import java.util.Scanner;
// Scanner is in the java.util package
public class ComputeAreaWithConstant
{ public static void main(String[] args)
{
final double PI = 3.14159;
// Declare a constant // Create a Scanner object
Scanner input = new Scanner(System.in);
// Prompt the user to enter a radius
System.out.print("Enter a number for radius: ");
double radius = input.nextDouble();
// Compute area
double area = radius * radius * PI;
// Display result
System.out.println("The area for the circle of radius " + radius + " is " +
area); } } 51
import java.util.Scanner;
public class Gasstation {
public static void main(String[] args) {
final byte pumpprice80=5;
final byte pumpprice92=7;
final byte pumpprice95=8;
Scanner input =new Scanner(System.in);
System.out.print("Enter the pumpnumber:");
byte pumpnumber=input.nextByte();
if(pumpnumber==80)
{
System.out.print("Enter the number of gasliters:");
float gasliters=input.nextFloat();
float totalcost=gasliters*pumpprice80;
System.out.println("The total cost is :"+totalcost);
}
52
else if(pumpnumber==92)
{
System.out.print("Enter the number of gasliters:");
float gasliters=input.nextFloat();
float totalcost=gasliters*pumpprice92;
System.out.println("The total cost is :"+totalcost);
}
else if(pumpnumber==95)
{
System.out.print("Enter the number of gasliters:");
float gasliters=input.nextFloat();
float totalcost=gasliters*pumpprice95;
System.out.println("The total cost is :"+totalcost);
}
}
} 53
System.out.print("Enter the pumpnumber:");
byte pumpnumber=input.nextByte();
if (pumpnumber !=80 && pumpnumber !=92 &&
pumpnumber !=95)
{
main(args);
}
else
{
Continue the previous code
}
54
switch Statements
○ A switch statement executes statements based on the value of a
variable or an expression. The if statement in Listing 3.5,
ComputeTax.java, makes selections based on a single true or false
condition. There are four cases for computing taxes, which depend on
the value of status. To fully account for all the cases, nested if
statements were used. Overuse of nested if statements makes a
program difficult to read. Java provides a switch statement to simplify
coding for multiple conditions. You can write the following switch
statement to replace the nested if statement in Listing 3.5:
55
Simple java Program
Import java.util.Scanner;
Scanner input = new Scanner(System.in);
System.out.print("Enter the number: ");
int day=input.nextInt();
switch (day){
case 1:System.out.println("Saturday");
break;
case 2:System.out.println("Sunday");
break;
case 3:System.out.println("Monday");
break;
case 4:System.out.println("Tuesday");
break;
case 5:System.out.println("Wensday");
break;
case 6:System.out.println("Thursday");
break;
case 7:System.out.println("Friday");
break; }}
56
references
○ Beginning Programming with Java For Dummies, 4th Edition.
○ Data Structures and Problem Solving Using Java4edWeiss.
○ fundamentals-of-computer-science-using-java.
○ Head First Java.
○ Java The Complete Reference, 7th Edition.
○ CS50 introduction to Computer Science.
57
58
Thanks!
Any questions?

More Related Content

What's hot (20)

PPT
C#/.NET Little Pitfalls
BlackRabbitCoder
 
DOCX
Java se 8 fundamentals
megharajk
 
PPT
C++ OOP Implementation
Fridz Felisco
 
PPTX
Lambdas and Extension using VS2010
vgrondin
 
PPT
Ap Power Point Chpt5
dplunkett
 
PPTX
The "Evils" of Optimization
BlackRabbitCoder
 
PPTX
Insight into java 1.8, OOP VS FP
Syed Awais Mazhar Bukhari
 
PDF
Refactoring: Improve the design of existing code
Valerio Maggio
 
PPTX
Bad Smells in Code
Özge Nur KOÇ
 
PPTX
C++ first s lide
Sudhriti Gupta
 
PPTX
Summer Training Project On Python Programming
KAUSHAL KUMAR JHA
 
PPTX
OCA Java SE 8 Exam Chapter 2 Operators & Statements
İbrahim Kürce
 
PPT
Intro. to prog. c++
KurdGul
 
PPT
Principles in Refactoring
Chamnap Chhorn
 
PPT
Ap Power Point Chpt3 B
dplunkett
 
PPT
Programming Paradigms
Directi Group
 
PDF
The pseudocode
Asha Sari
 
PPT
Introduction
richsoden
 
PPTX
Effective Java - Chapter 3: Methods Common to All Objects
İbrahim Kürce
 
C#/.NET Little Pitfalls
BlackRabbitCoder
 
Java se 8 fundamentals
megharajk
 
C++ OOP Implementation
Fridz Felisco
 
Lambdas and Extension using VS2010
vgrondin
 
Ap Power Point Chpt5
dplunkett
 
The "Evils" of Optimization
BlackRabbitCoder
 
Insight into java 1.8, OOP VS FP
Syed Awais Mazhar Bukhari
 
Refactoring: Improve the design of existing code
Valerio Maggio
 
Bad Smells in Code
Özge Nur KOÇ
 
C++ first s lide
Sudhriti Gupta
 
Summer Training Project On Python Programming
KAUSHAL KUMAR JHA
 
OCA Java SE 8 Exam Chapter 2 Operators & Statements
İbrahim Kürce
 
Intro. to prog. c++
KurdGul
 
Principles in Refactoring
Chamnap Chhorn
 
Ap Power Point Chpt3 B
dplunkett
 
Programming Paradigms
Directi Group
 
The pseudocode
Asha Sari
 
Introduction
richsoden
 
Effective Java - Chapter 3: Methods Common to All Objects
İbrahim Kürce
 

Similar to Intro to programing with java-lecture 3 (20)

PPTX
JAVA CLASS PPT FOR ENGINEERING STUDENTS BBBBBBBBBBBBBBBBBBB
NagarathnaRajur2
 
PDF
Java Basics.pdf
EdFeranil
 
PPT
CSL101_Ch1.ppt
kavitamittal18
 
PPT
CSL101_Ch1.ppt
DrPriyaChittibabu
 
PPTX
CSL101_Ch1.pptx
shivanka2
 
PPTX
CSL101_Ch1.pptx
Ashwani Kumar
 
PPT
a basic java programming and data type.ppt
GevitaChinnaiah
 
PPT
Basic elements of java
Ahmad Idrees
 
PPT
CSL101_Ch1.ppt Computer Science
kavitamittal18
 
PPT
Programming with Java by Faizan Ahmed & Team
FaizanAhmed272398
 
PPT
Introduction to java programming with Fundamentals
rajipe1
 
PPT
Mobile computing for Bsc Computer Science
ReshmiGopinath4
 
PPT
Programming with Java - Essentials to program
leaderHilali1
 
PPT
Java Concepts with object oriented programming
KalpeshM7
 
PDF
Lec-2- Ehsjdjkck. Jdkdbd djskrogramming.pdf
RahulKumar342376
 
PPTX
Java fundamentals
HCMUTE
 
PPT
presentation of java fundamental
Ganesh Chittalwar
 
PDF
Cis 1403 lab1- the process of programming
Hamad Odhabi
 
PPT
ch02-primitive-data-definite-loops.ppt
ghoitsun
 
PPT
ch02-primitive-data-definite-loops.ppt
Mahyuddin8
 
JAVA CLASS PPT FOR ENGINEERING STUDENTS BBBBBBBBBBBBBBBBBBB
NagarathnaRajur2
 
Java Basics.pdf
EdFeranil
 
CSL101_Ch1.ppt
kavitamittal18
 
CSL101_Ch1.ppt
DrPriyaChittibabu
 
CSL101_Ch1.pptx
shivanka2
 
CSL101_Ch1.pptx
Ashwani Kumar
 
a basic java programming and data type.ppt
GevitaChinnaiah
 
Basic elements of java
Ahmad Idrees
 
CSL101_Ch1.ppt Computer Science
kavitamittal18
 
Programming with Java by Faizan Ahmed & Team
FaizanAhmed272398
 
Introduction to java programming with Fundamentals
rajipe1
 
Mobile computing for Bsc Computer Science
ReshmiGopinath4
 
Programming with Java - Essentials to program
leaderHilali1
 
Java Concepts with object oriented programming
KalpeshM7
 
Lec-2- Ehsjdjkck. Jdkdbd djskrogramming.pdf
RahulKumar342376
 
Java fundamentals
HCMUTE
 
presentation of java fundamental
Ganesh Chittalwar
 
Cis 1403 lab1- the process of programming
Hamad Odhabi
 
ch02-primitive-data-definite-loops.ppt
ghoitsun
 
ch02-primitive-data-definite-loops.ppt
Mahyuddin8
 
Ad

More from Mohamed Essam (20)

PPTX
Data Science Crash course
Mohamed Essam
 
PPTX
2.Feature Extraction
Mohamed Essam
 
PPTX
Data Science
Mohamed Essam
 
PPTX
Introduction to Robotics.pptx
Mohamed Essam
 
PPTX
Introduction_to_Gui_with_tkinter.pptx
Mohamed Essam
 
PPTX
Getting_Started_with_DL_in_Keras.pptx
Mohamed Essam
 
PPTX
Linear_algebra.pptx
Mohamed Essam
 
PPTX
Let_s_Dive_to_Deep_Learning.pptx
Mohamed Essam
 
PPTX
OOP-Advanced_Programming.pptx
Mohamed Essam
 
PPTX
1.Basic_Syntax
Mohamed Essam
 
PPTX
KNN.pptx
Mohamed Essam
 
PPTX
Regularization_BY_MOHAMED_ESSAM.pptx
Mohamed Essam
 
PPTX
1.What_if_Adham_Nour_tried_to_make_a_Machine_Learning_Model_at_Home.pptx
Mohamed Essam
 
PPTX
Clean_Code
Mohamed Essam
 
PPTX
Linear_Regression
Mohamed Essam
 
PPTX
2.Data_Strucures_and_modules.pptx
Mohamed Essam
 
PPTX
Naieve_Bayee.pptx
Mohamed Essam
 
PPTX
Activation_function.pptx
Mohamed Essam
 
PPTX
Deep_Learning_Frameworks
Mohamed Essam
 
PPTX
Neural_Network
Mohamed Essam
 
Data Science Crash course
Mohamed Essam
 
2.Feature Extraction
Mohamed Essam
 
Data Science
Mohamed Essam
 
Introduction to Robotics.pptx
Mohamed Essam
 
Introduction_to_Gui_with_tkinter.pptx
Mohamed Essam
 
Getting_Started_with_DL_in_Keras.pptx
Mohamed Essam
 
Linear_algebra.pptx
Mohamed Essam
 
Let_s_Dive_to_Deep_Learning.pptx
Mohamed Essam
 
OOP-Advanced_Programming.pptx
Mohamed Essam
 
1.Basic_Syntax
Mohamed Essam
 
KNN.pptx
Mohamed Essam
 
Regularization_BY_MOHAMED_ESSAM.pptx
Mohamed Essam
 
1.What_if_Adham_Nour_tried_to_make_a_Machine_Learning_Model_at_Home.pptx
Mohamed Essam
 
Clean_Code
Mohamed Essam
 
Linear_Regression
Mohamed Essam
 
2.Data_Strucures_and_modules.pptx
Mohamed Essam
 
Naieve_Bayee.pptx
Mohamed Essam
 
Activation_function.pptx
Mohamed Essam
 
Deep_Learning_Frameworks
Mohamed Essam
 
Neural_Network
Mohamed Essam
 
Ad

Recently uploaded (20)

PDF
Governing Geospatial Data at Scale: Optimizing ArcGIS Online with FME in Envi...
Safe Software
 
PDF
How to Visualize the ​Spatio-Temporal Data Using CesiumJS​
SANGHEE SHIN
 
PPTX
Paycifi - Programmable Trust_Breakfast_PPTXT
FinTech Belgium
 
PDF
Pipeline Industry IoT - Real Time Data Monitoring
Safe Software
 
PPTX
MARTSIA: A Tool for Confidential Data Exchange via Public Blockchain - Poster...
Michele Kryston
 
PDF
Kubernetes - Architecture & Components.pdf
geethak285
 
PDF
What’s my job again? Slides from Mark Simos talk at 2025 Tampa BSides
Mark Simos
 
PPTX
Agentforce World Tour Toronto '25 - MCP with MuleSoft
Alexandra N. Martinez
 
PDF
Bitkom eIDAS Summit | European Business Wallet: Use Cases, Macroeconomics, an...
Carsten Stoecker
 
PDF
ICONIQ State of AI Report 2025 - The Builder's Playbook
Razin Mustafiz
 
PDF
Optimizing the trajectory of a wheel loader working in short loading cycles
Reno Filla
 
PDF
Darley - FIRST Copenhagen Lightning Talk (2025-06-26) Epochalypse 2038 - Time...
treyka
 
PDF
TrustArc Webinar - Navigating APAC Data Privacy Laws: Compliance & Challenges
TrustArc
 
PPTX
Practical Applications of AI in Local Government
OnBoard
 
PDF
UiPath DevConnect 2025: Agentic Automation Community User Group Meeting
DianaGray10
 
PDF
Draugnet: Anonymous Threat Reporting for a World on Fire
treyka
 
PDF
🚀 Let’s Build Our First Slack Workflow! 🔧.pdf
SanjeetMishra29
 
PPTX
Smarter Governance with AI: What Every Board Needs to Know
OnBoard
 
PPTX
01_Approach Cyber- DORA Incident Management.pptx
FinTech Belgium
 
PDF
Sound the Alarm: Detection and Response
VICTOR MAESTRE RAMIREZ
 
Governing Geospatial Data at Scale: Optimizing ArcGIS Online with FME in Envi...
Safe Software
 
How to Visualize the ​Spatio-Temporal Data Using CesiumJS​
SANGHEE SHIN
 
Paycifi - Programmable Trust_Breakfast_PPTXT
FinTech Belgium
 
Pipeline Industry IoT - Real Time Data Monitoring
Safe Software
 
MARTSIA: A Tool for Confidential Data Exchange via Public Blockchain - Poster...
Michele Kryston
 
Kubernetes - Architecture & Components.pdf
geethak285
 
What’s my job again? Slides from Mark Simos talk at 2025 Tampa BSides
Mark Simos
 
Agentforce World Tour Toronto '25 - MCP with MuleSoft
Alexandra N. Martinez
 
Bitkom eIDAS Summit | European Business Wallet: Use Cases, Macroeconomics, an...
Carsten Stoecker
 
ICONIQ State of AI Report 2025 - The Builder's Playbook
Razin Mustafiz
 
Optimizing the trajectory of a wheel loader working in short loading cycles
Reno Filla
 
Darley - FIRST Copenhagen Lightning Talk (2025-06-26) Epochalypse 2038 - Time...
treyka
 
TrustArc Webinar - Navigating APAC Data Privacy Laws: Compliance & Challenges
TrustArc
 
Practical Applications of AI in Local Government
OnBoard
 
UiPath DevConnect 2025: Agentic Automation Community User Group Meeting
DianaGray10
 
Draugnet: Anonymous Threat Reporting for a World on Fire
treyka
 
🚀 Let’s Build Our First Slack Workflow! 🔧.pdf
SanjeetMishra29
 
Smarter Governance with AI: What Every Board Needs to Know
OnBoard
 
01_Approach Cyber- DORA Incident Management.pptx
FinTech Belgium
 
Sound the Alarm: Detection and Response
VICTOR MAESTRE RAMIREZ
 

Intro to programing with java-lecture 3

  • 2. Hello! I am Mohamed Essam ! You can find me at [email protected] 2
  • 3. “ “Talk is cheap. Show me the code.” ― Linus Torvalds 3
  • 4. Last time Let’s start with the first set of slides 1
  • 5. Simple java Program public class Welcome { public static void main(String[] args) { // Display message Welcome to Java! A class Block System.out.println("Welcome to Java!"); a method block } } 5 Welcome to Java! Output
  • 7. Numeric Operators The operators for numeric data types include the standard arithmetic operators: ○ addition (+), ○ subtraction (–), ○ multiplication (*), ○ division (/), ○ and remainder (%), The operands are the values operated by an operator. 7
  • 8. perform mathematical computations ○ Listing 1.3 gives an example of evaluating. 8 public class ComputeExpression { public static void main(String[] args) { System.out.println((10.5 + 2 * 3) / (45 – 3.5)); } } Output 0.39759036144578314
  • 10. What bug is The terms "bug" and "debugging" are popularly attributed to Admiral Grace Hopper in the 1940s. While she was working on a Mark II computer at Harvard University, her associates discovered a moth stuck in a relay and thereby impeding operation, whereupon she remarked that they were "debugging" the system. However, the term "bug", in the sense of "technical error" 10
  • 11. Types of errors 1. Syntax error: Errors that are detected by the compiler are called syntax errors or compile errors. Syntax errors result from errors in code construction, such as mistyping a keyword, omitting some necessary punctuation, or using an opening brace without a corresponding closing brace. These errors are usually easy to detect because the compiler tells you where they are and what caused them. 11
  • 12. Types of errors 2. Runtime error: Another example of runtime errors is division by zero. This happens when the divisor is zero for integer divisions. public class ShowRuntimeErrors { public static void main(String[] args) { System.out.println(1 / 0); } } 12
  • 13. Types of errors 3. Logic Errors: Logic errors occur when a program does not perform the way it was intended to. Errors of this kind occur for many different reasons. For example if we have a program prompt a user for input and detect if the input is negative or positive we will notice that the program will print the zero as a negative number because it’s less than one. public class LogicErrors { public static void main(String[] args) { int x=0; if(x>=1) { System.out.println("positive"); } else if(x<1) {System.out.println("negative"); } } } 13
  • 14. Augmented Assignment Operators ○ The operators +, -, *, /, and % can be combined with the assignment operator to form augmented operators. ○ Very often the current value of a variable is used, modified, and then reassigned back to the same variable. ○ For example, the following statement increases the variable count by 1: count = count + 1; ○ Java allows you to combine assignment and addition operators using an augmented (or compound) assignment operator. ○ For example, the preceding statement can be written as count += 1; The += is called the addition assignment operator. 14
  • 16. Augmented Assignment Operators 16 ○ The augmented assignment operator is performed last after all the other operators in the expression are evaluated. For example, ○ x /= 4 + 5.5 * 1.5; ○ is same as x = x / (4 + 5.5 * 1.5);
  • 17. Increment and Decrement Operators ○ The ++ and —— are two shorthand operators for incrementing and decrementing a variable by ○ These are handy because that’s often how much the value needs to be changed in many programming tasks. ○ For example, the following code increments i by 1 and decrements j by 1. int i = 3, j = 3; i++; ○ // i becomes 4 ○ j——; ○ // j becomes 2 ○ These operators can also be placed before the variable. ○ For example, int i = 3, j = 3; ++i; ○ // i becomes 4 ——j; ○ // j becomes 2 ++i increments i by 1 and ——j decrements j by 1. ○ These operators are known as prefix increment (or preincrement) and prefix decrement (or predecrement). As you see, the effect of i++ and ++i or i—— and ——i are the same in the preceding examples. However, their effects are different when they are used in statements that do more than just increment and decrement. 17
  • 18. 18 Let’s build a Gas station system
  • 19. Gas station system We have a gas station wanted to build a program to count the final price after fueling the car with the gasoline. Hint the price of the fueling for ○ Gasoline 95 is 8 $. ○ Gasoline 92 is 7 $ ○ Gasoline 80 is 5 $ ○ We need a program to get the type of the gasoline and the number of liters , calculate the total price and print it on the screen. 19
  • 20. Gas station pseudocode ○ get the input(Price ,Liters) from the user. maybe from the machine itself or an admin for the system who can change the price for liters when it increase. ○ Store it in two variables. ○ multiply the price in the liters and store it in a variable. ○ Print the number of liters and the price on the screen. 20
  • 21. Variables ○ According to the integer and floating variables in the last lecture we have six kinds with different sizes ○ byte 1 byte -128 to 127 ○ short 2 bytes -32,768 to 32,767 ○ int 4 bytes -2,147,483,648 to 2,147,483,647 ○ long 8 bytes -9,223,372,036,854,775,808 to 9,223,372,036,854,775,80. ○ float 4 bytes 7 decimal digits. ○ double 8 bytes 16 decimal digits. 21
  • 22. In your opinion ? ○ Liters ○ The number liters for cars lies between 30 to 65 and can be a floating number . ○ Hint :I have to put f in the end of the number of float like float x=3.1f. or use double instead . ○ Gasoline price per liter ○ because the price of it is between 5 to 8 dollars and byte variable can store up to 127 ○ Also I don’t need to use short which up to 32,767 or int which are up to 2,147,483,647 ○ Total cost ○ if we predict that there is a person can fuel his car 65 liters with gasoline 95 which are 8$ will liter the price will be 520 which already can store in float which are up to 2,147,483,647. 22 ○ Which types of variables I can use for my three variables Liters , Gasoline price and Total cost.
  • 23. public class gasstation { public static void main(String[] args) { float x=30.55f; byte y=8; float z=x*y; System.out.println(z); //system.out.println(liters*gasolineprice); } } 23 244.4 Output
  • 24. public class gasstation { public static void main(String[] args) { Bad Design float x=30.55f; byte y=8; float z=x*y; System.out.println(z); //system.out.println(liters*gasolineprice); } } 24 244.4 Output
  • 25. 25
  • 26. How YOU can start writing clean code? 1.Use Descriptive Names ○ 1. What are variables, classes, and functions? There are many ways to answer that, but when you really think about it, those things are nothing more than the interface between a programmer and the underlying logic of an application. ○ So when you use unclear and non-descript names for variables, classes, and functions, you’re essentially obfuscating the application logic from any programmer who reads the code, including yourself. ○ “I’m not a great programmer; I’m just a good programmer with great habits.” — Kent Beck ○ What does a variable named x actually mean? Who knows. You’d probably have to read the entire chunk of code to reverse engineer its meaning. On the other hand, the meaning of a variable like gasolineLiters is instantly recognizable. 26
  • 27. public class gasstation { public static void main(String[] args) { float gasLiters=30.55f; byte gasLiterPrice=8; float totalCost=gasLiters*gasLiterPrice; System.out.println(totalCost); } } 27 244.4 Output
  • 28. How YOU can start writing clean code? 2.Write Good Comments ○ Write good comments” is the oldest piece of advice in the world of programming. In fact, as soon as newbies are introduced to comments, they’re pretty much encouraged to comment as often as they can. ○ But it almost feels like we’ve swung too far in the opposite direction. Newbies, in particular, tend to over-comment – describing things that don’t need to be described and missing the point of what a “good comment” actually is. ○ “Always code as if the guy who ends up maintaining your code will be a violent psychopath who knows where you live.” — John Woods ○ Here’s a good rule of thumb: comments exist to explain WHY a piece of code exists rather than WHAT the code actually does. If the code is written cleanly enough, it should be self-explanatory as to what it does — the comment should shed light on the intention behind why it was written. 28
  • 29. 29 2. Write Good Comments
  • 30. public class gasstation { public static void main(String[] args) { float gasLiters=30.55f; // For Gasoline 95 byte gasLiterPrice=8; //the total cost of gasLiter which are the multiply of gasLiters * gasLiterPrice float totalCost=gasLiters*gasLiterPrice; System.out.println(totalCost); } } 30 244.4 Output
  • 31. Prompting the user for input in java Enter your name: 31
  • 32. Prompting the user for input in java ○ To use a different gasLiters, you have to modify the source code and recompile it. Obviously, this is not convenient, so instead you can use the Scanner class for console input. ○ Scanner reader= new Scanner(System.in); The syntax new Scanner(System.in) creates an object of the Scanner type. The syntax Scanner input declares that reader is a variable whose type is Scanner. ○ So Scanner is class is something similar to the dog class that we create last lecture to be as a template for us and to take an objects from it to create multiple kinds of dogs with just one class template, 32
  • 33. Football Video game use Object oriented programing for create players ○ what happening in Football games indeed they create one class player and take objects for from it for all players instead to create class for every player. 33
  • 34. Prompting the user for input in java ○ To invoke a method on an object is to ask the object to perform a task. You can invoke the nextFloat() method to read a double value as follows: float gasLiters=reader.nextFloat(); ○ This statement reads a number from the keyboard and assigns the number to gasLiters variables. import java.util.Scanner; // Scanner is in the java.util package ○ But don’t forget to import the class. 34
  • 35. Reading Numbers from the Keyboard ○ You know how to use the nextDouble() method in the Scanner class to read a double value from the keyboard. You can also use the methods listed in Table 2.2 to read a number of the byte, short, int, long, and float type 35
  • 36. Prompting the user for input in java import java.util.Scanner; public class gasstation { public static void main(String[] args) { Scanner reader = new Scanner(System.in); // Reading from System.in int gasLiters= reader.nextFloat(); // Scans the next token of the input as an int. 36
  • 37. import java.util.Scanner; public class gasstation { public static void main(String[] args) { Scanner reader = new Scanner(System.in); // Reading from System.in // Prompt the user to enter the liters number System.out.print("Enter the number of liters: "); float gasLiters=reader.nextFloat(); // Prompt the user to enter a gas price System.out.print("Enter the gas price : "); byte gasLiterPrice=reader.nextByte(); float totalCost=gasLiters*gasLiterPrice; System.out.println("the total cost is: "+totalCost); } } 37
  • 38. if Statements ○ An if-else statement decides the execution path based on whether the condition is true or false. A one-way if statement performs an action if the specified condition is true. If the condition is false, nothing is done. But what if you want to take alternative actions when the condition is false? You can use a two-way if-else statement. The actions that a two-way if-else statement specifies differ based on whether the condition is true or false. Here is the syntax for a two-way if-else statement: ○ if (boolean-expression) ○ { ○ statement(s)-for-the-true-case; } ○ else ○ { ○ statement(s)-for-the-false-case; ○ } 38
  • 39. SimpleIfDemo.java The program can decide which statements to execute based on a condition. If you enter a negative value for radius in Listing 2.2, ComputeAreaWithConsoleInput.java, the program displays an invalid result. If the radius is negative, you don’t want the program to compute the area. How can you deal with this situation? Like all high-level programming languages, Java provides selection statements: statements that let you choose actions with alternative courses. You can use selection statement. if (radius < 0) { System.out.println("Incorrect input"); } else { area = radius * radius * 3.14159; System.out.println("Area is " + area); } 39
  • 40. boolean Data Type ○ The boolean data type declares a variable with the value either true or false. How do you compare two values, such as whether a radius is greater than 0, equal to 0, or less than 0? Java provides six relational operators (also known as comparison operators), shown in Table 3.1, which can be used to compare two values (assume radius is 5 in the table). 40
  • 41. SimpleIfDemo.java 1 import java.util.Scanner; public class SimpleIfDemo { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.println("Enter your grade: "); byte grade = input.nextByte(); if (grade > =50) System.out.println(“Passed"); else if (grade <50) System.out.println(“failed"); } } 41
  • 42. SimpleIfDemo.java 2 import java.util.Scanner; public class SimpleIfDemo { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.println("Enter an integer: "); int number = input.nextInt(); if (number % 2 == 0) System.out.println(“Even"); else System.out.println(“odd"); } } 42
  • 43. SimpleIfDemo.java 4 if (score >= 90.0) System.out.print("A"); else if (score >= 80.0) System.out.print("B"); else if (score >= 70.0) System.out.print("C"); else if (score >= 60.0) System.out.print("D"); else System.out.print("F"); 43
  • 44. Build a program check the Pump number using if statement before calculating the total price 44
  • 45. import java.util.Scanner; public class Gasstation { public static void main(String[] args) { Scanner input =new Scanner(System.in); System.out.print("Enter the pumpnumber:"); byte pumpnumber=input.nextByte(); if(pumpnumber==80) { System.out.print("Enter the number of gasliters:"); byte pumpprice=5; float gasliters=input.nextFloat(); float totalcost=gasliters*pumpprice; System.out.println("The total cost is :"+totalcost); } 45
  • 46. else if(pumpnumber==92) { byte pumpprice=7; System.out.print("Enter the number of gasliters:"); float gasliters=input.nextFloat(); float totalcost=gasliters*pumpprice; System.out.println("The total cost is :"+totalcost); } else if(pumpnumber==95) { byte pumpprice=8; System.out.print("Enter the number of gasliters:"); float gasliters=input.nextFloat(); float totalcost=gasliters*pumpprice; System.out.println("The total cost is :"+totalcost); } } } 46
  • 47. How YOU can start writing clean code? 3. Delete Unnecessary Code We ascribe beauty to that which is simple; which has no superfluous parts; which exactly answers its end... — Ralph Waldo Emerson Less is more. It’s a trite maxim, but sometimes it really is true. Some of the most exciting improvements I remember making to code involved removing vast chunks of it. Let me tell you, it’s a good feeling. 47
  • 48. Logical Operators ○ The logical operators !, &&, ||, and ^ can be used to create a compound Boolean expression. Sometimes, whether a statement is executed is determined by a combination of several conditions. You can use logical operators to combine these conditions to form a compound Boolean expression. Logical operators, also known as Boolean operators, operate on Boolean values to create a new Boolean value. ○ the not (!) operator, which negates true to false and false to true. Defines ○ (&&) operator. The and (&&) of two Boolean operands is true if and only if both operands are true. ○ (||) operator. The or (||) of two Boolean operands is true if at least one of the operands is true. 48
  • 49. Naming Conventions ○ Sticking with the Java naming conventions makes your programs easy to read and avoids errors. ○ Make sure that you choose descriptive names with straightforward meanings for the variables, constants, classes, and methods in your program. As mentioned earlier, names are case sensitive. Listed below are the conventions for naming variables, methods, and classes. ○ ■ Use lowercase for variables and methods. If a name consists of several words, concatenate them into one, making the first word lowercase and capitalizing the first letter of each subsequent word— for example, the variables radius and area and the method print. ○ ■ Capitalize the first letter of each word in a class name—for example, the class names ComputeArea and System. ○ ■ Capitalize every letter in a constant, and use underscores between words—for example, the constants PI and MAX_VALUE. It is important to follow the naming conventions to make your programs easy to read. 49
  • 50. Named Constants ○ A named constant is an identifier that represents a permanent value. ○ The value of a variable may change during the execution of a program, but a named constant, or simply constant, represents permanent data that never changes. In our ComputeArea program, p is a constant. If you use it frequently, you don’t want to keep typing 3.14159; instead, you can declare a constant for p. Here is the syntax for declaring a constant: ○ final datatype CONSTANTNAME = value; ○ A constant must be declared and initialized in the same statement. The word final is a Java keyword for declaring a constant. For example, you can declare p as a constan 50
  • 51. ComputeAreaWithConstant.java import java.util.Scanner; // Scanner is in the java.util package public class ComputeAreaWithConstant { public static void main(String[] args) { final double PI = 3.14159; // Declare a constant // Create a Scanner object Scanner input = new Scanner(System.in); // Prompt the user to enter a radius System.out.print("Enter a number for radius: "); double radius = input.nextDouble(); // Compute area double area = radius * radius * PI; // Display result System.out.println("The area for the circle of radius " + radius + " is " + area); } } 51
  • 52. import java.util.Scanner; public class Gasstation { public static void main(String[] args) { final byte pumpprice80=5; final byte pumpprice92=7; final byte pumpprice95=8; Scanner input =new Scanner(System.in); System.out.print("Enter the pumpnumber:"); byte pumpnumber=input.nextByte(); if(pumpnumber==80) { System.out.print("Enter the number of gasliters:"); float gasliters=input.nextFloat(); float totalcost=gasliters*pumpprice80; System.out.println("The total cost is :"+totalcost); } 52
  • 53. else if(pumpnumber==92) { System.out.print("Enter the number of gasliters:"); float gasliters=input.nextFloat(); float totalcost=gasliters*pumpprice92; System.out.println("The total cost is :"+totalcost); } else if(pumpnumber==95) { System.out.print("Enter the number of gasliters:"); float gasliters=input.nextFloat(); float totalcost=gasliters*pumpprice95; System.out.println("The total cost is :"+totalcost); } } } 53
  • 54. System.out.print("Enter the pumpnumber:"); byte pumpnumber=input.nextByte(); if (pumpnumber !=80 && pumpnumber !=92 && pumpnumber !=95) { main(args); } else { Continue the previous code } 54
  • 55. switch Statements ○ A switch statement executes statements based on the value of a variable or an expression. The if statement in Listing 3.5, ComputeTax.java, makes selections based on a single true or false condition. There are four cases for computing taxes, which depend on the value of status. To fully account for all the cases, nested if statements were used. Overuse of nested if statements makes a program difficult to read. Java provides a switch statement to simplify coding for multiple conditions. You can write the following switch statement to replace the nested if statement in Listing 3.5: 55
  • 56. Simple java Program Import java.util.Scanner; Scanner input = new Scanner(System.in); System.out.print("Enter the number: "); int day=input.nextInt(); switch (day){ case 1:System.out.println("Saturday"); break; case 2:System.out.println("Sunday"); break; case 3:System.out.println("Monday"); break; case 4:System.out.println("Tuesday"); break; case 5:System.out.println("Wensday"); break; case 6:System.out.println("Thursday"); break; case 7:System.out.println("Friday"); break; }} 56
  • 57. references ○ Beginning Programming with Java For Dummies, 4th Edition. ○ Data Structures and Problem Solving Using Java4edWeiss. ○ fundamentals-of-computer-science-using-java. ○ Head First Java. ○ Java The Complete Reference, 7th Edition. ○ CS50 introduction to Computer Science. 57