Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 57

Chapter 1. What is Java?

1
What is Java ?
• Java is a popular programming language.
• Java is used to develop mobile apps, web apps, desktop apps,
games and much more.
• Java works on different platforms. (Windows, Mac, Linux,
Raspberry Pi, etc.)
• It is easy to learn and simple to use.
• It is open-source and free.
• It is secure, fast and powerful.
• Java is an object oriented language which gives a clear structure
to programs and allows code to be reused, lowering development
costs.
• As Java is close to C++ and C#, it makes it easy for
programmers to switch to Java or vice versa

2
Syntax
• Every line of code that runs in Java must be inside a class.
•  Java is case-sensitive: "MyClass" and "myclass" has different
meaning.
• The name of the java file must match the class name. 
• When saving the file, save it using the class name and add ".java"
to the end of the filename. 
Example: Output:
public class Main {
public static void main(String[] args)
{
System.out.println("Hello World");
}
}
3
Comments
• Comments can be used to explain Java code, and to make it more
readable.
• It can also be used to prevent execution when testing alternative code.
• There are two types of comment.
1) Single-line comment: start with two forward slashes (//). Any text
between // and the end of the line is ignored by Java (will not be
executed).
Example:
// This is a comment
System.out.println("Hello World");
2) Multi-line comment: start with /* and ends with */. Any text between
/* and */ will be ignored by Java.
Example:
/* The code below will print the words Hello World
to the screen, and it is amazing */
System.out.println("Hello World");
4
Variables
• Variables are containers for storing data values.
• In Java, there are different types of variables, some common use
of variables are
• String - stores text, such as "Hello". String values are surrounded
by double quotes.
• int - stores integers (whole numbers), without decimals, such as
123 or -123
• float - stores floating point numbers, with decimals, such as
19.99 or -19.99
• char - stores single characters, such as 'a' or 'B'. Char values are
surrounded by single quotes
• boolean - stores values with two states: true or false

5
Variables (Con’t)
• To create a variable, it must specify the type and assign a value.
Syntax:
type variableName = value;

Example:
String name = "John";
System.out.println(name);

• The println() method is often used to display variables.


• To combine both text and a variable, use the + character.
Example
String name = "John";
System.out.println("Hello " + name);
6
Variables (Con’t)
• To declare more than one variable of the same type, it can use a
comma-separated list.
Example:
int x = 5, y = 6, z = 50;
System.out.println(x + y + z);
• All Java variables must be identified with unique names.
• These unique names are called identifiers.
• Identifiers can be short names (like x and y) or more descriptive
names (age, sum, totalVolume).
Example:
// Good
int minutesPerHour = 60;
// OK, but not so easy to understand what m actually is
int m = 60;
7
Variables (Con’t)
The general rules for naming variables are:
• Names can contain letters, digits, underscores, and dollar signs
• Names must begin with a letter
• Names should start with a lowercase letter and it cannot contain
whitespace
• Names can also begin with $ and _
• Names are case sensitive ("myVar" and "myvar" are different
variables)
• Reserved words (like Java keywords, such as int or boolean)
cannot be used as names

8
Data types
• A data type is a classification of data which tells the compiler or
interpreter how the programmer intends to use the data.
Data types are divided into two groups:
(1)Primitive data types - There are eight primitive data types in Java.

9
Data types (Con’t)
• Primitive number types are divided into four groups:
• Integer types: store whole numbers, positive or negative (such as
123 or -456), without decimals. Valid types are byte, short, int and
long.
• Floating point types: represents numbers with a fractional part,
containing one or more decimals. There are two types: float and
double.
• Boolean type: which can only take the values true or false.
• Char type: is used to store a single character. The character must
be surrounded by single quotes, like 'A' or 'c‘.

(2) Non-primitive data types - are called reference types because


they refer to objects such as String, Arrays and Classes, Interfaces,
etc.
10
Type Casting
• Type casting is when you assign a value of one primitive data type to another
type.
In Java, there are two types of casting:
(1) Widening Casting (automatically) - converting a smaller type to a larger type
size
byte -> short -> char -> int -> long -> float -> double

Example:
public class Main {
public static void main(String[] args) {
int myInt = 9;
double myDouble = myInt; // Automatic casting: int to double

System.out.println(myInt); //Outputs 9
System.out.println(myDouble); //Outputs 9.0
}
}
11
Type Casting (Con’t)
(2) Narrowing Casting (manually) - converting a larger type to a
smaller size type
double -> float -> long -> int -> char -> short -> byte

Example:
public class Main {
public static void main(String[] args) {
double myDouble = 9.78d;
int myInt = (int) myDouble; // Manual casting: double to int

System.out.println(myDouble); // Outputs 9.78


System.out.println(myInt); // Outputs 9
}
}
12
Operators
• Operators are used to perform operations on variables and values.

