“Java Essentials: From Casting to Arrays”

Welcome back everyone. In today’s last article of Java programming, we will be looking at Type Casting in Java. We will also cover Strings, Math, Boolean, Switch, Break, Continue, and Arrays. So, let’s get started!

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

Widening Casting

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

Narrowing Casting

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

Real Life Example

Here’s a real-life example of type casting where we create a program to calculate the percentage of a user’s score in relation to the maximum score in a game.

We use type casting to make sure that the result is a floating-point value, rather than an integer:

Java Strings

Strings are used for storing text.

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

Create a variable of type String and assign it a value:

String Length

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:

More String Methods

There are many string methods available, for example toUpperCase() and toLowerCase():

Finding a Character in a String

The indexOf() method returns the index (the position) of the first occurrence of a specified text in a string (including whitespace):

Java counts positions from zero.
0 is the first position in a string, 1 is the second, 2 is the third …

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.

Adding Numbers and Strings

If you add two numbers, the result will be a number, if you add two strings, the result will be a string concatenation and if you add a number and a string, the result will be a string concatenation:

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:

Escape CharacterResultDescription
\’Single Quote
\”Double Quote
\\\Backslash

The sequence \"  inserts a double quote in a string:

Other common escape sequences that are valid in Java are:

CodeResult
\nNew Line
\rCarriage Return
\tTab
\bBackspace
\fForm Feed

Java Math

The Java Math class has many methods that allows you to perform mathematical tasks on numbers.

Math.max(x,y)

The Math.max(x,y) method can be used to find the highest value of x and y:

Math.min(x,y)

The Math.min(x,y) method can be used to find the lowest value of x and y:

Math.sqrt(x)

The Math.sqrt(x) method returns the square root of x:

Math.abs(x)

The Math.abs(x) method returns the absolute (positive) value of x:

Random Numbers

Math.random() returns a random number between 0.0 (inclusive), and 1.0 (exclusive):

To get more control over the random number, for example, if you only want a random number between 0 and 100, you can use the following formula:

Java Boolean

Very often, in programming, you will need a data type that can only have one of two values, like:

  • YES / NO
  • ON / OFF
  • TRUE / FALSE

For this, Java has a boolean data type, which can store true or false values.

Boolean Values

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

However, it is more common to return boolean values from boolean expressions, for conditional testing (see below).

Boolean Expression

A Boolean expression returns a boolean value: true or false.

This is useful to build logic, and find answers.

For example, you can use a comparison operator, such as the greater than (>) operator, to find out if an expression (or a variable) is true or false:

Or even easier:

In the examples below, we use the equal to (==) operator to evaluate an expression:

Java Switch

Java Switch Statements

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

The example below uses the weekday number to calculate the weekday name:

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.

The default Keyword

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

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

Java Break

You have already seen the break statement above in this article. 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:

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:

Break and Continue in While Loop

You can also use break and continue in while loops:

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:

We have now declared a variable that holds an array of strings. To insert values to it, you can place the values in a comma-separated list, inside curly braces:

To create an array of integers, you could write:

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:

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

Change an Array Element

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

Array Length

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

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:

Loop Through an Array with For-Each

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

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

The example above 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.

Real Life Example

To demonstrate a practical example of using arrays, let’s create a program that calculates the average of different ages:

And in this example, we create a program that finds the lowest age among different ages:

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.

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:

Change Element Values

You can also change the value of an element:

Loop Through a Multi-Dimensional Array

You 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):

Or you could just use a for-each loop, which is considered easier to read and write:

Check Your Learning….

Blogroll


Social, Cultural u0026amp; Behavioral Issues in PHC u0026amp; Global Health
Social, Cultural u0026amp; Behavioral Issues in PHC u0026amp; Global Health
Social, Cultural and Behavioral Foundations of Primary Health Care (JHSPH)

Penny Zeller
Penny Zeller
Random thoughts from a day in the life of a wife, mom, and author

Discover more from Sophia's Tech Journey

Subscribe to get the latest posts sent to your email.

Leave a Reply

Discover more from Sophia's Tech Journey

Subscribe now to keep reading and get access to the full archive.

Continue reading