0% found this document useful (0 votes)
7 views280 pages

Java

Uploaded by

Josh
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
7 views280 pages

Java

Uploaded by

Josh
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 280

JAVA PROGRAMMING FOR

BEGINNERS

By, Abd El Fattah Khatib.


PART 1
THE JAVA IDE - ECLIPSE

By, Abd El Fattah Khatib.


WE ARE GOING TO DOWNLOAD THE
ECLIPSE IDE, THE EDITOR WE ARE
GOING TO USE TO WRITE JAVA CODE.

IDE STANDS FOR INTEGRATED


DEVELOPMENT ENVIRONMENT
CREATE A FOLDER CALLED JAVA ON
YOUR DESKTOP
OPEN YOUR BROWSER AND GO TO
GOOGLE.COM
TYPE ECLIPSE IN THE SEARCH BAR
Click the link to
Eclipse.org
Scroll down and click the
download button
Click on Download
Wait for the download to
finish
Open the downloaded file
In the installer pick this
option
In the installer, click install
Wait on the install to
finish.
Click on launch
Click on launch
Click on launch
Click on this option to
create a project or click
file in the toolbar
Click on this option to
create a project
Give your program a name

We can change the location


to Desktop/java folder on our
desktop
When done click Finish
Choose - Don’t Create -
option
Choose Class –
Create a new class option
Give it the name – Main
Check this option
Make sure this option is
checked and click Finish
These lines of Code will be used in every java
program that we write

The // are used to write a comment


The line after // is a comment and is ignored by the
compiler (or IDE), they are not part of the java code
and do nothing in terms of programming or what
the program we write will do.
After Downloading Search for eclipse in the
windows search bar
Choose Pin to taskbar
Open file Location
Put a copy of Eclipse to your
Desktop
Make sure you have a file called
Java on your desktop as well
Launch Eclipse and make sure to
click Browse and set this Path
for the Eclipse IDE

When done click Launch


Choose close
Create a new java project
Give the project a name

Path is set to where we set it


during launch

When done click finish


Choose don’t create
Call it Main

Check this one


Type this line
Click run to run the program

Or this one
Click Ok
The output is in the console
Hello world was printed
COMMENTS WITH // AND /* */
The comment line,
The line after // did nothing in this program
Try to replace the line after // with any text you want
and then run the program and nothing will change, the
program will still print Hello World! Every time.

// are used to start a comment line, a line that is not


