Tuesday, June 30, 2020

Features of JAVA 8 Introduction


1. What is an objective of Java 1.8 features?

  • To simplify the programming steps
  • To enable the functional programming benefits in java
  • To enable parallel programming (multi core processing)

2. What are the features available in java 1.8?

  • Lambda Expression
  • Functional Interfaces
  • Default methods
  • Predicates
  • Functions
  • Double colon Operator ::
  • Stream API
  • Date and Time API

Sunday, June 7, 2020

C programming_ Day 1

Importance of Programming Language
  • A programming language is an instruction set written machine understandable language that instructs computer to do the desired task. 
  • A programmer writes source code text in the programming language to create programs. It is used to make all the computer programs and computer software to control the assign task in certain procedure.
  • For example: Binary language, Assembly language, B, PASCAL, GOBAL, C, C++, C#, JAVA, Python, Go and etc.

Introduction to C language:
  • C is a general-purpose high level language that was originally developed by Dennis Ritchie for the Unix operating system.
  • It was first implemented on the Digital Equipment Corporation PDP-11 computer in 1972.
  • It is an upgrade version of languages B and BCPL.
Steps to Learn Programming Language



//80% usually Means "excellent"
#include <stdio.h>
int main()
{   int n=80;
    char ch='a';
    printf("%d%% usually\n Means \?excellent\?\v",n);
    printf("Learn\t with durga\v");//Learn       with durga
    printf("Never stop learning\n");                        //Never stop learning
    printf("Food\rGuard");//\r-> carriage return ==>Good
    return 0;

}

Structure of C programming Language


Declaration and Initialization:

int a,b,c=10;
int a=2,b;
if(pf)
for
//#include <stdio.h> //printf and scanf
#include"stdio.h"//userdefined modification
int main()

  //  int a=7;
   // int a='c';//a=99
    int a=printf("Learn with Durga\n");//Learn with Durga
    printf("%d",a);//a=?
    return 0;
}

2.
#include<stdio.h>//userdefined modification
int main()

   int a=20;
   printf("%d\n",a); //20
   printf("%4d....\n",a); //__20
   printf("%-4d....\n",a);//20__
   printf("%6.5d....\n",a);//_00020
   printf("%-6.5d....\n",a);//00020_
    return 0;
}
Storage classes available in C:
  • auto
  • extern
  • static
  • register
auto:
#include <stdio.h>
int main()
{   auto int i=5;
    {
        auto int i=4;
        printf("%d\t",i);
        {
        auto int i=3;
        printf("%d\t",i);
        }
        printf("%d\t",i);
    }
     printf("%d",i);
    return 0;

}

static:
#include <stdio.h>
int main()
{   static int a=4;
    printf("%d\t",a--);//4 3 2 1
    if(a>0)
    main();
    return 0;

}

extern:
#include <stdio.h>
int main()
{   extern int a;//a=9
    printf("%d\t",a);//9
    a=10;
    printf("%d\t",a--);//10
    printf("%d\t",a);//9
    return 0;
}

a=9;
Classification of Datatype:
  • Primitive datatype - int,float, double and char
  • User defined datatype - typedef and enum
  • Derived datatype: primitive derived - array and user-defined derived - structure and union

step 3: Instruction set

  • Decision making statement - if else and switch
  • Looping statement - while, do while and for


7.1. Multithreading in JAVA

1. What is Multi threading?
The process of executing two or more threads concurrently, where each thread responsible for different task at the same time is called as multi threading.

2. Difference between sleep() and wait()

3. How to call a thread? 
  • Threads may not execute sequentially, meaning thread 1 may not be the first to write its name to System.out. This is because the threads are principle executing in parallel and not sequentially. The JVM and/or operating system determines the order in which the threads are executed. This order does not have to be same order in which they were started.
  • Main threads automatically start by JVM and the other user defined threads calls by using start() method.

4. Can Java thread object invoke start method twice?
No. After starting a thread, it can never be started again. If you do so, an IllegalThreadStateException is thrown. In such a case, thread will run once but for a second time, it will throw an exception.

5. What is Daemon thread?
Daemon thread is a low priority thread,works with JVM when all the user threads finishes their execution, JVM doesn't care whether Daemon thread is running or not because it terminates the thread and after that shutdown itself.
Example:
public class ThreadDemo {
public static void main(String[] args) throws InterruptedException {
Thread.currentThread().setDaemon(true);
System.out.println(Thread.currentThread().isDaemon());
       }
}
Output:
True


6. Can we change the name of the main thread ?

