Search Header Logo
Java G11

Java G11

Assessment

Presentation

Computers

11th Grade

Practice Problem

Hard

Created by

Roshpinna Roshpinna

Used 3+ times

FREE Resource

82 Slides • 0 Questions

1

media

Learn Java

2

media

What is Java ?

Java is a popular programming language, created in 1995.

It is owned by Oracle, and more than 3 billion devices run Java.

It is used for:

Mobile applications (specially Android apps)

Desktop applications

Web applications

Web servers and application servers

Games

Database connection

2

3

media

Why use Java ?

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

It has a huge community support (tens of millions of developers)

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

3

4

media

Install Java

https://www.java.com/en/

4

5

media

Java IDE offline and online

IntelliJ

https://www.jetbrain
s.com/idea/

Choose Community
version (free)

Netbeans

https://netbeans.apa
che.org

Eclipse

https://www.eclipse.
org/downloads/

5

Replit (online)

https://replit.com

6

media
media

Java Syntax/ Print Line

Example explained

Every line of code that runs in Java must be inside a
class. In our example, we named the class Main.

A class should always start with an uppercase first
letter.

Note: 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.

System.out.println() can print to the console:

System is a class from the core library provided by Java

out is an object that controls the output

println() is a method associated with that object that receives a single argument

6

7

media
media

ANSI color code

7

8

media
media

Java Syntax/Print colored text

8

9

media
media

Java Syntax/Print colored text and colored background

9

10

media

The curly braces { }

The curly braces {} marks the beginning and the end of a block of code.

System is a built-in Java class that contains useful members, such as out, which is short for "output". The
println() method, short for "print line", is used to print a value to the screen (or a file).

Don't worry too much about System, out and println(). Just know that you need them together to print stuff to
the screen.

You should also note that each code statement must end with a semicolon (;).

10

11

media
media
media
media

Comment

Example explained

Comments are bits of text that are ignored by the
compiler. They are used to increase the readability
of a program.

Single line comments are created by using //.

Multi-line comments are created by starting with /*
and ending with */.

Any text between // and the end of the line is ignored by Java (will not be executed).

11

12

media

Java Variables

Example explained

Variables are containers for storing data values.

In Java, there are different types of variables, for example:

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

12

In Java, the type of a variable is checked at compile time. This is known as static typing. It has the advantage of
catching the errors at compile time rather than at execution time.

Variables must be declared with the appropriate data type or the program will not compile.

13

media
media
media

Declaring/Creating Variables

Example explained

To create a variable, you must specify the type and
assign it a value.

Where type is one of Java's types (such as int or
String), and variableName is the name of the
variable (such as x or name). The equal sign is used
to assign values to the variable.

To create a variable that should store text, look at
the following example

13

14

media
media
media
media

Display Variables

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

To combine both text and a variable, use the + character:

You can also use the + character to add a variable to another variable:

For numeric values, the + character works as a mathematical operator (notice that we use int (integer)
variables here):

14

15

media
media

The value of a variable cannot be changed if the variable was declared using the final keyword.

Note: the variable must be given a value when it is declared as final. final variables cannot be changed; any attempts at doing so will
result in an error message.

Final Variables

Example explained

If you don't want others (or yourself) to overwrite existing values, use the final keyword (this will declare
the variable as "final" or "constant", which means unchangeable and read-only):

15

16

media
media

Declare Variables of other types

16

17

media
media
media
media

Java Declare Multiple Variables

Declare Many Variables

To declare more than one variable of the same type, you can use a comma-separated list:

To this:

One Value to Multiple Variables

17

18

media
media

Java Identifiers

Identifiers

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).

Note:

It is recommended to use descriptive names in order to create understandable and maintainable code:

18

19

media

Naming Variables

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 _ (but we will not use it in this tutorial)

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

19

20

media

Java Data Types

a variable in Java must be a specified data type:

int myNum = 5; // Integer (whole number)

float myFloatNum = 5.99f; // Floating point number