Java divides the operators into the following groups:


1) Arithmetic operators
2) Assignment operators
3) Comparison operators
4) Logical operators
5) Bitwise operators

13
Operators (Con’t)
(1) Arithmetic Operators
• Arithmetic operators are used to perform common mathematical
operations.

14
Operators (Con’t)
(2) Assignment Operators
• Assignment operators are used to assign values to variables.

15
Operators (Con’t)
(3) Comparison operators
• Comparison operators are used to compare two values (or
variables).
• The return value of a comparison is either true or false.
• These values are known as Boolean values.

16
Operators (Con’t)
(4) Logical operators
• Logical operators are used to determine the logic between
variables or values.
• You can also test for true or false values with logical operators.

17
Operators (Con’t)
(5) Bitwise Operators
• Java defines several bitwise operators, which can be applied to the
integer types, long, int, short, char, and byte.
• Bitwise operator works on bits and performs the bit-by-bit
operation.

18
Strings
• Strings are used for storing text.
• A String variable contains a collection of characters surrounded by
double quotes
Example:
String greeting = "Hello";
• A String in Java is actually an object, which contain methods that
can perform certain operations on strings.
• For example, the length of a string can be found with the length()
method.
• The + operator can be used between strings to combine them. This
is called concatenation.
Example:
String firstName = "John";
String lastName = "Doe";
System.out.println(firstName + " " + lastName); 19
Strings
• Because strings must be written within quotes, Java will
misunderstand this string, and generate an error.
• The solution to avoid this problem, is to use the backslash escape
character.
• The backslash (\) escape character turns special characters into
string characters.

20
Conditions and If Statements
Java has the following conditional statements:
• Use if to specify a block of code to be executed, if a specified condition is true
• Use else to specify a block of code to be executed, if the same condition is
false
• Use else if to specify a new condition to test, if the first condition is false

Example:
int time = 22;
if (time < 10) {
System.out.println("Good morning.");
} else if (time < 18) {
System.out.println("Good day.");
} else {
System.out.println("Good evening.");
}
// Outputs "Good evening."
21
Switch Statements
• The switch expression is evaluated once.
• The value of the expression is compared with the values of each case.
• If there is a match, the associated block of code is executed.
• When Java reaches a break keyword, it breaks out of the switch block.
• This will stop the execution of more code and case testing inside the block.
• When a match is found, and the job is done, it's time for a break. There is no need for
more testing. The default keyword specifies some code to run if there is no case
match.
Syntax:
switch(expression) {
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
} 22
Switch Statements (Con’t)
Example:
int day = 4;
switch (day) {
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
case 3:
System.out.println("Wednesday");
break;
case 4:
System.out.println("Thursday");
break;
case 5:
System.out.println("Friday");
break;
case 6:
System.out.println("Saturday");
break;
case 7:
System.out.println("Sunday");
break;
}
// Outputs "Thursday" (day 4) 23
Do/While Loop
• Loops can execute a block of code as long as a specified condition is
reached.
• Loops are handy because they save time, reduce errors, and they make
code more readable.
• The while loop loops through a block of code as long as a specified
condition is true.
Syntax
while (condition) {
// code block to be executed
} int i = 0;

Example
while (i < 5) {
System.out.println(i);
i++;
} 24
Do/While Loop (Con’t)
• The do/while loop is a variant of the while loop. This loop will execute
the code block once, before checking if the condition is true, then it will
repeat the loop as long as the condition is true.
Syntax
do {
// code block to be executed
}
while (condition);

Example
int i = 0;
do {
System.out.println(i);
i++;
}
while (i < 5); 25
For loop
• When you know exactly how many times you want to loop through
a block of code, use the for loop instead of a while loop.
Syntax
for (statement 1; statement 2; statement 3) {
// code block to be executed
}
• Statement 1: is executed (one time) before the execution of the
code block.
• Statement 2: defines the condition for executing the code block.
• Statement 3: is executed (every time) after the code block has
been executed.

26
For loop (Con’t)
Example:
for (int i = 0; i < 5; i++) {
System.out.println(i);
}
• It is also possible to place a loop inside another loop. This is called a nested loop.
• The "inner loop" will be executed one time for each iteration of the "outer loop“.
Example:
// Outer loop
for (int i = 1; i <= 2; i++) {
System.out.println("Outer: " + i); // Executes 2 times

// Inner loop
for (int j = 1; j <= 3; j++) {
System.out.println(" Inner: " + j); // Executes 6 times (2 * 3)
}
}
27
For loop (Con’t)
• There is also a "for-each" loop, which is used exclusively to loop
through elements in an array.

