More New Stuff For Day 7 Of My Month of Java

in #java6 years ago

Ternary Operators And Comments On Day 7 of JavaTober

abstract-access-close-up-1089438.jpg
Image of the matrix courtesy of pexels.com

We talked about conditional statements in day 6 and we are taking one extra day to look at one special conditional which could make things pretty interesting in your code if you can get the hang of it. The ternary operator is something I have seen this before in Python and it looks pretty cool, but never really something I've been able to use before in my own coding and scripts. Just a quick note on comments first though.

What Did I Learn Today

  • Comments in Java: A Comment will be ignored by the compiler. Sometimes you need to put some information in your code that is not an instruction for the computer but more of an extra piece of information for other programmers or yourself that may be reading your code at a later date. There are two types of comments in Java, a single line comment and a multi line comment.
  1. A single line comment starts with two slashes // and everything after the double slash will be ignored by the compiler.
  2. A multi line comment will be indicated by the slash and star(/), and will then end with a star and slash(/). When the program is compiled, the compiler omits everything between the two sets of symbols /* and */.
  • And Now The Java Ternary Operator: It is the only conditional operator that takes three operands and is like a one line replacement for an "If Else Statement". The first operator should be a boolean or a statement with a boolean result. If the first operand is true the Java Ternary Operator reterns the second operand, if false, it returns the third operand. The Java Ternary Operator looks like this:
    result = ConditionalStatement ? Value1 : Value2;
    // If ConditionalStatement is true, Value1 is assigned to result, if false Value2 is assigned to result

Code For The Day


Time to see a Ternary Operator in action:

  1 public class TernaryTest {
  2 
  3    public static void main(String args[]) {
  4       int a, b;
  5       a = 10;
  6       b = (a == 1) ? 20: 30;
  7       System.out.println( "Value of b is : " +  b );
  8 
  9       b = (a == 10) ? 20: 30;
 10       System.out.println( "Value of b is : " + b );
 11    }
 12 }

Output:

java TernaryTest 
Value of b is : 30
Value of b is : 20

I'll be posting daily, sharing my experiences on my “1 Month of Java Code” experiences”, my previous post on day 6 can be found below, so feel free to have a look:
https://steemit.com/java/@run.vince.run/i-ve-made-it-to-day-6-of-my-month-of-java

If you have found this post useful or interesting, please consider Commenting, Upvoting, Following and/or Resteeming

Coin Marketplace

STEEM 0.30
TRX 0.12
JST 0.034
BTC 64231.88
ETH 3128.59
USDT 1.00
SBD 3.95