Saturday, 12 January 2019

Java Beginners Excercises


Que 1: Answer the below questions based on the following Java program:

public class MyFirstProgram {
    public static void main(String[] args){
        System.out.println("hello world");
    }
}

A; What would be the Java file name for the above Java program and why?
Ans: The file name will be MyFirstProgram.java. The file name should be the same as the name of the public class defined.

B: What is the command used to compile and run the above Java program. Write the full command.
Ans: Compile: javac MyFirstProgram.java, Run: java MyFirstProgram

Que 2: How many data types are available in Java?
Ans:
Integer: int, short, long, byte
Floating point: float, double
Char type: char
Boolean type: boolean

Que 3: How can we define variables in Java? Please provide an example.
Ans:
public class DefineSomeVariables
{
    double salary;
   int vacationDays = 12;
   long earthPopulation
   boolean done;
}

Que 4: How can we define constants in Java? Please provide an example.
Ans: We use the keyword final to denote a constant.
public class Constants
{
     public static void main(String[] args)
    {
         final double CM_PER_INCH = 2.54;
         final INCH = 12;
     }
}


Que 5: Which In-built class does Java provide for mathematical operations. Please provide some basic examples using that class.
Ans: Java provide Math class.
Below are some examples:
1: To take the square root of a number, use the sqrt method:
double x = 4;
double y = Math.sqrt(x);
System.out.println(y); // prints 2.0

2: The Math class supplies the usual trigonometric functions:
Math.sin
Math.cos
Math.tan
Math.atan
Math.atan2

Que 6: What is the data type conversion in Java? Please explain using an example.
Ans: When we assign the value of one data type to another, the two types might not be compatible with each other. If the data types are compatible, then Java will perform the conversion automatically known as Automatic Type Conversion and if not then they need to be cast or converted explicitly.

For example:
The syntax for casting is to give the target type in parentheses, followed by the variable name.
double x = 9.997;
int nx = (int) x;
Now, the variable nx has the value 9 because casting a floating-point value to an integer discards the fractional part.

Que 7: Explain operator combining in Java using an example.
Ans:
x += 4;
is equivalent to
x = x + 4;
(In general, place the operator to the left of the = sign, such as *= or %= .)

If the operator yields a value whose type is different than that of the left-
hand side, then it is coerced to fit. For example, if x is an int , then the statement
x += 3.5;
is valid, setting x to (int)(x + 3.5) .


Que 8: Is Java supports Increment and Decrement Operators? If yes then explain using an example.
Ans: Yes java supports both Increment and Decrement Operators.

Example:
int n = 12;
n++;
changes n to 13. Since these operators change the value of a variable, they cannot
be applied to numbers themselves. For example, 4++ is not a legal statement.

int a = 2 * ++m; // now a is 16, m is 8
int b = 2 * n++; // now b is 14, n is 8

The same way we can do --n and n--.

Que 9: What are the relational operators in Java? Provide some examples.
Ans: Java has six relational operators that compare two numbers and return a boolean value. The relational operators are <, >, <=, >=, ==, and !=.

Examples:
x < y
Less than
True if x is less than y, otherwise false.
x > y
Greater than
True if x is greater than y, otherwise false.
x <= y
Less than or equal to
True if x is less than or equal to y, otherwise false.
x >= y
Greater than or equal to
True if x is greater than or equal to y, otherwise false.
x == y
Equal
True if x equals y, otherwise false.
x != y
Not Equal
True if x is not equal to y, otherwise false.


Que 10: What are Enumerated types in Java? Explain using an example.
Ans: Sometimes, a variable should only hold a restricted set of values.

For example:
you may sell clothes or pizza in four sizes: small, medium, large, and extra large.
Of course, you could encode these sizes as integers 1, 2, 3, 4 or characters S, M, L,
and X . But that is an error-prone setup. It is too easy for a variable to hold a wrong
value (such as 0 or m ).

We can define our own enumerated type whenever such a situation arises. An
enumerated type has a finite number of named values. For example:
enum Size { SMALL, MEDIUM, LARGE, EXTRA_LARGE };
Now we can declare variables of this type:

Size s = Size.MEDIUM;

A variable of type Size can hold only one of the values listed in the type declaration,
or the special value null indicates that the variable is not set to any value at all.

Que 11: Is there any data type for Strings in Java? Please explain the basic concept of String in Java?
Ans: No, Java does not support any data type for Strings. The standard Java library contains a predefined class called String.

Example:
Each quoted string is an instance of the String class:
String e = ""; // an empty string
String greeting = "Hello";

Que 12: Write a program to print the first three letters from a given string.
Hint: Use the substring method of the String class.
Ans:
public class SubstringExample{
    public static void main(String args[]){
        String greeting = "Hello";
        String s = greeting.substring(0, 3);
        System.out.println(“First three letters of given String: ” + s);
    }
}


Que 13: What methods String class provides to test equality between two strings? Please provide an example.
Ans: String class provides the following two methods to test the equality which returns true or false.
  1. equals(): Case-sensitive check
  2. equalsIgnoreCase(): Case insensitive

Examples:
1. String greeting = "Hello";
"Hello".equals(greeting); // returns true
2. String greeting = "hello";
"Hello".equals(greeting); // returns false
"Hello".equalsIgnoreCase(greeting) // returns true

Que 14: What is the significance of NULL and Empty String? Please explain using appropriate examples.
Ans:
Empty: The empty string "" is a string of length 0. We can test whether a string is empty
by calling
if (str.length() == 0)
or
if (str.equals(""))

An empty string is a Java object which holds the string length (namely 0 ) and an
empty contents.

NULL: a String variable can also hold a special value, called null, that indicates that no object is currently associated with the variable.

To test whether a string is null, use the condition
if (str == null)

Sometimes, we need to test that a string is neither null nor empty. Then use the Condition
if (str != null && str.length() != 0)

We need to test that str is not null first. It is an error to invoke a method on a null value.