Yes, we can change the name of the main thread. It can be done by first getting the reference of the main thread by using currentThread() method and then calling setName() method on it.
For example:
public class ThreadDemo {
public static void main(String[] args) throws InterruptedException {
Thread t=Thread.currentThread();
t.setName("Durga");
                System.out.println(t.getName() +"Thread");
        }
}
Output:
Durga Thread.

Wednesday, June 3, 2020

6.1 Exception Handling

1.What are the differences between an error and an exception?


2. Draw the hierarchy of exception.

3. Difference between Checked and Unchecked Exception.

Checked Exception
Unchecked Exception
Exception which is checked by the compiler whether programmer handling or not, for normal execution of the program at runtime, is called checked exception. 
Exception which is not checked by the compiler whether programmer handling or not, is called unchecked exception.
Eg: 
InvalidAgeException
HallTicketMissingException
FileNotFoundException
Eg:
ArithmeticException
BombBlastException
NullPointerException

4.What is the order of catch blocks when catching more than one exception?
case 1: Exception catch block defined before NumberFormatException catch block will throw an unreachable catch block error. Because it is already handled by Exception catch block.
public class MultipleCatchBlock {
public static void main(String[] args) {
try {
int a=Integer.parseInt("One");
}
catch(Exception e) {
System.out.println(e.getMessage());
}
catch(NumberFormatException e) {
System.out.println(e.getMessage());
}
}
}
Output:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
Unreachable catch block for NumberFormatException. It is already handled by the catch block for Exception at Batch4.MultipleCatchBlock.main(MultipleCatchBlock.java:11)

case 2: NumberFormatException catch block defined before Exception catch block handles the specified exception and terminate the program normally without showing any error.
public class MultipleCatchBlock {
public static void main(String[] args) {
try {
int a=Integer.parseInt("One");
}
catch(NumberFormatException e) {
System.out.println(e.getMessage());
}
catch(Exception e) {
System.out.println(e.getMessage());
}
}
}
Output:
java.lang.NumberFormatException: For input string: "One"

5. How many different ways to print the Exception message?
There are three different way to print exception information in different format as follow:
  • printStackTrace() → prints Exception package and class: Name of the exception and its path.
  • toString() → prints Exception package class: Name of the exception
  • getmessage() → prints only Exception name
For Example:
public class ExceptionDemo {
public static void main(String[] args) {
try {
System.out.println(25/0);
}
catch(Exception e) {
e.printStackTrace();
System.out.println(e.getMessage());
System.out.println(e.toString());
}
System.out.println("Learn with Durga");
}
}
Output:
java.lang.ArithmeticException: / by zero
at Batch4.ExceptionDemo.main(ExceptionDemo.java:6)
/ by zero
java.lang.ArithmeticException: / by zero
Learn with Durga

Note: default exception handler internally uses printStackTrace() method to print exception information to the console.

6. Describe behavior of following exception?
RuntimeException - unchecked
Error -unchecked
IOException - fully checked
Exception - partially checked
InterruptedException - fully checked
CloneNotSupportedException - checked
Throwable - partially checked
ArithmeticException - unchecked
ConcurrentModificationException - unchecked
NullPointerException - unchecked
FileNotFoundException  - fully checked

7. Difference between throw and throws.



8. Which are the valid declaration of try catch and finally block as in the following options?




9. What is finally block?
finally block is used at the end of exception handling try-catch block and it terminated the exception thrown by the try block even it is handled/not handled or checked/unchecked. finally block will not executed if there is no try block mentioned in the program. 

5.1. Java Collection

1. Difference between Collection and Collections
Key
Collection
Collections
Basic 
interface in Java collection framework 
utility class in Collection framework 
Static Methods 
doesn't has all static methods 
has all static method 
Operation 
used to store list of object in a single object  
used to operate on collection.

Difference between ArrayList, LinkedList and Vector.

Difference between HashSet,LinkedHashSet and Treeset.

What is legacy class?

What is concurrentModificationException?

What is the difference between Hashtable and HashMap?

What is concurrentHashMap?


Is Map comes under collection framework?
No. Map interface has key and value pair stored under the common name. Cursor available under collection hierarchy such as Iterator, ListIterator, Enumeration and foreach doesn't iterates the map interface variable.

4.3 OOPS basics - Inheritance and Polymorphism

1. What is Polymorphism?
Polymorphism is the ability of an object to take on many forms. In a same class or classes inheriting other class having same method name with different behavior (Overriding) and same method with different in number,type and order arguments(Over loading) is know as Polymorphism.

2. What is runtime polymorphism or dynamic method dispatch?


3. Difference between overloading and method overriding?