considered a line code but a comment the user put for
some reason and doesn’t affect the code in the program.
The comment here is different and the
program still does the same thing.
We can also use /* */ to write comment
The comments start after /*
And ends only when we close the comment with */
So comments in this case can expand to many lines
On other hand , comments with // are only valid for one line.
Always make sure to save your file
ERRORS IN THE CONSOLE
IF there are errors in the code(line 11 is
missing a semicolon (;) at the end,
You will get a message saying so when
you try to run the program.
A message telling you what the Click on the error and the IDE
error is . ; is missing in line 11. will highlight the line with error
in it.
JAVA PROGRAMMING FOR
BEGINNERS

By, Abd El Fattah Khatib.


PART 1
VARIABLES

By, Abd El Fattah Khatib.


System.out.Println*( is method that prints the
string it has in parentheses()
If we change the string the method will print
something else
System.out.Println*( is method that prints the
string it has in parentheses()
We changed the string and the console has a
different output now
System.out.Println*( is method that prints the
string it has in parentheses() - it can print
numbers or strings)
We can create number variables in java.
In line 7 we created variable x that stores 10.
In line 8 , we used println() to print the
variable to the consol.e.
In line 8, we declared a variable and assigned
variable x and assigned value to it – we
initialized it. It holds 10 and it’s ready to be
used. For

In Line 9, we declared variable y but we did not


assign value to it - we did not initialize it.
Int Line 10 we assign data to it. From line 10
and on y is equal to 10.

Int Line 12, we declared variable z and we did


not assign data to it. So we don’t know what’s
the data in it.
We should not use a variable before
assigning a data to it. Don’t use z before
assigning data to it(for example as in line
12, we assign a number to y).
Trying to print z caused an error

We should not use a variable before


assigning a data to it. Don’t use z
before assigning data to it(for
example as in line 12, we assign a
number to y).
Trying to print z caused an error
THE SYNTAX FOR DECLARING OR
INITIALIZING A VARIABLE

Int key word is used to declare variables of type int which can store only
complete numbers.
-----------------------------------------------------------------------------------------------------
Int x = 10; (initialize a variable of type int)
The syntax is :
Variable_type variable_name = value ;
-----------------------------------------------------------------------------------------------------
Int x; (declaring a variable of type int)
The synatax is :
Variable_type variable_name ;
So far we have seen that:
System.out.println() can work with a :
string
Int ( a number)
And print them to the screen.
We can change x’s value
Line 9 – we change x’s value from 10 to 20
X =10 * 20; (200) multiply 10 by 20
X = 20/10; (2) divide 20 by 10
X = 10 + 20 (30) add x to 20
X = 10 – 20 (-10) substract 10 from 20

As you can see, x of type int can store negative


numbers as well.
X’s value changes on the next assignment
For example: from line 10 to 12 x’s value is 30
From line 13 to 15 x’s value is 200.

Operator Operation
+ Addition
- Substraction
* Multiplying
/ Division
OPERATORS SYNTAX

Int x;
X = 10 + 20 ;
Variable = oprerand1 operator operator2;
On the right side of = we perform the operations on numbers.
On the left side of = we have the variable we want to assign the result of the
operations to.
We can perform operations between
variables of the same type(int)
X – holds the lowest number an int can hold
Y – holds the biggest number an int can hold
We can use the + operator between a string
an int inside of system.out.println() to print
to the console the value of x at the same
time we’re printing a string.
We can use the + operator between a string
an int inside of system.out.println() to print
to the console the a number at the same
time we’re printing a string.
FLOATING NUMBERS

There are to primitive types for holding floating numbers:

Float
Double – has more precision than float.

Double and float can hold whole numbers as well.


Double variable can hold a floating point
number
Double variable can hold a whole number
In System.out.println() we can use the
operator + more than once to print mixed
values of strings, doubles (and ints).
CHAR PRIMITIVE TYPE

• Chars are used to store one character.


• Char c =we ‘a’;
• C stores the letter a in it.
• We use special marks ‘ ‘ to indicate it’s once character
• Each character has a Unicode code and a decimal value
You can use the website: Unicode-table.com to get
the unicodes for all characters
‘a’ – has a decimal value of 97
Char c = ‘a’ is the same as typing
char c = 97.
‘a’ has the Unicode ‘\u0061’ , the because it is in line
0060 and in column 1(one) so its Unicode is 0061

Char c = ‘a’ is equal to typing


char c = ‘\u0061’
C1 ,c2, c3 all hold the character ‘a’.
In the console the character a is printed 3 times.
BOOLEAN PRIMITIVE TYPE

In java there is a variable type called Boolean


Bool b1 = true;
Bool b2 = false;
The only two values a Boolean(bool) variable can hold can either be true or false
True’s value is 1
False’s value is 0
STRING

• String is actually is a class type.


• A string can is a sequence of char variable type.
We can convert a number to a string using the
operator + between a string and an int and we can
assign the result value to a string variable.
MORE OPERATORS
X can appear of the left side and the right side of the
assignment at the same time
VARIABLE TYPES
These are the kinds of variables we are going to focus on in this course:
Int – stores whole numbers.
Double – stores numbers with floating point.
String – stores strings
Boolean – can store only either true or false
Boolean variables will be used in conditional statements
System.out.prinln(x) – prints the value of x to the console
It prints or goes on to a new line automatically
System.out.prinln() – can print different types to the console
System.out.println() – we use operator + inside the parentheses () of
println which casts the type of any variable to a String

String + int = String


String + double = String
String + String = String
String + variable converts the statement to a string

String + int = String


String + double = String
String + String = String
We must declare variables (names) before we can use them.
Using an undeclared variable will cause an error and will prevent the
program from running
We want to assign values to variables before we can use them. In this
example we do that in line 7.
ACCEPTING INPUT FROM THE USER
We type lines 4 ,6 and 7 to declare scanner. An object that we can use to
accept input from the user
We use scanner.nextInt() to get an integer from the user
We user scanner.next() to get a string from the user
Notice only the word java was used . So strings ends we get using
scanner.nextInt() are determined by spaces or pressing enter
We are going to use scanner.nextLine() for the purpose of getting a whole
line from the user
USING SCANNER.NEXTLINE()
Scanner.nextLine() - get a whole line from the user as a string
Scanner.nextLine() – get a whole line from the user as a string
In this case when we press enter we get the empty input for input 2
The solution is to flush the input
We preform an “extra” scanner.nextLine();
Notice there is operator priority
x * y is performed then String + (Int result) is casted to string.
CASTING
Cannot assign variable of type double to int
We need to cast double to int first
OPERATORS BETWEEN NUMBERS

• The operators we are going to talk about are


• + , *, -
• ++ , --
• += , -= …
• / ,%
10 divided by 3 is 3 and the remainder is 1 so the answer here is 1.
The result is 3.33 and because its an operation between two ints the
result is rounded down to 3.
We can use casting
THE DIFFERENCE BETWEEN X++ AND
++X
MORE OPERATORS
Operator Operation
X += Y X = X +Y
X *= Y X = X*Y
X -= Y X = X -Y
X /= Y X = X /Y
X %= Y X = X %Y
… …
CONDITIONAL STATEMENTS
Operators
X == Y Returns true if x and y have the same
values
X < Y Returns true if x is smaller than y
X != Y Returns true if x and y have different
values
X >= Y Returns true if x is bigger or equal to y
MORE OPERATORS

• We have the operators:


&& the and operator
|| the or operator
X Y X && Y
False False False
False True False
True False False
True True True

X Y X || Y
False False False
False True True
True False True
True True True
IF ELSE
If the condition inside if ( condition) is true the if block is executed
otherwise the else block is executed;
This code is the same as in the previous slide.
THE SWITCH STATEMENT
The break statement will cause the compiler to execute line 18 , 19 then
jump to 22 and skip the rest of the code until that line
Without break in line 19
The code will executed lines 20 and 21 as well
This code does the same as the code in the previous slide
FOR LOOP
FOR LOOP

For (Initializations ; condition ; modifiers ){


for loop body code
}
On the first run initializations are executed only once , then condition is
check if the condition is true the for body is executed until the end of the
block then the compiler jumps to modifier then to condition and if the
condition is true to for loop body code then moidifiers and so on and so
on until condition is check and it is false the compiler will jump our of the
for body block.
FOR LOOP

• In the first run , i is declared and assigned the value 1(only on the first
run will the compiler execute this part of the code) then then
condition i<= number is checked it’s true so the first run is executed
(line 10) then the compiler jumped to i++;
• Then the compiler jumps to check i<= number (it’s true) so the second
run starts and line 10 is executed and the the compiler jumps to i++
and then jumped to check if i <= number and so on and son on
• The program will stop when i > number in the condition check and will
jump to line 12
Break will cause the for loop to stop
It will terminate the for run and jump to line 15.
The continue keyword will case the run to stop on line 11 and
jump to line 9 to execute the next iteration or run
Lines 12 13 and 14 are skipped on the run which if fulfills the
condition in.
WHILE LOOP

• The while loop functions the same way as the for loop does
TASK

• Write a program that accepts from the user an unlimited amount of positive
numbers and stops when the user inters a negative number.
• The program prints to the console the average of the numbers.
NESTED LOOPS

This code explains how i and j appear in the loop


TASK

• Print a board of size 5x 5 that consists of X and O


XOXOX
OXOXO
XOXOX
OXOXO
XOXOX
PART
ARRAYS

By, Abd El Fattah Khatib.


ARRAYS
• We use operator [ ] to access array elements
• Array [i] accesses the element i
• Array of size 10 contains elements from array[0] to array[9]
• Array[0] is the first element array[9] is the last element
• Don’t access arrays with out of range index!
• It will cause an error
• We can initialize an array with brackets { } . The size of array
is determined by the number of elements in brackets.
• Less practical.
• Array.length returns the length of an array.
ARRAYS CAN BE OF DIFFERENT TYPES
TWO DIMENSIONAL ARRAYS
PART
STRINGS

By, Abd El Fattah Khatib.


STRINGS
METHODS
• Line 6 is a method call . The method implemented
from line 9 to 17 is called.
• Line 9 to 17 is the implementation of the function
method.
• Line 9 (until the “{“ ) is the declaration of the
method called max.
• a method starts with public static.
• A method must have a :
• Return type – in the case it’s void , it can be of any
type (int, double, String , void …)
• It has a name – in this case it’s max
• It has a arguments list (of any type) of any number
of arguments (int this case 2 , of type int which are
a & b).
• Same method as before but returns int
and not void.
METHODS OVERLOADING
• Two methods can have the same function name,
line 12 and line 22, this is called FUNCTION
OVERLOADING.
• Two methods can have :
the same name but must have different number of
arguments and types or same number of arguments
but are of different types
Argument list is the arguments in parentheses ( … )
after the method name and before the ;{‘ char.
Its called method overloading
Methods are disquotable by the argument list (types
and number of arguments)
Methods are NOT distinguishable by the return type
Two methods with the same name and same
arguments list and different return type will cause an
error they cannot be overloaded this way.
Two methods with the same name and
arguments list is an error.
The IDE will till you the same method
has been implemented twice
In the example. Line 12 and line 22.
PART
SEARCHING ALGORITHMS

By, Abd El Fattah Khatib.


LINEAR SEARCH

• We have an array of numbers and we want to check if a value is in the array, if


it is return the index of the value else return -1.
• Solution: we iterate over the array element by element if the value is equal to
the current element in the array we return the index, return the index.
• Else we are done and we return -1 because the value was not found in the
array.
• Note: the method returns the index of the first appearance of the element in
the array.
BINARY SEARCH

• We have a SORTED array and we want to find if a certain value is in the array.
• If it is return the index of the first appearance of the value in the array, else
return -1.
• Let’s check the algorithm for implementing the method.
BINARY SEARCH

• We have an array from 0 to n-1 of length n


• We declare 0 to be left and n-1 to be right
• We check middle = (n-1 + 0)/2 [the middle element] if it’s the number we’re
looking for we return the index.
• If the middle is bigger then we look at the array left = 0 and right = middle -1
and we look at that array. Otherwise left = middle+ 1 and left = left -1 .
• We look at left = 0 right = middle -1. and we check middle = (left + right )/2
and we check if middle == number. And etc etc.. Until left == right and on the
next step we get left>right and we stop and return -1;
Let’s assume we the number is smaller,
First we check the middle number of the
we’re now looking at the left subarray of
array. If it’s the number we’re looking for
the number.We now do the same process
we’re done else if the number is smaller
as before on the sub array and so on until
we look at the array left of the number
we end with a sub array of length one if it’s
otherwise if the number is bigger we look
the number we’re looking for then we’re
at the sub array on the right side of the
done else the number does not exist in
middle.
the array.
Binary search method is defined as Arrays.binarySearch(int[ ] , int).
We need to import java.util.Arrays to use it
IMPLEMENTING BINARY SEARCH
PART
SORTING ALGORITHMS

By, Abd El Fattah Khatib.


SORTING ALGORITHMS

• We want to write methods that sort arrays into sorted arrays in


ascending/descending order ( we will focus on ascending order).
• We have an unsorted array of random whole numbers. We want to sort the
array in ascending order.
• For example:
• [4,5,10,2,3,40,20,1] is unsorted
• [1,2,3,4,5,10,20,40] now the array is sorted.
10 20 1 5 4 99 90 3 5 2
10 20 1 5 4 99 90 3 5 2
10 20 1 5 4 2 90 3 5 99

10 20 1 5 4 2 5 3 90 99

10 3 1 5 4 2 5 20 90 99
5 3 1 5 4 2 10 20 90 99
2 3 1 5 4 5 10 20 90 99
2 3 1 4 5 5 10 20 90 99
2 3 1 4 5 5 10 20 90 99

2 1 3 4 5 5 10 20 90 99

1 2 3 4 5 5 10 20 90 99
MAX SORT / SELECTION SORT

we have an array of length n


• Iteration 1 : go over the array and find the element with the maximum value.
Save that index. And swap the element in with the maximum value with the
element with the last index(the last element in the array). Now we know the
maximum number is the last element in the array.
• Iteration 2: since the maximum number in the array is in its place – the last
element. We will only look at the n-1 first elements. For 0 to n-1 do the same
as in iteration 1. After we’re finished with that number with the highest value
of the n-1 left elements is in its place
MAX SORT / SELECTION SORT

• Iteration 3 : do the same as with iteration 2 with n-2 elements …


• ..
• Iteration n: array’s length is 1 now and there is only one element we can stop
now
• The result is that we have a sorted array
• This is called an algorithm. And it’s called Max Sort Algorithm because every
iteration we look for the maximum element and swap it with the last element.
10 20 1 5 4 99 90 3 5 2
10 20 1 5 4 99 90 3 5 2
10 20 1 5 4 2 90 3 5 99

10 20 1 5 4 2 5 3 90 99

10 3 1 5 4 2 5 20 90 99
5 3 1 5 4 2 10 20 90 99
2 3 1 5 4 5 10 20 90 99
2 3 1 4 5 5 10 20 90 99
2 3 1 4 5 5 10 20 90 99

2 1 3 4 5 5 10 20 90 99

1 2 3 4 5 5 10 20 90 99
BUBBLE SORT
• So we have seen Max sort that sorts an array by finding the maximum element
in the array.
• There is another algorithm to sort an array. This algorithm is called bubble
sort.
BUBBLE SORT ILLUSTRATION
BUBBLE SORT – 1 ST RUN

7 8 2 3 5 6 1 9 0 4

7 8 2 3 5 6 1 9 0 4
7 2 8 3 5 6 1 9 0 4
7 2 3 8 5 6 1 9 0 4
7 2 3 5 8 6 1 9 0 4
7 2 3 5 6 8 1 9 0 4
7 2 3 5 6 1 8 9 0 4
7 2 3 5 6 1 8 9 0 4
7 2 3 5 6 1 8 0 9 4
7 2 3 5 6 1 8 0 4 9

9 iterations
BUBBLE SORT – 2 ND RUN
7 2 3 5 6 1 8 0 4 9

2 7 3 5 6 1 8 0 4 9
2 3 7 5 6 1 8 0 4 9
2 3 5 7 6 1 8 0 4 9
2 3 5 6 7 1 8 0 4 9
2
2 3
3 5
5 7
6 6
1 1
7 8
8 0
0 4
4 9
9
2 3 5 6 1 7 8 0 4 9
2 3 5 6 1 7 0 8 4 9
2 3 5 6 1 7 0 4 8 9

8 iterations
BUBBLE SORT – 3 RD RUN

2 3 5 6 1 7 0 4 8 9
2 3 5 6 1 7 0 4 8 9
2 3 5 6 1 7 0 4 8 9
2 3 5 6 1 7 0 4 8 9
2 3 5 1 6 7 0 4 8 9
2 3 5 1 6 7 0 4 8 9
2 3 5 1 6 0 7 4 8 9
2 3 5 1 6 0 4 7 8 9

7 iterations
BUBBLE SORT ALGORITHM

• We have an array of length n , 0 to n-1.


• Iteration 1: swap element 0 with 1 if 0 is bigger , swap element 1 with 2 if 1 is bigger. Swap 2 with 3 if
2 is bigger.. Swap n-2 with n-1 if n-2 is bigger.
• Now we have the highest number at the end of the array. So will handle from 0 to n-2.
• Iteration 2: swap element 0 with 1 if 0 is bigger, swap element 1 with 2 if 1 is bigger… swap element
n-3 with n-2 if n-2 is bigger.
• …
• Iteration n-1 : swap 0 with 1 if 0 is bigger.
• Array is sorted.
MERGE SORT
MERGE

We want to merge two sorted arrays into a new sorted array


MERGE SORT
RECURSION
TASK

• Write a program that prints a triangle of numbers


The program expects a number as input and prints a triangle in reversed order
• Example: input is 3
output is:
1
12
123
TASK

• Write a program that prints a triangle of numbers like in the previous example
slide except that it prints the number in reverse order.
• The program excepts a number as input and prints a triangle in reversed order
• Example: input is 3
• output is:
123
12
1
• Write a program that gets 2 numbers from the user x and p. the program
calculates the power of x, p times.
• For example : input 2 3
• The output is 8 (2*2*2).
TASK

• Write a recursion method that takes a string and prints it in the reversed
order.
TASK

• Write a recursion method that takes a number x – called count_down.


• Prints
• 1
• 2
• 3
• 4
• 5
TASK

• Write a recursion method that takes a number x – called count_up.


• Prints
• 5
• 4
• 3
• 2
• 1
TASK

• Write a method called add_digits that takes a number


• For example(464646)
• And returns the sum of the digits.

You might also like