Que 15: Write down some mostly used String class method names.
Ans:
char charAt(int index)
boolean startsWith(String prefix)
boolean endsWith(String suffix)
int indexOf(String str)
int lastIndexOf(String str)
String replace(CharSequence oldString, CharSequence newString)
String substring(int beginIndex)
String substring(int beginIndex, int endIndex)
String toLowerCase()
String toUpperCase()
String trim()
boolean equals(Object other)
boolean equalsIgnoreCase(String other)




Que 16: What is the use of the Scanner class? Explain using an example.
Ans: Scanner class is used to read input from the command line.
Example:
public class CommandLineInput
{
      public static void main(String args[])
     {
          Scanner in = new Scanner(System.in);
          System.out.print("What is your name? ");
          String name = in.nextLine();
          System.out.print("Your name is: "+name);

          //Get second input
          System.out.print("How old are you? ");
          int age = in.nextInt();
          System.out.print("Your age is: "+age);

      }
}

Que 17: Explain the IF conditional statement using an example.
Ans:
The conditional statement in Java has the form
if (condition) statement
The condition must be surrounded by parentheses.

Example:
if (yourSales >= target)
{
performance = "Satisfactory";
bonus = 100;
}

Que 18: Explain FOR and WHILE loop.
Ans:
While Loop: The while loop executes a statement (which may be a block statement) while a
condition is true. The general form is
while (condition) statement
The while loop will never execute if the condition is false.
Example:
while (balance < goal)
{
    balance += payment;
    double interest = balance * interestRate / 100;
    balance += interest;
    years++;
}

For loop: The for loop is a general construct to support iteration controlled by a counter or
the similar variable that is updated after every iteration.

Example: the following loop prints the numbers from 1 to 10 on the screen.
for (int i = 1; i <= 10; i++)
System.out.println(i);


Que 19: What is the Array? How do we declare and initialize arrays in Java? Explain using an example.
An array is a data structure that stores a collection of values of the same type.
We access each individual value through an integer index.
For example, if a is an array of integers, then a[i] is the i th integer in the array.

Array Declaration:
int[] a; // array a of integers

Array Initialization:
int[] a = new int[100]; // This statement declares and initializes an array of 100 integers.

Que 20: Create a method to insert and print elements from an array.
Ans:
public void arrayExample()
{
// Initialize the array
int[] a = new int[10];

// Get the array length by using length property
int length = a.length;

// Insert values in the array
for (int i = 0; i < a.length; i++)
a[i] = i+10;

//Print the array
for (int i = 0; i < a.length; i++)
System.out.println(a[i]);
}
Que 21: What is the class in Java? Generally what things we can have inside a class?
Ans: A class is a template or blueprint from which objects are made. Think about
classes as cookie cutters. Objects are the cookies themselves. When you construct
an object from a class, you are said to have created an instance of the class.

Generally, a class have fields/variables and methods. All code that we write in Java is inside a class.


Que 22: In OOPs what are the main characteristics of objects?
Ans:
  • The object’s behaviour—what can you do with this object, or what methods can
you apply to it?
  • The object’s state—how does the object react when you invoke those methods?
  • The object’s identity—how is the object distinguished from others that may
have the same behaviour and state?


Que 23: What are the differences between the Procedural program and OOP?
Ans:
In a traditional procedural program, we start the process at the top, with the main
function. When designing an object-oriented system, there is no “top,” and new-
comers to OOP often wonder where to begin. The answer is: Identify your classes
and then add methods to each class.

in an order-processing system, some of the nouns are
Item
Order
Shipping address
Payment
Account
These nouns may lead to the classes Item, Order, and so on.

Que 24: What are the Constructors in Java?
Ans:
In the Java programming language, we use constructors to construct new instances.
A constructor is a special method whose purpose is to construct and initialize
Objects.
Constructors always have the same name as the class name. Thus, the constructor
for the Date class is called Date. To construct a Date object, combine the constructor
with the new operator, as follows:
new Date()
This expression constructs a new object. The object is initialized to the current date and time.


Que 25: Write 5 properties/characteristics of Constructors.
Ans:
  • A constructor has the same name as the class.
  • A class can have more than one constructor.
  • A constructor can take zero, one, or more parameters.
  • A constructor has no return value.
  • A constructor is always called with the new operator.


Que 26: What happens when we defile class fields as static?
Ans:
If we define a field as static, then there is only one such field per class. In contrast,
each object has its own copy of all instance fields. For example, let’s suppose we
want to assign a unique identification number to each employee. We add an
instance field id and a static field nextId to the Employee class:

class Employee
{
private static int nextId = 1;
private int id;
. . .
}

Every employee object now has its own id field, but there is only one nextId field
that is shared among all instances of the class. Let’s put it another way. If there
are 1,000 objects of the Employee class, then there are 1,000 instance fields id, one for
each object. But there is a single static field nextId . Even if there are no employee
objects, the static field nextId is present. It belongs to the class, not to any individual
object.


Que 27: What are the Static Methods in Java?
Ans:
Static methods are methods that do not operate on objects. For example, the pow method of the Math class is a static method.
The expression Math.pow(x, a) computes the power x a. It does not use any Math object to carry out its task.
In other words, it has no implicit parameter.
We can think of static methods as methods that don’t have this parameter.

Here is an example of such a static method:


public static int getNextId()
{
return nextId; // returns static field
}

To call this method, we supply the name of the class:
int n = Employee.getNextId();

Que 28: What is Overloading?
Ans: some classes have more than one constructor.
For example, you can construct an empty StringBuilder object as
StringBuilder messages = new StringBuilder();

Alternatively, you can specify an initial string:
StringBuilder todoList = new StringBuilder("To do:\n");

This capability is called overloading. Overloading occurs if several methods have the same name (in this case, the StringBuilder constructor method) but different parameters.

The compiler must sort out which method to call. It picks the correct method by matching the parameter types in the headers of the various methods with the types of values used in the specific method call.

A compile-time error occurs if the compiler cannot match the parameters, either because there is no match at all or because there is not one that is better than all others.