4. How to prevent override method in Java?
There are three different ways to prevent overriding of method in Java. The following three approach does that
  • Private method cannot be overridden, because it is not visible to the other class.
  • Static method can also not be overridden, because it relates with class rather than objects. So it hides the method to the child class.
  • Final method cannot be overridden, because it doesn't allows redefinition of the method.

5. What is Inheritance and its types?
Inheritance is the process of using extends keyword,  the attributes and behaviors of one class used in  the other class.

6. What is multiple inheritance and does java support?
In multiple inheritance, child class inherits the properties of two parents classes. Multiple parent classes may contains the same method signature causes the confusion in the child class which method to inherit during runtime, called as diamond problem. There is no virtual keyword in java to avoid this problem. Due to this problem, java doesn't allow inheritance with classes but it allows using interface.

7. What is the difference between super() and this()?
super() is constructor of an immediate parent class. this() is a current class constructor.
Example:
class A{
A(){
System.out.println("Class A no argument constructor called");
}
}
class B extends A{
B(){
System.out.println("Class B no argument constructor called");
}
B(String s){
this();
System.out.println("Class B argument constructor called");
}
}
public class Constructor{
public static void main(String[] args) {
new B("Learn");
}

}

Output & Explanation:
Class A no argument constructor called
Class B no argument constructor called

Class B argument constructor called



8. What is the super class of all java classes?

Object class is a super class of all java classes which is available in java.lang.object. All user defined class extends from object class and it follows simple inheritance, because it collects the behaviors of objects to the implemented class.

9. How can you create an immutable class in java?
  • Define class as final public (extends are not allowed)
  • Define the properties inside class also private and final
  • Assign the values with the help of constructor
  • Declare only getter method() (setter method not allowed)
Example:
final public class Immutable{
private final int a;
public Immutable(int a){
this.a=a;
}
public int getA(){
return this.a;
}
}
10.

Wednesday, May 20, 2020

JAVA Lambda Expressions

Introduction:

  • Java's first step into functional programming
  • It is an anonymous function and doesn't belong to any class
  • It implements the interface methods in a concise expression clearly.
  • It provides the implementation of functional interface and simplifies the software development
  • First programming language uses Lambda expression is LISP, later on C, C++, C#, .Net, RUBY and etc.

Syntax:

parameter -> expression body

→ Arrow operator is introduced in Java through lambda expression that divides it into two parts(Parameter & Body).

Characteristics:
Optional Type Declarations
Optional parenthesis around parameters and curly braces
Optional return keyword


Interview Questions:

1. Objective of Lambda expression in JAVA:

  • To enable the functional programming benefits
  • To write the code in more readable, maintainable and concise code
  • To use API's very easily and effectively
  • To enable parallel processing
2. Difference between Anonymous Inner class and Lambda Expression.

Anonymous Inner class

Lambda Expression

class without name
function without name
can extends abstract, concrete classes and interface
can extends only the functional interface (Single Abstract Method)
can declare instance variable
can’t declare instance variable
can be instantiated
can’t be instantiated
Inside anonymous inner class, this always refers current anonymous inner class object but not outer class object
Inside lambda expression, this always refers Outer class object
highly recommended for multiple method handling
highly recommended for one abstract method in an interface i.e, functional interface
separate .class file generated for every anonymous class
no separate .class file generated during compilation
object memory allocated in heap area  
reside in permanent memory of JVM (method area)


Friday, April 24, 2020

Python - IO functions

1. How the print function differs in Python 3 and 2 version?
Most notable and most widely known change in Python 3 is how the print function is used. Use of parenthesis () with print function is now mandatory. It was optional in Python 2.
  • print "Hello World" #is acceptable in Python 2
  • print ("Hello World") # in Python 3, print must be followed by () 
2. How the reading input functions differ in Python 3 and 2 version?
  • Python 2 has two versions of input functions, input() and raw_input(). The input() function treats the received data as string if it is included in quotes '' or "", otherwise the data is treated as number.
  • In Python 3, raw_input() function is deprecated. Further, the received data is always treated as string.
3. Major difference between Python 2 and Python 3:
Basis of comparison
Python 3
Python 2
Release Date
2008
2000
Function print
print ("hello")
print "hello"
Division of Integers
Whenever two integers are divided, you get a float value
When two integers are divided, you always provide integer value.
Unicode
In Python 3, default storing of strings is Unicode.
To store Unicode string value, you require to define them with "u".
Syntax
The syntax is simpler and easily understandable.
The syntax of Python 2 was comparatively difficult to understand.
Rules of ordering Comparisons
In this version, Rules of ordering comparisons have been simplified.
Rules of ordering comparison are very complex.
Iteration
The new Range() function introduced to perform iterations.
In Python 2, the xrange() is used for iterations.
Exceptions
It should be enclosed in parenthesis.
It should be enclosed in notations.
Leak of variables
The value of variables never changes.
The value of the global variable will change while using it inside for-loop.
Backward compatibility
Not difficult to port python 2 to python 3 but it is never reliable.
Python version 3 is not backwardly compatible with Python 2.
Library
Many recent developers are creating libraries which you can only use with Python 3.
Many older libraries created for Python 2 is not forward-compatible.


