Saturday, July 29, 2017

Java - Random Helpful Tips

  • Ternary Operator
This  will to reduce line number of  code . 
condition ? ifConditionTrueWhatShouldHappen : ifConditionFalseWhatShouldHappen
 This can  be use instead of ,Normal if  and  else .


  •  Substring
    •     public String substring(int startIndex) : 
   This method returns new String object containing the substring of the given string from specified     startIndex (inclusive). 

    •     public String substring(int startIndex, int endIndex):  
  This method returns new String object containing the substring of the given string from specified     startIndex   to    endIndex (exclusive).
  Index starts  from 0  .Returns index where found, or -1 if not found 
ex :-  
String text = "Here there everywhere";
int a =text.indexOf("there");   // a is 5
int b =text.indexOf("er"); // b is 1 
int c =text.indexOf("eR"); // c is -1, "eR" is not found
  •  For Checking Null
    if(foo != null && foo.bar()) {
       someStuff();
    }
    will use short-circuit evaluation, meaning it ends if the first condition of a logical AND is false.            
  •  The && and || operators "short-circuit", meaning they don't evaluate the right hand side if it isn't        necessary. The & and | operators, when used as logical operators, always evaluate both sides.


  • Variable Arguments (Varargs) in Java
     
  • There can be only one variable argument in a method.
  • Variable argument (varargs) must be the last argument.
  • ex:-
    // Java program to demonstrate varargs
    class Test1
    {
        // A method that takes variable number of intger
        // arguments.
        static void fun(int ...a)
        {
            System.out.println("Number of arguments: " + a.length);
            // using for each loop to display contents of a
            for (int i: a)
                System.out.print(i + " ");
            System.out.println();
        }
        // Driver code
        public static void main(String args[])
        {
            // Calling the varargs method with different number
            // of parameters
            fun(100);         // one parameter
            fun(1, 2, 3, 4);  // four parameters
            fun();            // no parameter
        }
    }

No comments:

Post a Comment

The AI Driven Software Developer, Optimize Innovate Transform

  The AI-Driven Software Developer: Optimize, Innovate, Transform": AI Transformation in Software Development : Understand how AI is re...