Saturday, 12 January 2019

Java Beginners Excercises Part - 2


BASIC JAVA

1) Correct the program below so that it can compile and run without any errors and prints the text “Hello World”:
public class MyFirstProgram { public void main(String args){ System.out.println("Hello World"); } }
public class MyFirstProgram {
   public static void main(String[] args){         
         System.out.println("Hello World");
   }
}

DATA TYPES AND CONSTANTS

1) Correct the variable initializations below:

public class DefineSomeVariables
{
    double amount = 100.50;
    long population = 9999999999;
}


public class DefineSomeVariables
{
     double amount = 100.50d;
     long earthPopulation = 9999999999l;
}

2) What is the difference between Variable and Constant?

Constants are basically variables whose value can't change. We use the keyword final to declare constants like below.

public final int DAYS = 7;

According to java convention, the Constant name should be in capital letters always.

OPERATORS

1) Provide the output of the below code:

public class SimpleOperations
{
    public static void main(String[] args)
    {
        double a = 10.5 % 2;
        double b = 3.5 * 2;
        float c = (float)6.8 / 2;
        System.out.println("a => " + a + " b => " + b + " => c " + c);
     }
}

a => 0.5 b => 7.0 => c 3.4

2) What is the data type conversion in Java? Fill in the missing values in the below code.

double x = 9.997;
int nx = (...) x;

When we assign a 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.

double x = 9.997;
int nx = (int) x;

3) Fill in the blank below:

x += 4; is equivalent to ...

x += 4; is equivalent to x = x + 4;



4) After execution below statements what would be the value of variables m, n, a and b:

int m = 7;
int n = 7;

int a = 2 * ++m;
int b = 2 * n++;

a = 16, m = 8
B = 14, n = 8


5) Write down the result of the below expressions in the form of True and False:

int x = 10;
Int y = 20;

x < y
...


x > y
...


x <= y
...


x >= y
...


x == y
...


x != y
...



x < y = True

x > y = False

X <= y = True

x >= y = False

x == y = False

x != y = True





ENUMS

1) Why use Enums instead of Constants? Which is better?

// Constants for player types
public static final String ARCHER = "Archer";
public static final String WARRIOR = "Warrior";

// Constants for genders
public static final String MALE = "Male";
public static final String FEMALE = "Female";

then you end up not really knowing the type of your data - leading to potentially incorrect code:

String playerType = Constants.MALE; // This is wrong but Java will not complain

if you use enums, that would end up as:

// Compile-time error - incompatible types!
PlayerType playerType = Gender.MALE;

This is why Enums are better than Constants.

STRING

1) Write down the output of the below String comparisons:

public class StringComp
{
    public static void main(String[] args)
    {
        String a = "Rahul";
        String b = "Rahul";
        String c = new String("Rahul");
        System.out.println("Rahul".equals(a));
        System.out.println("Rahul" == a);
        System.out.println(a.equals(b));
        System.out.println(a==b);
        System.out.println(a.equals(c));
        System.out.println(a==c);
    }
}

System.out.println("Rahul".equals(a)); // True
System.out.println("Rahul" == a); // True
System.out.println(a.equals(b)); // True
System.out.println(a==b); // True
System.out.println(a.equals(c)); // True
System.out.println(a==c); // False

2) Write down the output of the below String class methods:

public class StringMethods
{
    public static void main(String[] args)
    {
       String str = "Java Fundamentals";
System.out.println(str.charAt(5));
System.out.println(str.startsWith("java"));
System.out.println(str.endsWith("tals"));
System.out.println(str.indexOf("men"));
System.out.println(str.lastIndexOf("a"));
System.out.println(str.replace("Fund", "Coll"));
System.out.println(str.substring(3));
System.out.println(str.substring(1, 5));
System.out.println(str.toLowerCase());
System.out.println(str.toUpperCase());

    }
}

System.out.println(str.charAt(5)); // F
System.out.println(str.startsWith("java")); // false
System.out.println(str.endsWith("tals")); // true
System.out.println(str.indexOf("men")); // 10
System.out.println(str.lastIndexOf("a")); // 14
System.out.println(str.replace("Fund", "Coll")); // Java Collamentals
System.out.println(str.substring(3)); // a Fundamentals
System.out.println(str.substring(1, 5)); // ava
System.out.println(str.toLowerCase()); // java fundamentals
System.out.println(str.toUpperCase()); // JAVA FUNDAMENTALS