Syntax
for (type variableName : arrayName) {
// code block to be executed
}

Example:
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
for (String i : cars) {
System.out.println(i);
}
28
For loop (Con’t)
• The break statement can also be used to jump out of a loop.
Example:
for (int i = 0; i < 10; i++) {
if (i == 4) {
break;
}
System.out.println(i);
}
• The continue statement breaks one iteration (in the loop), if a specified
condition occurs, and continues with the next iteration in the loop.
Example:
for (int i = 0; i < 10; i++) {
if (i == 4) {
continue;
}
System.out.println(i);
} 29
Arrays
• Arrays are used to store multiple values in a single variable,
instead of declaring separate variables for each value.
• To declare an array, define the variable type with square brackets.
• You can access an array element by referring to the index number.
• Array indexes start with 0: [0] is the first element. [1] is the
second element, etc
Example:
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
System.out.println(cars[0]);
// Outputs Volvo

30
Arrays
• To find out how many elements an array has, use the length
property.
Example:
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
System.out.println(cars.length);
// Outputs 4
• A multidimensional array is an array of arrays.
• Multidimensional arrays are useful when you want to store data
as a tabular form, like a table with rows and columns.
• To create a two-dimensional array, add each array within its
own set of curly braces.
Example:
int[][] myNumbers = { {1, 2, 3, 4}, {5, 6, 7} };

31
Chapter 2. Methods

32
Methods
• A method is a block of code which only runs when it is called.
• Methods are used to perform certain actions, and they are also
known as functions.
• A method must be declared within a class.
• To call a method in Java, write the method's name followed by
two parentheses () and a semicolon;
• A method can also be called multiple times:
• Java provides some pre-defined methods, such as
System.out.println(), but you can also create your own methods
to perform certain actions:

33
Methods (Con’t)
Syntax: Declare a method
<access_modifier> <return_type> <method_name>( list_of_parameters)
{
//body
}
In general, method declarations has six components :
1. Modifier: It defines the access type of the method i.e. from where it can
be accessed in your application. In Java, there 4 types of access specifiers.
public: It is accessible in all classes in your application.
• protected: It is accessible within the class in which it is defined and
in its subclass.
• private: It is accessible only within the class in which it is defined.
• default: It is declared/defined without using any modifier. It is
accessible within the same class and package within which its class
is defined.
34
Methods (Con’t)
2. The return type: The data type of the value returned by the
method or void if does not return a value.
3. Method Name: the rules for field names apply to method names
as well, but the convention is a little different.
4. Parameter list: Comma-separated list of the input parameters is
defined, preceded with their data type, within the enclosed
parenthesis. If there are no parameters, you must use empty
parentheses ().
5. Exception list: The exceptions you expect by the method can
throw, you can specify these exception(s).
6. Method body: it is enclosed between braces. The code you need
to be executed to perform your intended operations.

35
Methods (Con’t)
Syntax:

36
Methods (Con’t)
There are two types of methods in Java:
1. Predefined Method: In Java, predefined methods are the method
that is already defined in the Java class libraries is known as
predefined methods. It is also known as the standard library
method or built-in method. We can directly use these methods
just by calling them in the program at any point. 
2. User-defined Method: The method written by the user or
programmer is known as a user-defined method. These methods
are modified according to the requirement.

37
Methods (Con’t)
Example: Output:
public class Main {
//user defined method
static void myMethod() {
System.out.println("I just got executed!");
}
public static void main(String[] args) {
myMethod();
myMethod();
myMethod();
}
}
38
Method Parameters
• Information can be passed to methods as parameter.
• Parameters act as variables inside the method.
• Parameters are specified after the method name, inside the
parentheses.
• If parameters are more than one, it will need to separate them
with comma.
• When a parameter is passed to the method, it is called
an argument.

39
Method Parameters (Con’t)
Example: Output:
public class Main {
static int myMethod(int x, int y) {
return x + y;
}

public static void main(String[] args) {


int z = myMethod(5, 3);
System.out.println(z);
}
}

40
Method Parameters (Con’t)
A Method with If...Else
• It is common to use if...else statements inside methods:
Example: Output:
public class Main {
// Create a checkAge() method with an integer variable called age
static void checkAge(int age) {
// If age is less than 18, print "access denied"
if (age < 18) {
System.out.println("Access denied - You are not old enough!");
// If age is greater than, or equal to, 18, print "access granted"
} else {
System.out.println("Access granted - You are old enough!");
}
}
public static void main(String[] args) {
checkAge(20); // Call the checkAge method and pass along an age of 20
}
} 41
Method Overloading
• With method overloading, multiple methods can have the same name with
different parameters.
Example: Output:
static int plusMethod(int x, int y) {
return x + y;
}
static double plusMethod(double x, double y) {
return x + y;
}
public static void main(String[] args) {
int myNum1 = plusMethod(8, 5);
double myNum2 = plusMethod(4.3, 6.26);
System.out.println("int: " + myNum1);
System.out.println("double: " + myNum2);
}

