开发者

Explanation for ? and : operators

In my controller class I have the following line of check against my model. Someone please put some light on and explain me that if the model attribute is not null, is it creating a new model attribute

Object modelObj=pr.getPortletSession().getAttribute("tickets_from_Model");
TicketModel ticketmodel=modelObj!=null ? (TicketModel)modelObj:new TicketModel();

Please e开发者_开发问答xplain ? and : in the line


It is turnery operator

condition ? if condition is true execute this code : else this code

for example:

int i = 0;

String str =( i==0 ? "i is equal to zero" : "i is non zero");


To be a little clearer, the ? and : are components of the ternary operator. When using the ternary operator, you put your condition before the ?, the statement to execute if the condition is true after the ?, and the statement to execute if the condition is false after the ':'. So it acts like:


if condition ? then do this : else do this. 
isRunning ? doSomething() : doSomethingElse();

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