char myLetter = 'D'; // Character

boolean myBool = true; // Boolean

String myText = "Hello"; // String

Data types are divided into two groups:

Primitive data types - includes byte, short, int, long, float, double, boolean and char.

Non-primitive data types - such as String, Arrays and Classes.

20

21

media
media

Primitive Data Types

A primitive data type specifies the size and type of variable values, and it has no additional methods.

There are eight primitive data types in Java:

21

22

media

Java Numbers

Primitive number types are divided into two groups:

Integer types stores whole numbers, positive or negative (such as 123 or -456), without decimals. Valid types are
byte, short, int and long. Which type you should use, depends on the numeric value.

Floating point types represents numbers with a fractional part, containing one or more decimals. There are two types:
float and double.

Scientific Numbers: A floating point number can also be a scientific number with an "e" to indicate the power of 10.

Integer Types:

Byte: The byte data type can store whole numbers from -128 to 127. This can be used instead of int or other
integer types to save memory when you are certain that the value will be within -128 and 127

Short: The short data type can store whole numbers from -32768 to 32767:

Long: The long data type can store whole numbers from -9223372036854775808 to 9223372036854775807.
This is used when int is not large enough to store the value. Note that you should end the value with an "L".

Floating Point Types: You should use a floating point type whenever you need a number with a decimal, such
as 9.99 or 3.14515.

Int: The int data type can store whole numbers from -2147483648 to 2147483647. In general, and in our tutorial,
the int data type is the preferred data type when we create variables with a numeric value.

22

23

media
media
media

Floating Point Types

You should use a floating point type whenever you need a number with a decimal, such as 9.99 or 3.14515.

The float and double data types can store fractional numbers.

Note that you should end the value with an "f" for floats and "d" for doubles:

Use float or double?

The precision of a floating point value indicates how many digits the value can have after the decimal point.

The precision of float is only six or seven decimal digits, while double variables have a precision of about 15 digits.
Therefore it is safer to use double for most calculations.

23

24

media

Java Boolean Data Types

A boolean data type is declared with the boolean keyword and can only take the values true or false:

boolean isJavaFun = true;

boolean isFishTasty = false;

System.out.println(isJavaFun); // Outputs true

System.out.println(isFishTasty); // Outputs false

Boolean values are mostly used for conditional testing.

24

25

media
media
media
media

Java Characters

Characters

The char data type is used to store a single character. The character must be surrounded by single quotes, like
'A' or 'c':

Strings

The String data type is used to store a sequence of characters (text). String values must be surrounded by
double quotes:

The String type is so much used and integrated in Java, that some call it "the special ninth type".

A String in Java is actually a non-primitive data type, because it refers to an object. The String object has
methods that are used to perform certain operations on strings. Don't worry if you don't understand the term
"object" just yet.

25

Alternatively, if you are familiar with ASCII values, you can
use those to display certain characters:

26

media

Non-Primitive Data Types

Non-primitive data types are called reference types because they refer to objects.

The main difference between primitive and non-primitive data types are:

Primitive types are predefined (already defined) in Java.

Non-primitive types are created by the programmer and is not defined by Java (except for String).

Non-primitive types can be used to call methods to perform certain operations, while primitive types
cannot.

A primitive type has always a value, while non-primitive types can be null.

A primitive type starts with a lowercase letter, while non-primitive types starts with an uppercase
letter.

The size of a primitive type depends on the data type, while non-primitive types have all the same
size.

Examples of non-primitive types are Strings, Arrays, Classes, Interface, etc.

26

27

media

Java 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:

Widening Casting (automatically) - converting a smaller type to a larger type size

byte -> short -> char -> int -> long -> float -> double

Narrowing Casting (manually) - converting a larger type to a smaller size type

double -> float -> long -> int -> char -> short -> byte

27

28

media
media

Widening Casting

Type casting is when you assign a value of one primitive data type to another type:

Widening casting is done automatically when passing a smaller size type to a larger size type:

28

29

media
media

Narrowing Casting

