Wednesday, 24 May 2023

Java ExcecutorService Example

The Java ExecutorService is an interface that provides a way to execute tasks asynchronously. It is part of the java.util.concurrent package.

The ExecutorService interface provides a number of methods for submitting tasks, retrieving results, and managing the pool of threads. Some of the most commonly used methods are:

  • submit(Runnable task): Submits a task to the executor service. The task will be executed by one of the threads in the pool.
  • submit(Callable task): Submits a task to the executor service. The task will be executed by one of the threads in the pool and the result will be returned.
  • invokeAll(Collection tasks): Executes all of the tasks in the collection and returns a list of Futures. A Future represents the result of a task.
  • invokeAny(Collection tasks): Executes all of the tasks in the collection and returns the result of the first task that completes.
  • shutdown(): Shuts down the executor service. No new tasks will be accepted after the executor service has been shut down.
  • shutdownNow(): Shuts down the executor service and attempts to cancel all of the running tasks.

The ExecutorService interface can be used to execute a variety of tasks, such as:

  • Parsing a large file
  • Rendering a complex image
  • Executing a database query
  • Sending an email

The ExecutorService interface provides a convenient way to execute tasks asynchronously. It can help to improve the performance of your application by allowing you to execute multiple tasks at the same time.

Here is an example of how to use the ExecutorService interface to execute a task:

Code snippet
ExecutorService executorService = Executors.newFixedThreadPool(10);

Runnable task = () -> {
  // Do something
};

Future<String> future = executorService.submit(task);

String result = future.get();

In this example, we create an ExecutorService with a fixed pool of 10 threads. We then submit a task to the executor service. The task will be executed by one of the threads in the pool and the result will be returned. We can then get the result of the task by calling the get() method on the Future object.

The ExecutorService interface is a powerful tool that can be used to execute tasks asynchronously. It can help to improve the performance of your application by allowing you to execute multiple tasks at the same time.

Chatgpt usage for Software Developers

ChatGPT is a large language model chatbot developed by OpenAI. It is trained on a massive dataset of text and code and can generate text, translate languages, write different kinds of creative content, and answer your questions in an informative way.

ChatGPT can be used by software developers for a variety of tasks, including:

  • Generating code: ChatGPT can generate code in a variety of programming languages, including Python, Java, C++, and JavaScript. This can be helpful for developers who need to quickly prototype an application or add new features to an existing one.
  • Answering questions: ChatGPT can answer questions about coding, programming languages, and software development. This can be helpful for developers who are stuck on a problem or need to learn about new technology.
  • Writing documentation: ChatGPT can generate documentation for software projects. This can save developers time and effort, and ensure that the documentation is accurate and up-to-date.
  • Testing code: ChatGPT can be used to test code for errors. This can help developers to identify and fix bugs early in the development process.
  • Debugging code: ChatGPT can be used to debug code that is not working correctly. This can help developers to identify the source of the problem and fix it quickly.

Overall, ChatGPT is a powerful tool that can be used by software developers to improve their productivity and efficiency. It can be used to generate code, answer questions, write documentation, test code, and debug code.

Here are some specific examples of how ChatGPT can be used by software developers:

  • A developer can use ChatGPT to generate a list of all the possible ways to sort a list of numbers.
  • A developer can use ChatGPT to answer a question about how to implement a particular algorithm.
  • A developer can use ChatGPT to write a user manual for a new software application.
  • A developer can use ChatGPT to test a new piece of code for errors.
  • A developer can use ChatGPT to debug a piece of code that is not working correctly.

ChatGPT is still under development, but it has the potential to revolutionize the way software is developed. It can help developers to save time and effort and improve the quality of their work.

Tuesday, 23 May 2023

Java use enum in switch

Here is an example of how to use an enum in a switch statement in Java:

public enum Color {
  RED,
  GREEN,
  BLUE;
}