3) Correct the below code if you see any mistakes?
String str;
// Some code here
if(str.length != 0 && str != null)
{
    //Do something here
}


String str;
// Some code here
if(str != null && str.length != 0)
{
     //Do something here
}

SCANNER / COMMAND LINE INPUT

1) Complete the below code which is used to take input from the command line:

public class CommandLineInput
{
    public static void main(String args[])
    {
        Scanner in = new Scanner(.....); // Code missing here
        System.out.print("What is your name? ");
        String name = …………………………….. // code missing here
        System.out.print("Your name is: "+name);

        //Get second input
        System.out.print("How old are you? ");
        int age = ……………………………………. // code missing here
        System.out.print("Your age is: "+age);
     }
}


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);

      }
}

BLOCK SCOPE

1) Fill in the blanks:

class Test
{
     private int x;
     public void setX(int x)
     {
          // set the x argument variable value in instance field x
………………………………………….
      }
}

class Test
{
       private int x;
       public void setX(int x)
       {
            // set the x argument variable value in instance field x
    This.x = x;
       }
}


2) Write the output of the below program:

public class Test
{
     static int x = 11;
     private int y = 33;
     public void method1(int x)
     {
         Test t = new Test();
          this.x = 22;
          y = 44;
          System.out.println("Test.x: " + Test.x);
          System.out.println("t.x: " + t.x);
          System.out.println("t.y: " + t.y);
          System.out.println("y: " + y);
      }
      public static void main(String args[])
      {
          Test t = new Test();
           t.method1(5);
       }
}

Test.x: 22
t.x: 22
t.y: 33
Y: 44

LOOPS

1) Can for and while loop be infinite? If yes, implement the code.

Yes, We can have infinite for and while loops.

while(true)
{
      //This code execution will be infinite
}

for(;;)
{
     //This code execution will be infinite
}

2) Correct the below code so that the below program print number 1 to 10:

int i = 0;
for(i<10;)
{
    System.out.println(i);
}

int i = 1;
for(;i<=10; i++)
{
     System.out.println(i);
}

ARRAY

1) What type of error is in the below code? Compile time or run time? Fix the error and rewrite that code block.

class ArrayExample
{
      public static void main (String[] args)
      {
           int[] arr = new int[2];
           arr[0] = 10;
           arr[1] = 20;

           for (int i = 0; i <= arr.length; i++)
                   System.out.println(arr[i]);
       }
}

It is a Runtime error. This program will throw ArrayIndexOutOfboundException.

We have to correct the loop condition like the below:

for (int i = 0; i < arr.length; i++)
     System.out.println(arr[i]);

2) Fill in the blanks so that only indexes of even number gets printed:

public void arrayExample()
{
    int[] a = new int[10];
    int length = a.length;
    for (int i = 0; i < a.length; i++)
        a[i] = i+10;

     //Print the array
    for (int i = 0; i < a.length; ...) // you have to change here in the code
        System.out.println(a[i]);
}

public void arrayExample()
{
     int[] a = new int[10];
     int length = a.length;
     for (int i = 0; i < a.length; i++)
        a[i] = i+10;

     // print the array
     for (int i = 0; i < a.length; i+=2) // you have to change here in the code
       System.out.println(a[i]);
}

3) What would be the output of the following program where we are copying an array.

class TestArrayCopyDemo {
      public static void main(String[] args) {
          char[] copyFrom = { 'd', 'e', 'c', 'a', 'f', 'f', 'e',
                                    'i', 'n', 'a', 't', 'e', 'd' };
          char[] copyTo = new char[7];
          System.arraycopy(copyFrom, 2, copyTo, 0, 7);
          System.out.println(String.valueOf(copyTo));
      }
}

caffeine


CLASSES AND OBJECTS

1) Identify the issues and fix those:

public class Employee
{
       String name;
int salary;

        void Employee(String name, int salary) // you can find a issue here
        {
             this.name = name;
             this.salary = salary;
         }