42
Scope
• In Java, variables are only accessible inside the region they are created. This is
called scope.

(1) Method Scope


• Variables declared directly inside a method are available anywhere in the
method following the line of code in which they were declared
Example: Output:
public class Main {
public static void main(String[] args) {
// Code here CANNOT use x
int x = 100;
// Code here can use x
System.out.println(x);
}
}
43
Scope (Con’t)
(2) Block Scope
• A block of code refers to all of the code between curly braces {}.
• Variables declared inside blocks of code are only accessible by the code between the
curly braces, which follows the line in which the variable was declared.
Example: Output:
public class Main {
public static void main(String[] args) {
// Code here CANNOT use x
{ // This is a block
// Code here CANNOT use x
int x = 100;
// Code here CAN use x
System.out.println(x);
} // The block ends here
// Code here CANNOT use x
}
}
44
Recursion
• Recursion is the technique of making a function call itself.
Example: Output: 
public class Main {
public static void main(String[] args) {
int result = sum(10);
System.out.println(result);
}
public static int sum(int k) {
if (k > 0) {
return k + sum(k - 1);
} else {
return 0;
}
}
}
45
Chapter 3. Classes/Objects

46
Classes/Objects
Java is an object-oriented programming language.

What is OOP?
• Object-oriented programming(OOP) is about creating objects that
contain both data and methods.
• Classes and objects are the two main aspects of object-oriented
programming.
• A class is a template for objects, and an object is an instance of a
class.
• When the individual objects are created, they inherit all the
variables and methods from the class.
• Everything in Java is associated with classes and objects, along
with its attributes and methods.

47
Classes/Objects (Con’t)
Example:

Create a Class
To create a class, use the keyword class.
Example:
Create a class named "Main" with a variable x:
public class Main {
int x = 5;
}

48
Classes/Objects (Con’t)
Create an Object
• In Java, an object is created from a class. 
• To create an object of a class, specify the class name, followed
by the object name, and use the keyword new.
Example:
Create an object called "myObj" and print the value of x:
public class Main {
int x = 5;
public static void main(String[] args) {
Main myObj = new Main();
System.out.println(myObj.x);
}
}
49
Class Attributes
• In java, a variable within the class is referred as a
class attribute and the class attributes are also known
as fields.

Example
Create a class called "Main" with two attributes: x
and y:

public class Main {


int x = 5;
int y = 3;
}
50
Class Methods
• Class methods are methods that are called on the class itself, not
on a specific object instance.

Syntax
public class className {
modifier static dataType methodName (inputParameters)
{ //static method
//block of code to be executed
}
}

//calling the method, from anywhere


className.methodName(passedParams);

51
Class Methods
Example
public class Numbers {
public Numbers() {}
public static int findMinimum(int number1, int number2) {
//3 stored in number1, 5 stored in number2
int minimum = number2;
if (number1 < number2) minimum = number1;
return minimum;
}
}
//calling method outside of the class
int min = Numbers.findMinimum(3, 5);
//this would NOT work, static methods cannot be accessed with an
object
min = numberClass.findMinimum(3, 5);
52
Constructors
• A constructor in Java is a special method that is used to initialize
objects.
• The constructor is called when an object of a class is created.
• It can be used to set initial values for object attributes.
• the constructor name must match the class name, and it cannot
have a return type (like void).

// Create a Main class


public class Main {
int x; // Create a class attribute

// Create a class constructor for the Main class


public Main() {
x = 5; // Set the initial value for the class attribute x
} 53
Constructors (Con’t)
• Constructors can also take parameters, which is used to initialize
attributes.
Example:
public class Main {
int x;
public Main(int y) {
x = y;
}
public static void main(String[] args) {
Main myObj = new Main(5);
System.out.println(myObj.x);
}
}
//output 5
54
Chapter 4. File Handling

55
File Handling
• File handling is an important part of any application.
• Java has several methods for creating, reading, updating, and
deleting files.
• The File class from the java.io package, allows us to work with
files.
• To use the File class, create an object of the class, and specify
the filename or directory name.

Example:
import java.io.File; // Import the File class
File myObj = new File("filename.txt"); // Specify the
filename

56
File Handling (Con’t)
• The File class has many useful methods for creating and getting
information about files. For example:

57

You might also like