public class ColorDemo {
  public static void main(String[] args) {
    Color color = Color.RED;

    switch (color) {
      case RED:
        System.out.println("Red");
        break;
      case GREEN:
        System.out.println("Green");
        break;
      case BLUE:
        System.out.println("Blue");
        break;
    }
  }
}
Red

As you can see, the switch statement is used to execute different codes based on the value of the color variable. In this case, the code will print out the name of the color that is stored in the color variable.

Here is another example of how to use an enum in a switch statement in Java:

Java
public enum DayOfWeek {
  SUNDAY,
  MONDAY,
  TUESDAY,
  WEDNESDAY,
  THURSDAY,
  FRIDAY,
  SATURDAY;
}

public class DayOfWeekDemo {
  public static void main(String[] args) {
    DayOfWeek dayOfWeek = DayOfWeek.MONDAY;

    switch (dayOfWeek) {
      case SUNDAY:
        System.out.println("It's Sunday!");
        break;
      case MONDAY:
        System.out.println("It's Monday!");
        break;
      case TUESDAY:
        System.out.println("It's Tuesday!");
        break;
      case WEDNESDAY:
        System.out.println("It's Wednesday!");
        break;
      case THURSDAY:
        System.out.println("It's Thursday!");
        break;
      case FRIDAY:
        System.out.println("It's Friday!");
        break;
      case SATURDAY:
        System.out.println("It's Saturday!");
        break;
    }
  }
}

This code will print out the following output:

It's Monday!

As you can see, the switch statement can be used to execute different codes based on the value of an enum variable. This can be a very convenient way to write code that checks for a specific value.

Usage of Enum and Switch Keyword in Java

The enum keyword in Java is used to create a special type of class that can only contain a finite set of values. These values are called enum constants, and they are declared using the keyword enum followed by the name of the enum class. For example, the following code creates an enum calledColor with the three values RED, GREEN, and BLUE:

public enum Color {
  RED,
  GREEN,
  BLUE;
}

Enum constants are public, static, and final by default. This means that they can be accessed from anywhere in the program, and they cannot be changed. Enum constants can also be used with the switch keyword. For example, the following code uses a switch statement to print out the name of the colour that is passed in as a parameter:

public class ColorDemo {
  public static void main(String[] args) {
    Color color = Color.RED;

    switch (color) {
      case RED:
        System.out.println("Red");
        break;
      case GREEN:
        System.out.println("Green");
        break;
      case BLUE:
        System.out.println("Blue");
        break;
    }
  }
}

This code will print out the following output:

Red

A switch keyword is a powerful tool that can be used to execute different codes based on the value of a variable. When used with enum constants, it can be a very concise way to write code that checks for a specific value.

Here are some of the benefits of using enums in Java:

  • Enum constants are public, static, and final by default, which makes them more secure and reliable.
  • Enum constants can be used with the switch keyword, which makes it easy to write code that checks for a specific value.
  • Enum constants can be used to represent a set of related values, such as the days of the week or the colours of the rainbow.

Here are some of the drawbacks of using enums in Java:

  • Enum constants cannot be changed, which can make it difficult to update code if the values of the enum constants change.
  • Enum constants can only be used with the switch keyword, which can limit the flexibility of the code.

Overall, enums are a powerful tool that can be used to represent a set of related values in Java. They offer a number of benefits, such as security, reliability, and conciseness. However, there are also some drawbacks, such as the inability to change the values of enum constants and the limited flexibility of the switch keyword.

Thursday, 18 May 2023

Java arraylist contains case insensitive

There are several ways to check if an element exists in an ArrayList in a case-insensitive way in Java.

Using String.equalsIgnoreCase()

The simplest way is to use the String.equalsIgnoreCase() method. This method compares two strings for equality, ignoring case differences.

For example, the following code will check if the string "hello" exists in the ArrayList list in a case-insensitive way:

boolean found = list.contains(new String("hello").toLowerCase())

Using a custom function