Narrowing casting must be done manually by placing the type in parentheses in front of the value:

Narrowing Casting (manually) - converting a larger type to a smaller size type

29

30

media
media
media

Java Operators

Operators are used to perform operations on variables and values.

Java divides the operators into the following groups:

Arithmetic operators

Assignment operators

Comparison operators

Logical operators

Bitwise operators

In the example below, we use the + operator to add together two values:

Although the + operator is often used to add together two values, like in the example above, it can also be used
to add together a variable and a value, or a variable and another variable:

30

31

media
media

Arithmetic Operators

Arithmetic operators are used to perform common mathematical operations.

31

32

media
media
media

Java Assignment Operators

Assignment operators are used to assign values to variables.

In the example below, we use the assignment operator (=) to assign the value 10 to a variable called x:

The addition assignment operator (+=) adds a value to a variable:

32

33

media
media

Java Assignment Operators

A list of all assignment operators:

33

34

media
media

Java Comparison Operators

Comparison operators are used to
compare two values:

34

35

media
media

Java Logical Operators

Logical operators are used to determine the logic between variables or values:

35

36

media
media
media
media
media

Java String

Strings are used for storing text.

A String variable contains a collection of characters surrounded by double quotes:

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:

36

37

media
media
media

Java String Concatenation

The + operator can be used between strings to combine them. This is called concatenation:

Note that we have added an empty text (" ") to create a space between firstName and lastName on
print.

You can also use the concat() method to concatenate two strings:

37

38

media
media
media
media

Adding Numbers and Strings

Java uses the + operator for both addition and concatenation.

Numbers are added. Strings are concatenated.

If you add a number and a string, the result will be a string concatenation:

38

39

media
media
media
media
media

Java Special Characters

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:

39

40

media

Java Conditions and If Statements

Java If ... Else

40

41

media

Java Conditions

Java supports the usual logical conditions from mathematics:

Less than: a < b

Less than or equal to: a <= b

Greater than: a > b

Greater than or equal to: a >= b

Equal to a == b

Not Equal to: a != b

You can use these conditions to perform different actions for different decisions.

41

42

media

Java Conditional 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

Use switch to specify many alternative blocks of code to be executed

42

43

media
media
media
media

Java If Statements

Use the if statement to specify a block of Java code to be executed if a condition is true.

Note that if is in lowercase letters. Uppercase letters (If or IF) will generate an error.

In the example below, we test two values to find out if 20 is greater than 18. If the condition is true, print some
text:

43

44

media
media
media

Java Else Statements

Use the else statement to specify a block of code to be executed if the condition is false.

44

45

media
media

Java Else if Statements

Use the else if statement to specify a new condition
if the first condition is false.

if (condition1) {

// block of code to be executed if condition1 is true

} else if (condition2) {

// block of code to be executed if the condition1 is
false and condition2 is true

} else {

// block of code to be executed if the condition1 is
false and condition2 is false

}

45

46

media

Java Switch Statements

Java Switch

46

47

media
media

Java Switch

Instead of writing many if..else statements, you can
use the switch statement.

The switch statement selects one of many code
blocks to be executed:

This is how it works:

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.

The break and default keywords are optional,
and will be described later in this chapter

47

48

media
media

Java Switch
- Examples

48

49

media

Java Switch - The break keyword

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.

A break can save a lot of execution time because it "ignores" the execution of all the rest of the
code in the switch block.

49

50

media
media

Java Switch - The break keyword

50

51

media
media

Java Switch - The default keyword

The default keyword specifies some code to run if there is no case match:

Note that if the default statement is used as the last statement in a switch block, it does not
need a break.

51

52

media

Java Loop

Do/While, For

52

53

media
media

Java Loops

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.

Java While Loop

The while loop loops through a block of code as long as a specified condition is true:

53

54

media
media

Java While Loop

In the example below, the code in the loop will run, over and over again, as long as a
variable (i) is less than 5:

Do not forget to increase the variable used in the condition, otherwise the loop will
never end!

