-1

I have these two methods. I understand the "getTotalSalary" one but don't really get the way in which "getAverageSalary" is written. I don't understand why the question mark and colon is used as well as the "(size() != 0)" and 0 at the end.

This is the coding:

public double getTotalSalary() {
    double total = 0;
    for (Employee e : empReg) {
        total = total + e.getSalary();
    }
    return total;
}

public double getAverageSalary() {      
    return (size() != 0) ? this.getTotalSalary() / this.size() : 0;
}

empReg is the name of the ArrayList. Employee is a class which consists of "name" and "salary". getSalary is obviously a method returning the salary.

Lazio
  • 105
  • 1
  • 10
  • I believe what's confusing you is the `Ternary Operator` http://en.wikipedia.org/wiki/%3F:#Java – Dragondraikk Mar 02 '15 at 15:56
  • The getAverageSalary() implementation is all about avoiding division by zero. It's Java's ternary operator, described here http://docs.oracle.com/javase/tutorial/java/nutsandbolts/op2.html – unigeek Mar 02 '15 at 15:56

4 Answers4

6

The question mark is called the ternary operator, and it is used to make a decision based on an evaluation. It is often used to replace if statements, since they do the same thing. For example, an if statement with that would be written:

if (size != 0)
    return this.getTotalSalary() / this.size();
else
    return 0;

In my experience, I only use it if I want to reduce the code size. However, it does make the code a bit more difficult to read.

Lawrence Aiello
  • 4,560
  • 5
  • 21
  • 35
3

You cannot divide by zero. ? and : is a ternary operator. It means that if the expression before ? is true, then this.getTotalSalary() / this.size()will be returned, otherwise return 0.

Dia
  • 271
  • 1
  • 13
0

It's called ternary operator in java, here you have some examples: http://alvinalexander.com/java/edu/pj/pj010018

David Ruiz
  • 96
  • 3
0

See this discussion: What is a Question Mark "?" and Colon ":" Operator Used for?

It explains

A traditional if-else construct in C, Java and JavaScript is written:

if (a > b) {
    result = x;
} else {
    result = y;
}

This can be rewritten as the following statement:

result = a > b ? x : y;
Community
  • 1
  • 1
Pierpaolo Cira
  • 1,457
  • 17
  • 23