You can also create a custom function to check if an element exists in an ArrayList in a case-insensitive way. This function can be used as follows:

boolean found = containsIgnoreCase(list, "hello");

The following is an example of a custom function that can be used to check if an element exists in an ArrayList in a case-insensitive way:

public static boolean containsIgnoreCase(List<String> list, String str) {
  for (String s : list) {
    if (s.equalsIgnoreCase(str)) {
      return true;
    }
  }
  return false;
}

Using the Stream API

If you are using Java 8 or later, you can also use the Stream API to check if an element exists in an ArrayList in a case-insensitive way. The following code shows how to do this:

boolean found = list.stream().anyMatch(str::equalsIgnoreCase);

In this code, the anyMatch() method is used to check if any element in the stream matches the given string. The str::equalsIgnoreCase method is a method reference that calls the equalsIgnoreCase() method on the given string.

Conclusion

These are just a few of the ways to check if an element exists in an ArrayList in a case-insensitive way in Java. The best way to do this will depend on your specific needs.

Java hashmap to json string

There are several ways to convert a Java HashMap to a JSON string. Here are two of the most common methods:

Using Gson

Gson is a popular Java library for converting Java objects to and from JSON. To convert a HashMap to a JSON string using Gson, you can use the following code:

import com.google.gson.Gson;

public class Main {

  public static void main(String[] args) {
    // Create a HashMap.
    HashMap<String, String> map = new HashMap<>();
    map.put("name", "John Doe");
    map.put("age", "30");

    // Create a Gson object.
    Gson gson = new Gson();

    // Convert the HashMap to a JSON string.
    String json = gson.toJson(map);

    // Print the JSON string.
    System.out.println(json);
  }
}

The output of the above code will be the following JSON string:

{
  "name": "John Doe",
  "age": "30"
}

Using Jackson

Jackson is another popular Java library for converting Java objects to and from JSON. To convert a HashMap to a JSON string using Jackson, you can use the following code:

import com.fasterxml.jackson.databind.ObjectMapper;

public class Main {

  public static void main(String[] args) {
    // Create a HashMap.
    HashMap<String, String> map = new HashMap<>();
    map.put("name", "John Doe");
    map.put("age", "30");

    // Create an ObjectMapper object.
    ObjectMapper mapper = new ObjectMapper();

    // Convert the HashMap to a JSON string.
    try {
      String json = mapper.writeValueAsString(map);
    } catch (JsonProcessingException e) {
      e.printStackTrace();
    }

    // Print the JSON string.
    System.out.println(json);
  }
}

The output of the above code will be the same as the output of the previous code.

Java convert a date string to a date format

To convert a Java date string to a date format, you can use the following steps:

  1. Create a SimpleDateFormat object with the desired date format.
  2. Use the parse() method to parse the date string into a Date object.
  3. Use the format() method to format the Date object into a new date string with the desired format.

For example, the following code converts a date string in the format "MM/dd/yyyy" to a date string in the format "yyyy-MM-dd":

import java.text.SimpleDateFormat;

public class Main {

  public static void main(String[] args) {
    // Create a SimpleDateFormat object with the desired date format.
    SimpleDateFormat dateFormat1 = new SimpleDateFormat("MM/dd/yyyy");

    // Create a date string in the format "MM/dd/yyyy".
    String dateString1 = "05/18/2023";

    // Parse the date string into a Date object.
    Date date1 = dateFormat1.parse(dateString1);

    // Create a SimpleDateFormat object with the desired date format.
    SimpleDateFormat dateFormat2 = new SimpleDateFormat("yyyy-MM-dd");

    // Format the Date object into a new date string with the desired format.
    String dateString2 = dateFormat2.format(date1);

    // Print the new date string.
    System.out.println(dateString2);
  }
}

The output of the above code will be the following date string:

2023-05-18

Java arraylist to json string

There are several ways to convert an ArrayList to a JSON string in Java. Here are two of the most common methods:

