What are various combinations of try-catch=finally?


1.Whenever we are writing try block, compulsory we should write catch or finally.

2.Whenever we are writing catch block compulsory we should write try block

    that catch is without try is invalid

3.Whenever we are writing finally block compulsory we should write try block.

    Finally without try is invalid.

4.In try-catch-finally, order is important.

5.'try' with multiple catch blocks is valid but the order is important,

    compulsory we should take from child to parent. If we are trying to take from

    parent to child then we will get compile time error.

6.If we are defining two catch blocks for the same exception we will get

    compile time error.

7.We can define try-catch-finally within the try, with in the catch, and with in

    finally blocks. Hence nesting of try-catch-finally is valid.








Difference between Access Specifiers and Access Modifiers.

 

Answer:
In old languages like C++, public, private, protected, default are considered as
Access Specifiers. Except these, the remaining (like static) are considered as
Access Modifiers.

But in Java there is not terminology like specifies. All are by default considered as Modifiers.
We have 12 Modifiers in Java.

public                   Synchronized
private                   abstract
protected              native
default                  Strictfp
final                     transient
static                   volatile

What is the Difference between JDK, JRE and JVM.

 Answer :
 JDK : JDK (Java Development Kit) is a software development
 environment used for developing java applications. It includes
 JRE(Java Runtime Environment), an interpreter/loader, a compiler(javac)
 and other tool needed for java development.

 JRE : We need an environment to run a java program. Java Runtime Environment
 provides the minimum requirement for executing a java application or program.
 It consists of JVM and library classes.

 JVM : Java Virtual Machine is a very important part of both JDK and JRE. JVM
 is responsible to execute a java program line by line. That why, JVM is also
 known as Interpreter

 Note:
JDK = JRE + Development Tools
                            JRE = JVM + library classes


Explain System.out.println().


 Answer :
 Let us take an example
 class Test{
    Static String s = "Java Invent"
 }

 To Find the length of the string "s",
 Test.s.length()

 Test is a class name.
 "s" is a static variable present in class Test
 of String type.
 length() is the method present in String class.
 
 same like above example
 class System{
     Static PrintStream out;
 }

 System.out.println("Java Invent");

 System is a class present in java.lang package.
 out is a static variable  present in the system class of type PrintStream.
 println() is a method present in PrintStream class.

Difference between Overloading and Overriding

 

->Overloading:
    Two methods are said t be overloaded if and only if both methods having
    same name but different argument types.

    class Test{
        public void m1(int i){

        }
        publicvoid m1(long l){

        }
    }

 ->Overriding:  
    What ever methods parent has, by default will be available to the child
    through inheritance.
    But some times child may not satisfy with parent method implementation.
    Then child is allowed to redefine that method based on its requirement.
    This proces is known as Overriding.


 Note:
    In overloading we have to chekc only method names(must be same) and
    argument types(must be different) except this the remaining like
    return types, access modifiers etc.; are not required to check.

    But in overiding every thing we have to check like method name,
    argument types return types, access modifiers etc.


Can we change the syntax of public static void main(String[] args)


Answer:
->The above syntax is very strict if we perform any change we will get
exception saying NoSuchMethodError:main.

-> Even though the above syntax is very strict the following changes
are acceptable.
->1. The order of modifiers is not important i.e. instead of "public static"
we can write "static public" also.

->2. We can declare "String[]" in any acceptable form.
    main(String[] args)
    main(String []args)
    main(String args[])

->3. Instead of 'args' we can take any valid java identifier.

->4. We can replace String[] with var arg parameter.
    main(String[]args) ---> main(String...args)

->5. We can declare main() method with the following modifiers also.
    final
    sychronized
    strictfp

    class Test{
        final static sychronized strictfp public void main(String... javainvent){
            System.out.println("main method");
        }
    }
    Output : main method

Explain public static void main(String[] args)

->public -> To call by JVM from anywhere. It is possible that
JDK can be installed on your system anywhere and java program
is saved on another drive. So to be called by JVM from anywhere
main() method must be public.

->static -> A static method can be called without existing object.
main() method in any way is not related to any object. If main()
method is not static, JVM will have to create an object of the
class and then JVM will be able to call main() method. It will
add an extra work to JVM.

->void -> main() method is called by JVM and main() method doesn't
return anything to JVM.

->main -> This is the name which is configured inside JVM.