         private int calulateTax()
         {
             // you can find an issue here
             static int tax = 10; // This is the percent;
             return salary * 10 / 100;
         }

        public static void main(String[] args)
        {
              Employee e = new Employee("Rahul", 1000);
             System.out.println(e.calulateTax());
         }
}

public class Employee
{
       String name;
int salary;

       Employee(String name, int salary)
       {
            this.name = name;
            this.salary = salary;
        }

        private int calulateTax()
        {
             int tax = 10; // This is the percent;
             return salary * 10 / 100;
         }

         public static void main(String[] args)
         {
               Employee e = new Employee("Rahul", 1000);
               System.out.println(e.calulateTax());
          }
}

2) Fill in the blanks so that puppy’s age gets printed on the console

public class Puppy
{
     int puppyAge;

     public Puppy(String name)
     {
        System.out.println("Name chosen is :" + name );
     }

     public void setAge( int age )
     {
         puppyAge = age;
     }

     public int getAge()
     {
         System.out.println("Puppy's age is :" + puppyAge );
         return puppyAge;
     }

     public static void main(String []args)
     {
          Puppy myPuppy = new Puppy( "tommy" );
          myPuppy.setAge( 2 );

         /* Call another class method to get puppy's age, add code here */
…………………………………………………………...

     }
}

public class Puppy
{
     int puppyAge;

     public Puppy(String name)
     {
           System.out.println("Name chosen is :" + name );
     }

     public void setAge( int age )
     {
           puppyAge = age;
     }

     public int getAge()
     {
           System.out.println("Puppy's age is :" + puppyAge );
           return puppyAge;
      }

      public static void main(String []args)
      {
           Puppy myPuppy = new Puppy( "tommy" );
           myPuppy.setAge( 2 );

           /* Call another class method to get puppy's age, add code here */
           myPuppy.getAge( );

       }
}

STATIC METHODS

1) Correct the method declaration so that we can call that statically:

public class StaticMethodExample
{


public void getListofFriuts()
{
      // do something here
}

public static void main(String[] args)
{
      StaticMethodExample.getListofFriuts();
}
}

public class StaticMethodExample
{
public static void getListofFruits()
{
      // do something here
}

public static void main(String[] args)
{
      StaticMethodExample.getListofFruits();
}
}


2) What is wrong with the below code? I just want to call one constructor from another using this keyword

public Employee(double s)
{
       nextId++;
this("Employee #" + nextId, s);

}

this keyword statement should be the first line in the constructor like below:

public Employee(double s)
{
       this("Employee #" + nextId, s);
nextId++;

}
SPECIFIC CODE BLOCKS

1) What would be the output of the following code?

public class Employee
{
private static int nextId;
private int id;
private String name;
private double salary;

static {
   System.out.println(“This is the static block”);
}

// object initialization block
{
System.out.println(“This is the initialization block”);
id = nextId;
nextId++;
}

public Employee(String n, double s)
{
     System.out.println(“This is the two argument constructor”);
name = n;
salary = s;
}

public Employee()
{
      System.out.println(“This is the no argument constructor”);
name = "";
salary = 0;
}

public static void main(String[] args)
{
    Employee e = new Employee();
}
}

This is the static block
This is the initialization block
This is the no argument constructor

INHERITANCE

1) What is the benefit of inheritance? How can we call the parent class constructor from the child class?

The main benefit of inheritance is code reusability. We can call the parent class constructor using the super keyword.

2) What is the error in below code? Correct that.

class MountainBike extends Bicycle
{
     public int seatHeight;
     public MountainBike(int gear,int speed, int startHeight)
     {
         seatHeight = startHeight;
         super(gear, speed);
      }
      public void setHeight(int newValue)
      {
           seatHeight = newValue;
      }
}

public MountainBike(int gear,int speed, int startHeight)
{
      super(gear, speed);
      seatHeight = startHeight;
}

super keyword call can be used as first-line inside a constructor.

3) How can we make sure that no one can extend a particular class?

Using final keyword. If we add final keyword before the class name then that class can not be extended by any class.

public final class Utility
{

}

4) Modify the below code so that no one can override the below method in any child class.

public void noOneCanOverrideMe()
{

}

public final void noOneCanOverrideMe()
{

}


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.