4. 

Introduction to Python programming

1. What is Python?
Python is a popular programming language. It was created in 1991 by Guido van Rossum.
It is used for:
  • web development (server-side),
  • software development,
  • mathematics,
  • system scripting.

2.What can Python do?
  • used on a server to create web applications. 
  • used alongside software to create workflows. 
  • connect to database systems. It can also read and modify files. 
  • used to handle big data and perform complex mathematics. 
  • used for rapid prototyping, or for production-ready software development.

3.Why Python?
  • Python works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc).
  • Python has a simple syntax similar to the English language.
  • Python has syntax that allows developers to write programs with fewer lines than some other programming languages.
  • Python runs on an interpreter system, meaning that code can be executed as soon as it is written. This means that prototyping can be very quick.
  • Python can be treated in a procedural way, an object-orientated way or a functional way.

4. Good to know about Python:
  • The most recent major version of Python is Python 3, which we shall be using in this tutorial. However, Python 2, although not being updated with anything other than security updates, is still quite popular.
  • In this tutorial Python will be written in a text editor. It is possible to write Python in an Integrated Development Environment, such as Thonny, Pycharm, Netbeans or Eclipse which are particularly useful when managing larger collections of Python files.

5. How Python Syntax differs from other programming languages?
  • Python was designed to for readability, and has some similarities to the English language with influence from mathematics.
  • Python uses new lines to complete a command, as opposed to other programming languages which often use semicolons or parentheses.
  • Python relies on indentation, using whitespace, to define scope; such as the scope of loops, functions and classes. Other programming languages often use curly-brackets for this purpose.

Saturday, April 18, 2020

JAVA Programming - 4.1 OOPS basics - Introduction and Encapsulation

1. What is Encapsulation?
Encapsulation is the process of wrapping data member, member functions and member classes inside a single module called class, that defines the restriction of an object and its member variables and methods.

2. Can a class be defined inside an another class?
Yes. Class can be defined inside another class, that is called inner class. This increases the degree of encapsulation. Static class defined inside another class called Nested inner class which can be accessed without outer class instance; but Non-static defined inside another class (called inner class) can only be accessed with outer class instance.

3. What is constructor and define its function?
Constructor is a method defined inside a class which has same name as class name and it has no return time; It is used to initialize instance variable of class. If the constructor defined as private we can't create object instance of a class.

4. What will be the output of the following JAVA program?
class LWD{
public static void learn(){
System.out.println("Learning");
}
public LWD(){
System.out.println("Wondering");
}
public static void main(String l[]){
learn();
new LWD();
System.out.println("Developing");
}

}
Output & Explanation:
Learning
Wondering
Developing
Here, LWD class have two static(learn() & main()) and a constructor LWD(); Program execution start with main method which calls learn() prints "Learning" and LWD() calls prints "Wondering"; main() method prints "Developing".
Note:
learn(); // Non static method call doesn't requires object instance of the class LWD.
listen(); // Static method call requires object instance of the class LWD.


5. What will be the output of the following JAVA program?
class LWD{
class Online{
public static void main(String l[]){
System.out.println("Welcome to JAVA class");
}
}
}
Output & Explanation:
compilation error due to illegal declaration of static method inside non static inner class. Static method and variable only declared inside static block, so the inner class should be the static class.
class LWD{
static class Online{
public static void main(String l[]){ System.out.println("Welcome to JAVA class");}
}}
where output is "Welcome to JAVA class".

6. How many class files created when the following java code complied?
class AP{}
class TN{}
class College{
class Student{}
}
Answer & Explanation:
4 class files, namely
class AP{} → AP.class from AP class
class TN{} → TN.class from TN class
class College{ → College.class  from Outer class College
class Student{}→ College$Student.class from Inner class Student
}

7. What is Singleton class?
A class can have only one object instance is called Singleton class. It provides a global point of access to the object.
Singleton class used in logging, caches, thread pools, configuration settings, device driver objects.


Rules to implement singleton class:
  • Constructor should be private
  • Declare a static variable object of the class
  • Declare a static method to return the instance