Using Gson

Gson is a popular Java library for converting Java objects to and from JSON. To convert an ArrayList to a JSON string using Gson, you can use the following code:

Code snippet
import com.google.gson.Gson;

public class Main {

public static void main(String[] args) {
// Create an ArrayList of strings.
ArrayList<String> list = new ArrayList<>();
list.add("Hello");
list.add("World");

// Create a Gson object.
Gson gson = new Gson();

// Convert the ArrayList to a JSON string.
String json = gson.toJson(list);

// Print the JSON string.
System.out.println(json);
}
}

The output of the above code will be the following JSON string:

Code snippet
[
"Hello",
"World"
]

Using Jackson

Jackson is another popular Java library for converting Java objects to and from JSON. To convert an ArrayList to a JSON string using Jackson, you can use the following code:

Code snippet
import com.fasterxml.jackson.databind.ObjectMapper;

public class Main {

public static void main(String[] args) {
// Create an ArrayList of strings.
ArrayList<String> list = new ArrayList<>();
list.add("Hello");
list.add("World");

// Create an ObjectMapper object.
ObjectMapper mapper = new ObjectMapper();

// Convert the ArrayList to a JSON string.
try {
String json = mapper.writeValueAsString(list);
} catch (JsonProcessingException e) {
e.printStackTrace();
}

// Print the JSON string.
System.out.println(json);
}
}

The output of the above code will be the same as the output of the previous code.

Java array to arraylist

There are several ways to convert an array to an ArrayList in Java. Here are three of the most common methods:

Using Arrays.asList()

The Arrays.asList() method is the simplest way to convert an array to an ArrayList. It takes an array as its only argument and returns a List object that contains the elements of the array.

For example, the following code converts an array of strings to an ArrayList of strings:

Code snippet
String[] array = { "Hello", "World" };
List<String> list = Arrays.asList(array);

The list object returned by Arrays.asList() is backed by the original array. This means that if you modify the original array, the changes will be reflected in the list object.

Using Collections.addAll()

The Collections.addAll() method is another way to convert an array to an ArrayList. It takes two arguments: a List object and an array. The method adds all of the elements of the array to the List object.

For example, the following code converts an array of strings to an ArrayList of strings:

Code snippet
String[] array = { "Hello", "World" };
List<String> list = new ArrayList<>();
Collections.addAll(list, array);

The advantage of using Collections.addAll() over Arrays.asList() is that you can create a new ArrayList object and then add the elements of the array to it. This gives you more control over the type of List object that is created.

Using an iteration loop

The third way to convert an array to an ArrayList is to use an iteration loop. This method is the most flexible, but it is also the most time-consuming.

To convert an array to an ArrayList using an iteration loop, you first need to create a new ArrayList object. Then, you need to iterate through the array and add each element to the ArrayList object.

For example, the following code converts an array of strings to an ArrayList of strings:

Code snippet
String[] array = { "Hello", "World" };
List<String> list = new ArrayList<>();
for (String element : array) {
  list.add(element);
}

This method is the most flexible because you can use it to convert any type of array to any type of List object. However, it is also the most time-consuming because you need to iterate through the entire array.

Tuesday, 9 May 2023

Why Should an Object Used As the Key should be Immutable

Question) Why Should an Object Used As the Key should be Immutable? 
This is another follow-up to the previous core Java interview questions. It's good to test the depth of technical knowledge of candidate by asking more and more question on the same topic. If you know about Immutability, you can answer this question by yourself. The short answer to this question is key should be immutable so that hashCode() method  always return the same value.

Since hash code returned by hashCode() method depends on upon the content of object i.e. values of member variables. If an object is mutable than those values can change and so is the hash code. If the same object returns different hash code once you inserted the value in HashMap, you will end up searching in different bucket location and will not able to retrieve the object. That's why a key object should be immutable. It's not a rule enforced by the compiler but you should take care of it as an experienced programmer.

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()
{

}