->String[] args -> command line arguments.

Without writing main() method, is it possible to print some statements to the console?

Answer:
->Yes we can print by using static block.
->But this rule is applicable unti 1.6 version only.
From 1.7 version onwards main() method is mandatory to print some statements
to the console.

->Whether class contains main() method or not and whether main() method is
declared according to requirement or not, these things will not be checked by
Compiler. At runtime, JVM will be responsible to check these things.

->At runtime if JVM is unable to find required main() method then we will get
runtime exeception saying NoSuchMethodError.

class Test{

}

javac Test.java
java Test
RuntimeException: NoSuchMethodError.main

Case1:
Until 1.6 version if the class doesn't contain main() method then we will get
RuntimeException saying NoSuchMethodError. But from 1.7 version onwards,
Instead of NoSuchMethodError we wil get more meaningful error information.
i.e. Error: Main method not found in class, Please define main method as
public static void main(String[] args)

Case 2:
From 1.7 version onwards to run a java program main method is mandatory. Hence,
even though class contains static blocks they will not be executed, if main
method is not present.
Example:
Class Test{
    Static{
        System.out.println("Static block");
    }
}
Version 1.6 Output: Static block
            RE:NoSuchMethodError:main

Version 1.7 Error: main method not found in class.

Example: If the class contains main() method whether it is 1.6 or 1.7 version,
there is no change in execution sequence.
Class Test{
    static{
        System.out.println("static block");
    }
    public static void main(String[] args) {
        System.out.println("main method");
    }
}
version 1.6 : output: static block
                      main method
version 1.7 : output: static block
                      main method

Can we Overload main() method?

Question: Can we Overload main() method?
Answer:
Case 1:
Overloading of the main method is possible but JVM will always call String[]
argument main method only. The other overloaded method we have to call
explicitly then it will be executed just as a normal method call.

 Example:
Class Test{
    public static void main(String[] args)
    {
    System.out.println(“String[]”);
    }
//Overloaded Method
    public static void main(int[] args)
    {
    System.out.println(“int[]);
    }
}

Case 2:
Inheritance concept applicable for the main method.
Hence while executing child class if child class doesnt contain main method
then parent class main method will be executed.
Class Parent{
    Public static void main(String[] args)
    {
     System.out.println(“parent main”);
    }
}
Class Child extends Parent
{
}

Case 3:
It seems overriding concept is applicable for main method but
it is not overriding, it is method hiding.

Class Parent{
    Public static void main(String[] args)
    {
        System.out.println(“parent main”);
    }
}
Class Child extends P{
    System.out.println(“child main”);
}

Note: For main method inheritance and overloading concepts are applicable
but overriding concept is not applicable instead of overriding,
method hiding is applicable.

Iterating, filtering and passing a limit to fix the iteration using Stream

 

import java.util.stream.*;

class JavaStreamIterate {

  public static void main(String[] args) {
    Stream
      .iterate(1, element -> element + 1)
      .filter(element -> element % 2 == 0)
      .limit(10)
      .forEach(System.out::println);
  }
}

Iterating over an ArrayList using forEachLoop within a Stream

 

import java.util.ArrayList;
import java.util.function.Consumer;

public class ForEachLoop {

  public static void main(String[] args) {
    ArrayList<Integer> l = new ArrayList<Integer>();
    l.add(10);
    l.add(0);
    l.add(15);
    l.add(5);
    l.add(20);
    l.add(25);
    System.out.println(l);
    Consumer<Integer> c = i -> {
      System.out.println("The squre of " + i + " is:" + (i * i));
    };
    l.stream().forEach(c);
  }
}

Finding maximum and minimum value element in an ArrayList using Stream

 

import java.util.ArrayList;

public class MaxMin {

  public static void main(String[] args) {
    ArrayList<Integer> l = new ArrayList<>();
    l.add(10);
    l.add(0);
    l.add(15);
    l.add(5);
    l.add(20);
    l.add(25);
    System.out.println("The list is : " + l);
    Integer min = l.stream().min((i1, i2) -> i2.compareTo(i1)).get();
    System.out.println("Minimum value present in the list : " + min);

    Integer max = l.stream().max((i1, i2) -> i2.compareTo(i1)).get();
    System.out.println("Maximum value present in the list : " + max);
  }
}

Filtering Data using Stream

 