Que 29: How can we call one constructor from another?
Ans:
The keyword this refers to the implicit parameter of a method. However, this keyword has a second meaning.
If the first statement of a constructor has the form this(. . .) , then the constructor calls another constructor of the same class.
Here is a typical example:

public Employee(double s)
{
// calls Employee(String, double)
this("Employee #" + nextId, s);
nextId++;
}

When you call a new Employee(60000), the Employee(double) constructor calls the Employee(String, double) constructor.
Using this keyword in this manner is useful—you only need to write common
construction code once.

Que 30: What are the Initialization Blocks? Explain using an example.
Ans:
Class declarations can contain arbitrary blocks of code. These blocks are executed whenever an object of that class is constructed. For example:
class Employee
{
private static int nextId;
private int id;
private String name;
private double salary;

// object initialization block
{
id = nextId;
nextId++;
}

public Employee(String n, double s)
{
name = n;
salary = s;
}

public Employee()
{
name = "";
salary = 0;
}
. . .
}

In this example, the id field is initialized in the object initialization block, no matter which constructor is used to construct an object. The initialization block runs first, and then the body of the constructor is executed.


Friday, 7 October 2016

How does ConcurrentHashMap achieves its Scalability?

Question) How does ConcurrentHashMap achieve its Scalability?
Sometimes this multithreading + collection interview question is also asked as, the difference between ConcurrentHashMap and Hashtable in Java.

The problem with synchronized HashMap or Hashtable was that the whole Map is locked when a thread performs any operation with Map.


The java.util.ConcurrentHashMap class solves this problem by using the lock stripping technique, where the whole map is locked at different segments and only a particular segment is locked during the write operation, not the whole map.

The ConcurrentHashMap also achieves its scalability by allowing lock-free reads as read is a thread-safe operation.

Sunday, 24 January 2016

Java one year experience interview questions

