Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

scala
mutable
variable
communitycreator

How to print the value of variables using printf() function?

Theodore Kelechukwu Onyejiaku

Overview

The printf() function stands for print format. It is an Input/Output function that is used to print values of variables in Scala. As the name suggests, it is used to print values in different formats. For instance, %f stands for float, %d stands for integer, %s stands for string, and %c stands for character format.

Syntax

The syntax for using the printf function is shown below:

printf("%format", variable)
Syntax for printf() function

Parameter

%format: this is the format representing the data type of the variable we want to print.

variable: this is the variable whose value we want to print to the console.

Return Value

The value returned is the value of the variable .

Code Example

Let's view a code example.

object Main extends App {
    // create mutable variables in Scala
    var age:Int = 50
    var isMarried:Boolean = false
    var name:String = "John Doe"
    var gender:Char = 'M'
    var height:Float = 5.65F

    // print values of variables
    printf("age is = %d\n", age)
    printf("isMarried is = %b\n", isMarried)
    printf("name is = %s\n", name)
    printf("gender is = %c\n", gender)
    printf("height is = %f\n", height)
}
Try it out!

Explanation

  • Lines 3-7: create some variables in Scala and initialize them.
  • Lines 10-14: print the values to the console by specifying the formats.

RELATED TAGS

scala
mutable
variable
communitycreator

CONTRIBUTOR

Theodore Kelechukwu Onyejiaku
RELATED COURSES

View all Courses

Keep Exploring