8. How garbage collector knows that the object is not in use and needs to be removed?
Java garbage collection is the process by which Java programs perform automatic memory management. Java programs compile to bytecode that can be run on a Java Virtual Machine. When Java programs run on the JVM, objects are created on the heap, which is a portion of memory dedicated to the program. Eventually, some objects will no longer be needed. The garbage collector finds these unused objects and deletes them to free up memory.

9. What is wrapper class in java?
Wrapper classes helps to convert primitives into object(Autoboxing) and object into primitives(Unboxing).

Example:
boolean→Boolean
byte→Byte
char→Character
int→Integer
float→Float
long→Long
short→Short

10. What is System.out in Java?


11. Is null a keyword in java?
 Yes. It is a reserved word(keyword) for a literal values, it is similar to true and false and used to represent the empty value or points to nothing.

12. What is java static import?

In 1.5 versions, according to sun static import improves readability of the code but according to worldwide programming exports static imports creates confusion and reduces readability of the code. Hence if there is no specific requirement never recommended to use a static import.

Without static method:
public class Main {
public static void main(String[] args) {
System.out.println(Math.sqrt(4));
}
}
With static method:
import static java.lang.Math.*;
public class Main {
public static void main(String[] args) {
System.out.println(sqrt(4));
}
}

Wednesday, April 15, 2020

Java Programming - 4.2 Looping statement

1. What will the output of following JAVA program?
public class LWD{
public static void main(String [] args){
int a=0;
for(System.out.print("Learn with ");a<1;System.out.println("Durga")){
a++;
}
System.out.println("Never stop learning");
       }
}
Output & Explanation:
Learn with Durga

2. What will the output of following JAVA program?
public class LWD{
public static void main(String [] args){
for(int x=0;x<20;x++);
System.out.println(x);
       }
}
Output & Explanation: compile time error
In the above JAVA code, for loop end with semi colon for(int x=0;x<20;x++); denotes empty for loop for(int x=0;x<20;x++){ }; Scope of variable x,  only inside for loop, next line x doesn't declare in LWD class.   
class LWD{
public static void main(String [] args){
int x;
for(x=0;x<20;x++);
System.out.println(x);
       }

}

3. What will be the output of following JAVA program?
class LWD{
    public static void main(String l[]){
        int a[]={10,20,30,40,50};
        for(int i=0; i<a.length;i++)
            System.out.print(a[i]+" ");
    }
}
A. Error – length is not a method of a.
B. 6
C. 10,20,30,40,50
D. 10 20 30 40 50
Output & Explanation:
10 20 30 40 50

4. What is the correct syntax of for each loop?
  1. for(variable:collection){body;}
  2. for(data_type variable:collection){body;}
  3. for(variable;collection){body;}
  4. for(data_type variable;collection){body;}
Answer: 
2
for(data_type variable:collection)
{body;}

5. Determine output:
public class LWD{
public static void main(String args[]){
int i, j;
for(i=1, j=0;i<10;i++) j += i;
System.out.println(i);
}
}
A. 10
B. 11
C. 9
D. 20
E. None of these
Answer: A

6. How many times will the following code print “Learn with Durga"? int count = 0;
do {
System.out.println("Learn with Durga");
count++;
} while (count < 10);

A. 8
B. 9
C. 10
D. 11
E. 0
Answer: C

7. Choose the correct statement in context of the following program code. public class LWD{
public static void main(String[] args){
double sum = 0;
for(double d = 0; d < 10;){
d += 0.1;
sum += sum + d;
}
}
}
A. The program has a compile error because the adjustment is missing in the for loop.
B. The program has a compile error because the control variable in the for loop cannot be of the double type.
C. The program runs in an infinite loop because d<10 would always be true.
D. The program compiles and runs fine.
Answer: D

8. What is the value of a[1] after the following code is executed? int[] a = {0, 2, 4, 1, 3};
for(int i = 0; i < a.length; i++)
a[i] = a[(a[i] + 3) % a.length];

A. 0
B. 1
C. 2
D. 3
E. 4 
Answer: B

9. Which of the following for loops will be an infinite loop? A. for(; ;)
B. for(i=0 ; i<1; i--)
C. for(i=0; ; i++)
D. All of the above
Answer: D


10. public class While { 
public void loop() { 
int x= 0; 
while ( 1 ) /* Line 6 */ 
{ System.out.print("x plus one is " + (x + 1)); /* Line 8 */ } 
Which statement is true?

A. There is a syntax error on line 1.
B. There are syntax errors on lines 1 and 6.
C. There are syntax errors on lines 1, 6, and 8.
D. There is a syntax error on line 6.
Answer: D