1. Explain System.out.println()?
  • The system is a class That is present in java.lang package.
  • Out is a static final field (variable) of  Printstream class
    Println(): method of Printstream Class
  • Class System{
    public static final Printstream Out;
    }
  • Class Printstream{
    public void println(){}}

 2. What happens When System.out.println(null)?
  • Compilation Error -This is because you can pass an Object or a String or char[]. Since null can fit in both, the compiler doesn't know which method to use, leading to compile error.
  • Method Overloading:
        1.public void prinltln(String str) { }
        2.public void prinltln(char[] ch){ }
        3.public void prinltln(Object ch){ 
  • It seems the call System.out.print(null) is ambiguous to the compiler because print(null) here will find the two best specific matches i.e. print(String) and print(char[]). So the compiler is unable to determine which method to call here.
  • Compilation Error:
       System.out.println(null)
  • Compile Fine:
         System.out.println((String)null);//null
         System.out.println((char[])null);
         System.out.println((Object)null);//null
  • It's the compiler type-checking the parameters of the method call.
  • But here we need to know one more thing  System.out.println((char[])null); will compile fine but at run time will throw runtime exception.
 
3. What are the oops concepts in Java

Oops:
Oops, concepts are the rules which are supposed to be satisfied by a programing language in order to call that programing language as an Object Oriented Programing Language.


1. The 3 oops concepts are
    I. Encapsulation
    ii. Polymorphism
    iii. Inheritance

Encapsulation:

The process of binding the data with corresponding methods
  • The concept of binding the data along with its related and corresponding methods is known as Encapsulation.
  • The concept of restricting the availability of the data only to its related areas and related functions it is known as binding.
  • Because of binding, we can restrict the availability of data to the unrelated methods
  • So that unrelated functions cannot access the data 
  • Class is the base for encapsulation 

Polymorphism:

Defining multiple methods with the same name is known as Polymorphism.
  1. Static polymorphism (Compile time polymorphism ):
    The concept of defining multiple methods with the same name and with different parameters within the same class is known as static polymorphism.
  2. Dynamic polymorphism (Run time polymorphism ):
    The concept of defining multiple methods with the same name and with the same signature in super class and subclass is known as Dynamic polymorphism.

Inheritance:

Getting the properties from one class object to another class object is known as Inheritance.
  1. Multiple inheritance:
    Getting the properties from one class object to another class object level-wise with different priorities.
  2. Multilevel inheritance: Getting the properties from one class object to another class object with the same priority.

4. What are classes and Objects in Java?

Class
  • Class is a structure.
  • Binding the data with its related and corresponding functions.
  • Class is the base for encapsulation.
  • Class is a user-defined data type in Java.
  • The class will act as the base for encapsulation and implement the concept of encapsulation through objects.
  • Any Java application looks like a collection of classes but whereas a c- application looks like a collection of functions.
public class Example{

         //variable declaration
          int id;

      // methods
        public int getId() {
          return id;
         }

    public void setId(int id) {
        this.id = id;
    }

}

Object

  • An object is nothing but an instance (dynamic memory allocation) of a class.
  • The dynamic memory allocated at run time for the members [non-static variables] of the class is known as an object.

What is a Reference variable?

  • A reference variable is a variable that would be representing the address of the object.
  • Reference will act as a pointer and handler to the object.
  • Since the reference variable always points to an object.
  • In practice, we call the reference variable also an object.
  • We can create an object by using a new operator.
  • If we want to call any method inside the class we need an object
               Syntax: A obj= new A();

Example program:

      public class A {
         int a;
         public  void Print(){
            System.out.println("value of a="+a);
        }
        public static void main(String[] args) {
            A obj=new A();
           obj.print();
        }
}

Output: the value of a=0 
 
What Object Contains?
  • The object of any class contains only data.
  • Apart from the data object of a class would not contains anything else.
  • An object of a class would not contain any functionalities or logic.
  • Thus object of a class would be representing only data and not represent logic.

What is the state of the Object?

The data present inside the object of a class at that point in time is known as the state of the object.

What is the behavior of the object? 

  • The functionalities associated with the object => Behavior of the object.
     The state of the object changes from time to time depending on the functionalities that are executed on that object but whereas the behaviour of the object would not change.

Naming conventions for declaring a class:

  • The class name should be relevant.
  • Use UpperCamelCase for class names. //StudentDemoClass
  • For Methods names follow camelCase(); //getName();
  • Declare variables in the lowercase first letter. // int rollNumber
  • To declare final static variables means they will act like constants
    MIN_WIDTH=10;
    MAX_AGE=18;


5. Can you define an abstract class without any abstract methods?

  • Yes.
  • Declaring a class abstract without abstract methods means that you don't allow it to be instantiated on its own.
  • The abstract class used in Java signifies that you can't create an object of the class directly.
  • This will work:
    public abstract class abs {

    protected int s=0;

    public void display() {
        System.out.print("hello");
    }

    }

6. what are the differences between Final, finally Finalize ()?

Final:

  •  Any variable declare along with the final modifier then those variables treated as final variables
  • if we declare final variables along with static will become constants.
  • public final String name = "foo"; //never change this value
  • If you declare a method as final that method is also known as final methods. Final methods are not overridden. means we can't override that method in any way.
  • public final void add(){
     }
     public class A{
     void add(){
     //Can't override
     }

     }
  • If you declare class is final that class is also known as final classes.Final classes are not extended.means we can't extens that calss in anyway.
  • public final class indhu{
     }
     public class classNotAllowed extends indhu {...} //not allowed

Finally:

  • Finally, blocks are followed by a try or catch. finally, blocks are compulsory executable blocks. But finally is useful for more than just exception handling.
  •  it allows the programmer to avoid having cleanup code accidentally bypassed by a return,
     continue, or break, Closing streams, network connection, database connection. Putting cleanup code in a finally block is always a good practice even when no exceptions are anticipated
  •  where finally doesn't execute e.g. returning a value from the finally block, calling System. exit from try block etc
  • finally, the block always executes, except in case of JVM dies i.e. calling System. exit().

     lock.lock();
    try {
      //do stuff
    } catch (SomeException se) {
      //handle se
    } finally {
      lock.unlock(); //always executed, even if Exception or Error or se
      //here close the database connection and any return statements like that we have to write
    }

Finalize():

  • finalize() is a method that is present in Java.lang.Object class.
  •  Before an object is garbage collected, the garbage collector calls this finalize() of the object. Any unreferenced before destroying if that object has any connections with the database or anything. It will remove the connections and it will call finalize() of object. It will destroy the object.
  • If you want to explicitly call this garbage collector you can use System.gc() or Runtime.gc() objects are there for a long time the garbage collector will destroy that objects.
  • public void finalize() {
      //free resources (e.g. un allocate memory)
      super.finalize();
    }

7. What is Exception? difference between Exception and Error? and types of Exceptions?
  • Exceptions are the objects representing the logical errors that occur at run time and make JVM enters into the state of  "ambiguity".
  • The objects which are automatically created by the JVM for representing these run-time errors are known as Exceptions.
  • An Error is a subclass of Throwable that indicates serious problems that a reasonable application should not try to catch. Most such errors are abnormal conditions.
  • few of the subclasses of 
  • Error
  • AnnotationFormatError - Thrown when the annotation parser attempts to read an annotation from a class file and determines that the annotation is malformed.
  • AssertionError- Thrown to indicate that an assertion has failed.    
  • LinkageError - Subclasses of LinkageError indicate that a class has some dependency on another class; however, the latter class has incompatibly changed after the compilation of the former class.
  • VirtualMachineError - Thrown to indicate that the Java Virtual Machine is broken or has run out of resources necessary for it to continue operating.
  •  There are really three important subcategories of Throwable:
  • Error - Something severe enough has gone wrong the most applications should crash rather than try to handle the problem,
  • Unchecked Exception (aka RuntimeException) - Very often a programming error such as a NullPointerException or an illegal argument. Applications can sometimes handle or recover from this Throwable category -- or at least catch it at the Thread's run() method, log the complaint and continue running.
  • Checked Exception (aka Everything else) - Applications are expected to be able to catch and meaningfully do something with the rest, such as FileNotFoundException and TimeoutException
   
 8. Differences between method overloading and method overriding
  • Method overloading is nothing but defining multiple functionalities with the same name with
    different parameters are known as method overloading
  • while compile time itself we know which method is executed
  • Overloading gives better performance compared to overriding. The reason is that the
    binding of overridden methods is being done at runtime.
  • The argument list should be different while doing method overloading.
  • Polymorphism does not apply to overloading. The return type of overloaded methods should be the same.
    static binding is used for overloaded methods
public class A{
   public void show(int a){
      S.o.p("indhu");
   }
   public void show(int a,int b){
     S.o.p("sindhu");
   }

   public void show(float a){
     S.o.p("lavanya");
   }
   public static void main(String args[]){

       A a=new A();
       a.show(10);
      a.show(1,2);
     a.show(1.2);
   }
}
  • Method overriding is nothing but defining multiple functionalities with the same name with
    the same definition in superclass and subclass is known as Method overriding.
    While Run time only now which method is Executed.
  • Overriding gives slower performance compared to overloading. The reason is that the
    binding of overridden methods is being done at run time.
  • The argument list should be the same while doing method overriding.
    Polymorphism applies to overriding. 
  • In method overriding the return type of the overriding method can be different from overridden
    method.
  • Dynamic binding is used for method-overriding methods
public class A{
    public void display(){
      S.o.p("Indhu");
    }
}

Public class B extends A{
   public void display(){
     S.o.p("Sindhu");
   }
   public sttaic void main(String args[]){
      A a =new B();
      a.display();
   }
}


9. How to write custom Exceptions?
  • "MyException" is our exception class name. You can give any name of your choice.
    An important thing to be noted is our class extends the "Exception" class. This is all we need to do to make a custom-defined exception
    "Now we define a constructor of my class. This constructor takes a "String" argument. We call the super class' constructor(super class here is "Exception class") and pass this string to it. Not Java creates a new Exception with the message as in the string passed.

    •   public class MyException extends Exception

      {

          public MyException(String message)        

          { 

              super(message);       

          }     

      }
public class ExceptionDemo 
    {     
        public static void main(String args[]) throws Exception   
        {         
            ExceptionDemo exceptionDemo = new ExceptionDemo();        
            exceptionDemo.displayNumbers();   
        }     
        public void displayNumbers() throws MyException   
        {         
            for(int i=0;i<10;i++)      
            {     
               try{       
                System.out.print(i);          
                if(i==6)          
                {                 
                  throw new MyException("My ExceptionOccurred");             
                }
               catch(Exception e){
              System.out.println(e);
            }    
        }
    }


Output: 1 2 3 4 5 6  My exception occurred


10. What is serialization?

Serializable means transferable
  • The concept of transferring an object of a class from one location to another location is known as Serialization.
  • All the Java classes can be divided into two. 
  • The classes whose objects can be transferable.  Objects of all classes  that are implementing serializable  interface can be transferable
  • The classes whose objects can't be transferable.  Objects of all classes which are not implementing serializable interface cant be transferable.
  • To transfer the object need to convert it to byte stream:  serializing 
  • To receive an Object need to convert from byte stream to Object: deserializing
  • Classes ObjectInputStream and ObjectOutputStream are high-level streams that contain the methods for serializing and deserializing an object.

public class Student implements java.io.Serializable
{
   public String name;
   public int number ;
   
}
 
import java.io.*;

public class SerializeDemo
{
   public static void main(String [] args)
   {
      Employee e = new Employee();
      e.name = "harsha";
       
     e.number = 101;
      try
      {
         FileOutputStream fileOut =
         new FileOutputStream("/tmp/student.ser");
         ObjectOutputStream out = new ObjectOutputStream(fileOut);
         out.writeObject(e);
         out.close();
         fileOut.close();
         System.out.printf("Serialized data is saved in /tmp/employee.ser");
      }catch(IOException i)
      {
          i.printStackTrace();
      }
   }
} 
     Deserialization
     
import java.io.*;
public class DeserializeDemo
{
   public static void main(String [] args)
   {
      Student e = null;
      try
      {
         FileInputStream fileIn = new FileInputStream("/tmp/employee.ser");
         ObjectInputStream in = new ObjectInputStream(fileIn);
         e = (Student ) in.readObject();
         in.close();
         fileIn.close();
      }catch(IOException i)
      {
         i.printStackTrace();
         return;
      }catch(ClassNotFoundException c)
      {
         System.out.println("student class not found");
         c.printStackTrace();
         return;
      }
      System.out.println("Deserialized student...");
      System.out.println("Name: " + e.name);

      System.out.println("Number: " + e.number);
By default all the variables in the object is converted to persistent state. In some cases, you may want to avoid persisting some variables because you don’t have the necessity to transfer across the network. So, you can declare those variables as transient. - See more at: http://www.javabeat.net/what-is-transient-keyword-in-java/#sthash.TMBQ2f9K.dpuf

    }
} 
 

Transient Keyword: 

  • The keyword transient in Java is used to indicate that the variable should not be serialized
  • By default, all the variables in the object are converted to a persistent state. In some cases, you may want to avoid persisting some variables because you don’t have the necessity to transfer across the network. So, you can declare those variables as transient.
  • If the variable is declared as transient, then it will not be persisted. It is the main purpose of the transient keyword.
 
11. What are abstract classes and interfaces?

Abstract Class:
  • An abstract class means hiding the implementation  and showing the function definition to the user is known as Abstract class
  • Abstract classes having Abstract methods and normal methods (non-abstract methods) will be there.
  • Abstract classes having methods will be anything that means public, private, or protected.
    In Abstract classes, variables will be anything( public, private, protected)
    For Abstract classes, we are not able to create objects directly. But Indirectly we can create objects using sub-class objects.
  • A Java abstract class should be extended using the keyword “extends”.
  • A Java abstract class can have instance methods that implement a default behaviour.
    If you know the requirements and partial implementation you can go for Abstract classes.
    an abstract class can extend from a class or from an abstract class.
  • An abstract class can extend only one class or one abstract class at a time. so Abstract classes can't support multiple inheritances.
  • In comparison with Java Interfaces, java Abstract classes are fast.
    If you add a new method to the abstract class, you can provide a default implementation of it. So you don’t need to change your current code.
  • Abstract classes can have constructors.
    We can run an abstract class if it has a main() method.

Interface :

  • The interface is nothing but some set of rules.
  • Interfaces have only Abstract methods.it is purely Achieve Abstraction.
  • In Interfaces, by default, the methods will be public abstract methods.
  • In Interfaces, by default, the variables will be static final.
  • For Interfaces, we can't create objects directly or Indirectly but we can give sub-class object references to the interface.
  • Java interface should be implemented using the keyword “implements”. 
  • methods of a Java interface are implicitly abstract and cannot have implementations.
  • If u don't know any requirements and any implementation you can go for Interfaces.
  • The interface can extend only from an interface
  • The interface can extend any number of interfaces at a time. so interfaces can support multiple inheritance(syntactically not implementation of multiple inheritance).
  • In comparison with Java abstract classes, java interfaces are slow as it requires extra indirection.
  • if  you add a new method to the interface, you have to change the classes which are implementing that interface
  • Interface having no constructor.
    we can’t run an interface because they can’t have the main method implementation.

 12. How to call garbage collectors explicitly?
  • When there are no more references to an object, the object is finalized and when the Garbage Collections starts these finalized objects get collected this will be done automatically by JVM.
  • But if we want to call  Garbage collection explicitly, There are methods
    1.System.gc();
    2.Runtime.gc(); 
How to prove it?
  • The java.lang.Runtime.freeMemory() method returns the amount of free memory in the Java Virtual Machine. Calling the gc method may result in increasing the value returned by free memory
Class GcDemo{

public static void main(String args[]){
System.out.println(Runtime.getRuntime().freeMemory());

    for (int i=0;i<= 100000;i++) {
    Double d = new Double(225);
    }
    System.out.println(Runtime.getRuntime().freeMemory());
    System.gc();
    System.out.println(Runtime.getRuntime().freeMemory());
}

13. Difference between ArrayList and vector?
  • Vector was introduced in the first version of Java. that's the reason only vector is a legacy class.
  • ArrayList was introduced in Java version1.2, as part of the Java collections framework.
  • Synchronization and Thread-Safe:
  • The vector is synchronized. Synchronization and thread-safe means at a time only one thread can access the code. In the Vector class, all the methods are synchronized. That's why the Vector object is already synchronized when it is created.
  • ArrayList is not synchronized.
How To Make ArrayList Synchronized:
  • We have a direct method in the collections class to make Arrraylist Synchronized.
  • List li=new ArrayList();
  • Collections.synchronized list(li);
Automatic Increase in Capacity:
  • A Vector defaults to doubling the size of its array.
  • ArrayList increases its size by 50%.
Performance:
  • Vector is slower than ArrayList.
  • ArrayList is faster than Vector.

14. Different ways to create objects in Java

   There are four different ways to create objects in Java:

  1.     Using new keyword
  2.     Using Class.forName():
  3.     Using clone():
  4.     Using Object Deserialization: 

Using new keyword:

This is the most common way to create an object in Java. Almost 99% of objects are created in this way.

MyObject object=new Object();

Using Class.forName():

  • If we know the name of the class & if it has a public default constructor we can create an object in this way.
  • Syntax:
  • Myobject obj=(MyObject) class.forName("object").newInstance();

Using clone():

  • The clone() can be used to create a copy of an existing object.
  • Syntax:
  • MyObject obj=new MyObject();
  • MyObject object=(MyObject )obj.clone();

Using Object Deserialization:

  • Object deserialization is nothing but creating an object from its serialized form.
  • Syntax:
  • objectInputStream istream=new objectInputStream(some data);
  • MyObject object=(MyObject) instream.readObject();

Java Program on creating an object using the new keyword:

    package com.instanceofjava;
    
    public class Employee
    {
    
          private int id;
          private String name;
    
          Employee(int id,String name){
          this.id=id;
          this.name=name;
    }
    
    public void display(){
          System.out.println(id+" "+name);
    }
    
    public static void  main (String args[]){

    Emploee e=new Employee(1,"Indhu");
    Employee e1=new Employee(2,"Sindhu");
    
    e.display();
    e1.display();
    
    }
    }

 Output:

    Indhu
    Sindhu

Java Program on creating objects using the clone() method:

    package com.instanceofjava;
    
    public class Empcloneable implements Cloneable {
    
      int a;
      String name;
    
    Empcloneable(int a,String name){
    
     this.a=a;
     this.name=name;
    
    }
    
     public Empcloneable clone() throws CloneNotSupportedException{
    
      return (Empcloneable) super.clone();
    
     }
    
    public static void main(String[] args) {

    Empcloneable e=new Empcloneable(2,"Indhu");
    System.out.println(e.name);
    
    try {

    Empcloneable b=e.clone();
    System.out.println(b.name);
    
    } catch (CloneNotSupportedException e1) {
    
     e1.printStackTrace();
    }
    
    }
    }

 Output:

    Indhu
    Indhu

Java Program on creating an object using Deserialization

    package com.instanceofjava;
    import java.io.*;
    public class Files
    {
    
    public static void main(String [] args)
    {
    
     Employee e = null;
    
    try
    {
    
    FileInputStream fileIn = new FileInputStream("/E/employee.txt");
    ObjectInputStream in = new ObjectInputStream(fileIn);
    
    e = (Employee) in.readObject();
    in.close();
    fileIn.close();
    
    }catch(IOException i)
    {
    i.printStackTrace();
    return;
    
    }catch(ClassNotFoundException c)
    {
    System.out.println("Employee class not found");
    c.printStackTrace();
    return;
    }
    
    System.out.println("Deserialized Employee...");
    System.out.println("Name: " + e.name);
    
    }
    
    }


 Output:

    Name: Indhu

Java Program on creating an object using class.forName();


    package com.instanceofjava;
    public class Sample{
    
    public static void main(String args[]){
    
    try {
    
     Class s= Class.forName("com.instanceofjava.Sample");
     Sample obj=(Sample) s.newInstance(); 
     System.out.println(obj.hashcode());
    
     } catch (Exception e) {
    
      e.printStackTrace();
    
    }
    
    }
    
    }

 Output:

    2007759836

15. Why Java does not support multiple inheritance?

Inheritance:

  • The concept of getting properties of one class object to another class object is known as inheritance.
  • Here properties mean variable and methods.

Types of Inheritance:

  1. Multiple inheritance.
  2. Multilevel inheritance.

 Multiple inheritance:

  • The concept of Getting the properties from multiple class objects to sub-class objects with the same priorities is known as multiple inheritances.
  • Java Doesn't Support multiple Inheritance.

Diamond problem:

  • In multiple inheritances there is every chance of multiple properties of multiple objects with the same name available to the sub-class object with the same priorities leads to ambiguity. 
  1. //Multiple inheritance program
  2. Class A{
  3. }
  4. Class B extends A{
  5. public void show(){
  6. }
  7. }
  8. Class C extends A{
  9. public void show(){
  10. }
  11. }
  12. Class D extends B, C{  // not supported by Java leads to a syntax error.
  13. }
  •  We have two classes B and c which are inheriting A class properties.
  • Here Class D inherits B class and C class So properties present in those classes will be available in Java.
  • But both classes are at the same level with the same priority.
  • If we want to use the show() method that leads to ambiguity
  • This is called the diamond problem.
  • Because of multiple inheritances, there is a chance of the root object getting created more than once.
  • Always the root object i.e. object of the object class has to be created only once.
  • Because of above mentioned reasons multiple inheritance would not be supported by Java.
  • Thus in Java, a class can not extend more than one class simultaneously. At most, a class can extend to only one class.
So these are the reasons that Java does not support multiple inheritances. Even though having this many reasons some people say that we also get some doubts when we are using interfaces. lets me clear this one also. our immediate question should be.

Is Java supports multiple inheritances using interfaces?

  • Before that, we need to know about interfaces.
  • Interfaces having fully abstract functionality.
  • This means methods in interfaces by default public abstract methods so we need to implement these methods in classes that are extending this interface.
   
  1. /Multiple inheritance program
  2. interface A{
  3. public void  show();
  4. }
  5. interface B{
  6. public void  display();
  7. }
  8. Class C Implements A,B{
  9. }

  • Here it seems we are achieving multiple inheritances by using interfaces. but we are not.
  • Syntactically it seems to be multiple inheritance but the actual implementation of multiple inheritance is not there. how can I say that? let me clear

Difference between interfaces and inheritance: in multiple inheritances

  • Inheritance means getting the properties from one class object to another class object.
  • This means if any class extends another class then the superclass methods can be used in sub-classes happily.
  • But in interfaces the methods in interfaces are fully abstract so we need to provide functionality in our extended class and use it .seems both are opposites right? yes.
  • That is the reason we can say interfaces only supports syntactical multiple inheritance which is not the implementation of multiple inheritance.
So finally java supports only the syntax of multiple inheritance and does not supports the implementation of multiple inheritance.
Inheritance is like debit and interface is like credit but the interface has its own importance in other concepts like server-side programming

16. Difference between throw and throws in Java

Throw: 

  • throw keyword used to throw user defined exceptions.(we can throw predefined exception too)
  • If we are having our own validations in our code we can use this throw keyword.
  • For Ex: BookNotFoundException, InvalidAgeException (user defined) 
  1. //Custom exception
  2. package com.instanceofjavaforus;
  3. public class InvalidAgeException extends Exception {
  4.  InvaidAgeException(String msg){
  5.  super(msg);
  6.  }
  7. }
     

  1. package com.instanceofjavaforus;
  2. public class ThrowDemo {
  3. public boolean isValidForVote(int age){
  4.  try{
  5.    if(age<18){
  6.   throw new InvalidAgeException ("Invalid age for voting");
  7. }
  8.  }catch(Exception e){
  9.  System.out.println(e);
  10.  }
  11.   return false;
  12.  }
  13.   public static void main(String agrs[]){
  14.  ThrowDemo obj= new ThrowDemo();
  15.    obj.isValidForVote(17);
  16.   }
  17. }
We can throw predefined exceptions also

  1. package com.instanceofjavaforus;
  2. public class ThrowDemo {
  3. public void method(){
  4.  try{
  5.   
  6.   throw new NullPointerException("Invalid age for voting");
  7. }
  8.  }catch(Exception e){
  9.  System.out.println(e);
  10.  }
  11.  }
  12.   public static void main(String agrs[]){
  13.  ThrowDemo obj= new ThrowDemo();
  14.    obj.method();
  15.   }
  16. }
Like this, we can throw checked exceptions and unchecked exceptions also. But the throw keyword is mainly used to throw used defined exceptions/custom exceptions.

Throws:

  • The functionality of the throws keyword is only to explicitly mention that the method is proven to transfer un handled exceptions to the calling place.
  1. package com.instanceofjavaforus;
  2. public class ThrowSDemo {
  3. public void method(int a,int b) Throws ArithmeticException{
  4.  
  5. inc c= a/b;
  6.  }
  7.   public static void main(String agrs[]){
  8.  ThrowDemo obj= new ThrowDemo();
  9.    try{
  10. obj.method(1,0);
  11. }catch(Exception e){
  12.  System.out.println(e);
  13. }
  14.   }
  15. }

 Uses of throws keyword:

  • Using the throws keyword we can explicitly provide the information about unhand-led exceptions of the method to the end user, Java compiler, or JVM.
  • Using the throws keyword we can avoid try-catch with respect to the statements which are proven to generate checked exceptions.
  • It is highly recommended not to avoid try-catch with respect to the statements which are proven to generate exceptions in the main method using the throws keyword to the main() method.

17. What is the difference between equals() method and == operator

== operator:

  •  == operator used to compare objects references.
  • used to compare data of primitive data types
  • if we are comparing two objects using the "==" operator if the reference of both is the same then it will return true otherwise returns false.
  • obj1==obj2;
  • If we are comparing primitive data type variables then it compares data of those two variables
  • Ex: int a=12; int b=12; if(a==b) returns true

Comparing primitive values: 

  1. package com.instanceofjava;
  2.  
  3. Class Demo{ 
  4.  
  5. public static void main (String args[]) {

  6. int a=12;
  7. int b=13;
  8. int c=12;
  9.  
  10. if(a==b){
  11. System.out.println("a and b are equal");
  12.  
  13. if(b==c){
  14. System.out.println("a and b are equal");
  15.  
  16. }
  17. }

Comparing Objects:

  1. package com.instanceofjavaforus;
  2.  
  3. Class Demo{ 
  4.  
  5. public static void main (String args[]) {
  6.  
  7.  Demo obj1= new Demo();
  8. Demo obj2=new Demo();
  9.  
  10. if(obj1==obj2){ // here both are two different objects(memory allocation wise);
  11.  
  12. System.out.println("obj1 and obj2 are referring to same address");
  13.  
  14. }else{
  15.  
  16.  System.out.println("obj1 and obj2 are referring to different address");
  17.  
  18. }
  19. }
  20. }

Comparing String Objects:

  1. package com.instanceofjava;
  2.  
  3. Class ComapreStringDemo{ 
  4.  
  5. public static void main (String args[]) {
  6.  
  7.  String s1=new String("abc");
  8. String s2=new String("abc");
  9.  
  10. if(s1==s2){ // here it returns false
  11. System.out.println("obj1 and obj2 are referring to same address");
  12. }else{
  13.  System.out.println("obj1 and obj2 are referring to different address");
  14.  
  15. }
  16. }

Comparing String Literals:

  •  If we declared two string literals with the same data then those will refer to the same reference.
  • means if we create any object using a string literal then it will be created in the string pool 
  • then if we are created another literal with the same data then it won't create another object but rather refers to the same object in the pool.
  • so if compare two string literals with the same data using the "==" operator then it returns true.
  1. package com.instanceofjava;
  2.  
  3. Class ComapreStringLiteralDemo{ 
  4.  
  5. public static void main (String args[]) {
  6.  
  7.  String s1="abc";
  8. String s2="abc";
  9.  
  10. if(s1==s2){ // here it returns true
  11.  
  12. System.out.println("obj1 and obj2 are referring to same address");
  13.  
  14. }else{
  15.  
  16.  System.out.println("obj1 and obj2 are referring to different address");
  17.  
  18. }
  19. }
  20. }

equals() method:

  • equals() method defined in the "object" class.
  • By default equals methods behave like the "==" operator when comparing objects.
  • By default equals() method compares references of objects.
  • But All wrapper classes and String classes override this equals method and comparing data.
  • This means in the String class and in All wrapper classes this equals() method is overridden to compare data of those class objects. 

Comparing String Objects:

  1. package com.instanceofjava;
  2.  
  3. Class ComapreStringDemo{ 
  4.  
  5. public static void main (String args[]) {
  6.  
  7.       String s1=new String("ABC");
  8.       String s2=new String("ABC");
  9.  
  10.       if(s1.equals(s2)){ // here it returns true
  11.  
  12.                System.out.println(" data present in obj1 and obj2 is same");
  13.  
  14.      }else{
  15.  
  16.                System.out.println(" data present in obj1 and obj2 is different");
  17.  
  18.      }
  19. }
  20. }

 Comparing custom objects:

  • If we want to compare custom objects means our own objects' data.
  • Then we need to override the equals method and in that, we need to compare data.

  1. package com.instanceofjavaforus;

    public class Patient {
       String name;
       Patient(String name){
           this.name=name;
       }
          public boolean equals(Patient obj){
          
           if(this.name.equals(obj)){
               return true;
           }else{
               return false;
           }
       }
           public static void main(){
            Patient obj1= new Patient("sam");
           
            Patient obj2= new Patient("sam");
           
            System.out.println(obj1.equals(obj2)); //returns true
        }
           
    }

Important points to note about equals() and "==":

  • "==" used to compare data for primitive data type variables .
  • "==" operator compares objects references
  • By default equals() method behaves like the "==" operator for objects means comparing objects references.
  • All wrapper classes and String class override this equals() method and compares data of two objects. if the same returns true.(whenever we override the equals() method we need to override the hashcode() method too and if two objects on an equal method same then both should have the same hashcode).
  • And in the equals() method in string class logic includes the "==" operator too.

  1. package com.instanceofjava;
  2.  
  3. public boolean equals(Object anObject) {
  4.    if (this == anObject) {
  5.       return true;
  6.      }
  7.  if (anObject instanceof String) {
  8.      String anotherString = (String) anObject;
  9.      int n = value.length;
  10.     if (n == anotherString.value.length) {
  11.     char v1[] = value;
  12.      char v2[] = anotherString.value;
  13.   int i = 0;
  14. while (n-- != 0) {
  15.    if (v1[i] != v2[i])
  16.            return false;
  17.            i++;
  18.        }
  19.          return true;
  20.         }
  21.     }
  22.        return false;
  23.   }

18. Differences between HashMap and Hash-table

Differences between HashMap and Hash-table
  •  Synchronization or Thread Safe: One of the major differences between HashMap and Hashtable is that HashMap is non-synchronized whereas Hashtable is synchronized, which means Hashtable is thread-safe and can be shared between multiple threads but HashMap cannot be shared between multiple threads without proper synchronization. Java 5 introduced ConcurrentHashMap which is an alternative to Hashtable and provides better scalability than Hashtable in Java. Synchronized means only one thread can modify a hash table at one point in time. Basically, it means that any thread before performing an update on a hashtable will have to acquire a lock on the object while others will wait for the lock to be released.
  • Null keys and null values: The HashMap class is roughly equivalent to Hashtable, except that it permits nulls. (HashMap permits one null key and multiple null values.
    Hashtable doesn't permit any sort of nulls (key or values).).
  • Iterating the values: The third significant difference between HashMap vs Hashtable is that Iterator in the HashMap is a fail-fast iterator while the enumerator for the Hashtable is not and throws ConcurrentModificationException if any other Thread modifies the map structurally by adding or removing any element except Iterator’s own remove() method. But this is not a guaranteed behavior and will be done by JVM with the best effort. This is also an important difference between Enumeration and Iterator in Java.
  • Default Capacity: 
  •  Hashmap: static final int DEFAULT_INITIAL_CAPACITY =16  static final float DEFAULT_LOAD_FACTOR = 0.75f;  
  • Hashtable:  static final int DEFAULT_INITIAL_CAPACITY = 11;   static final float DEFAULT_LOAD_FACTOR = 0.75f;
  • HashMap does not guarantee that the order of the map will remain constant over time.
HashMap can be synchronized by using Collections.synchronizedMap() method
Map m = Collections.synchronizedMap(hashMap);
Example:

import java.util.HashMap;

import java.util.Hashtable;

public class HashMapHashtableExample {
   
    public static void main(String[] args) {      

 

        Hashtable<String,String> hashtableobj = new Hashtable<String, String>();
        hashtableobj.put("name", "ramu");
        hashtableobj.put("petname", "ram");
        System.out.println("Hashtable object output :"+ hashtableobj);



        HashMap hashmapobj = new HashMap();
        hashmapobj.put("name", "ramu"); 
        hashmapobj.put("pertname", "ram");
        System.out.println("HashMap object output :"+hashmapobj);

 }
}