import java.util.ArrayList;
import java.util.List;
import java.util.stream.*;

public class FailedStudent {

  public static void main(String[] args) {
    ArrayList<Integer> l = new ArrayList<>();
    l.add(56);
    l.add(58);
    l.add(15);
    l.add(34);
    l.add(21);
    l.add(73);
    l.add(98);
    long failedSTudent = l.stream().filter(i -> i < 35).count();
    System.out.println("Total failed Students : " + failedSTudent);
    System.out.println("-------------------------------------------");
    List<Integer> sortedList = l.stream().sorted().collect(Collectors.toList());
    System.out.println(sortedList);
    System.out.println("-------------------------------------------");
  }
}

Sorting an ArrayList by Length of elements present in the List using Stream

 

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.*;

public class StreamCustSort2 {

  public static void main(String[] args) {
    ArrayList<String> actress = new ArrayList<>();
    actress.add("Sunny Leone");
    actress.add("Kajal Aggarwal");
    actress.add("Anushka Sharma");
    actress.add("Mallika Shetty");
    actress.add("Aamna Sarif");
    actress.add("Tara Sutaria");
    actress.add("Katrina Kaushal");
    ArrayList<String> alphabet = new ArrayList<>();
    alphabet.add("A");
    alphabet.add("AAAA");
    alphabet.add("AA");
    alphabet.add("AAA");
    alphabet.add("AAAAAA");
    alphabet.add("AAAAA");
    alphabet.add("AAAAAAA");

    Comparator<String> c = (s1, s2) -> {
      int l1 = s1.length();
      int l2 = s2.length();
      if (l1 < l2) return -1; else if (
        l1 > l2
      ) return 1; else return s1.compareTo(s2);
    };
    List<String> sortedList1 = actress
      .stream()
      .sorted(c)
      .collect(Collectors.toList());
    System.out.println("Increasing Length Order : " + sortedList1);
    System.out.println("-----------------------------------------------");
    List<String> sortedList2 = alphabet
      .stream()
      .sorted(c)
      .collect(Collectors.toList());
    System.out.println("Increasing Length Order : " + sortedList2);
  }
}

Customized sorting (Descending order) of an Arraylist of Integer type using stream

 

import java.util.ArrayList;
import java.util.List;
import java.util.stream.*;

public class StreamCustSort {

  public static void main(String[] args) {
    ArrayList<Integer> l = new ArrayList<>();
    l.add(56);
    l.add(58);
    l.add(15);
    l.add(34);
    l.add(21);
    l.add(73);
    l.add(98);

    List<Integer> sortedList = l
      .stream()
      .sorted((i1, i2) -> (i1 < i2) ? 1 : (i1 > i2) ? -1 : 0)
      .collect(Collectors.toList());
    System.out.println("Sorted List in descending order is : " + sortedList);
  }
}

Customized Sorting of an Arraylist of String using Stream

 

import java.util.ArrayList;
import java.util.List;
import java.util.stream.*;

public class StreamCustSort1 {

  public static void main(String[] args) {
    ArrayList<String> actress = new ArrayList<>();
    actress.add("Sunny");
    actress.add("Kajal");
    actress.add("Anushka");
    actress.add("Mallika");
    actress.add("Aamna");
    actress.add("Tara");
    actress.add("Katrina");

    List<String> sortedList1 = actress
      .stream()
      .sorted()
      .collect(Collectors.toList());
    System.out.println("Sorted List : " + sortedList1);
    System.out.println("-------------------------------------------------");
    List<String> sortedList2 = actress
      .stream()
      .sorted((s1, s2) -> s2.compareTo(s1))
      .collect(Collectors.toList());
    System.out.println("Sorted List : " + sortedList2);
  }
}

Sorting the element of an ArrayList using Stream

 

import java.util.ArrayList;
import java.util.List;
import java.util.stream.*;

public class StreamSorting {

  public static void main(String[] args) {
    ArrayList<Integer> l = new ArrayList<>();
    l.add(56);
    l.add(58);
    l.add(15);
    l.add(34);
    l.add(21);
    l.add(73);
    l.add(98);

    List<Integer> sortedList = l.stream().sorted().collect(Collectors.toList());
    System.out.println(sortedList);
  }
}

Google Script for Data Entry Form in Google Spreadsheet

// function to validate the entry made by user in user form function validateEntry (){ // declare a variable and referernece of active goog...