54

55

media
media

Java - The Do/While Loop

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.

55

56

media
media

Java - The Do/While Loop

The example below uses a do/while loop. The loop will always be executed at least
once, even if the condition is false, because the code block is executed before the
condition is tested:

56

57

media
media

Java - 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:

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.

57

58

media
media

Java - For Loop

Example explained

Statement 1 sets a variable before the loop starts (int i = 0).

Statement 2 defines the condition for the loop to run (i must be less than 5). If the
condition is true, the loop will start over again, if it is false, the loop will end.

Statement 3 increases a value (i++) each time the code block in the loop has been
executed.

58

59

media
media

Java - Nested Loop

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":

59

60

media
media

Java - For-Each Loop

There is also a "for-each" loop, which is used exclusively to loop through elements in an array:

60

61

media
media

Java - For-Each Loop

The following example outputs all elements in the cars array, using a "for-each" loop:

61

62

media

Java Break / Continue

62

63

media
media

Java - Break

You have already seen the break statement used in an earlier chapter of this tutorial. It was
used to "jump out" of a switch statement.

The break statement can also be used to jump out of a loop.

This example stops the loop when i is equal to 4:

63

64

media
media

Java - Continue

The continue statement breaks one iteration (in the loop), if a specified condition occurs, and
continues with the next iteration in the loop.

This example skips the value of 4:

64

65

media
media
media

Java - Break and Continue in While Loop

You can also use break and continue in while loops:

65

66

media

Java Arrays

66

67

media
media

Java - 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:

67

68

media
media

Java - Access the Elements of an Array

You can access an array element by referring to the index number.

This statement accesses the value of the first element in cars:

Note: Array indexes start with 0: [0] is the first element. [1] is the second element, etc.

68

69

media
media

Java - Change an Array Element

To change the value of a specific element, refer to the index number:

69

70

media
media

Java - Array length

To find out how many elements an array has, use the length property:

70

71

media
media

Java - Loop Through an Array

You can loop through the array elements with the for loop, and use the length property to
specify how many times the loop should run.

The following example outputs all elements in the cars array:

71

72

media
media

Java - Loop Through an Array with For-Each

There is also a "for-each" loop, which is used exclusively to loop through elements in
arrays:

72

73

media
media

Java - Loop Through an Array with For-Each

The following example outputs all elements in the cars array, using a "for-each" loop:

The example below can be read like this: for each String element (called i - as in index) in
cars, print out the value of i.

If you compare the for loop and for-each loop, you will see that the for-each method is
easier to write, it does not require a counter (using the length property), and it is more
readable.

73

74

media
media

Java - Multidimensional Arrays

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:

myNumbers is now an array with two arrays as its elements.

74

75

media
media

Java - Access Elements

To access the elements of the myNumbers array, specify two indexes: one for the array,
and one for the element inside that array.

This example accesses the third element (2) in the second array (1) of myNumbers:

75

76

media
media

Java - Change Element Values

You can also change the value of an element:

76

77

media
media

Java - Loop Through a Multi-Dimensional Array

We can also use a for loop inside another for loop to get the elements of a
two-dimensional array (we still have to point to the two indexes):

77

78

media

Java User Input

Scanner

78

79

media
media

Java User Input

The Scanner class is used to get user input, and it is found in the java.util package.

To use the Scanner class, create an object of the class and use any of the available methods
found in the Scanner class documentation. In our example, we will use the nextLine() method,
which is used to read Strings:

79

80

media
media

Java User Input - Input Types

In the example above, we used the nextLine() method, which is used to read Strings. To read
other types, look at the table below:

80

81

media
media

Java User Input - Examples

81

82

media

Java - Practices

82

Write a Java program to print text in different text color and background color

Write a Java program to print the sum, multiply, subtract, divide and remainder of two
numbers

Write a Java program that takes two numbers and display the product of two numbers

media

Learn Java

Show answer

Auto Play

Slide 1 / 82

SLIDE