How will you write an own immutable class in java ?

Writing an immutable class is generally easy but there can be some tricky situations. Follow the following guidelines:

1. A class is declared final (i.e. final classes cannot be extended).
public final class MyImmutable { ? }

2. All its fields are final (final fields cannot be mutated once assigned).
private final int[] myArray; //do not declare as Æ private final int[] myArray = null;

3. Do not provide any methods that can change the state of the immutable object in any way ? not just setXXX
methods, but any methods which can change the state.

4. The ?this? reference is not allowed to escape during construction from the immutable class and the immutable

class should have exclusive access to fields that contain references to mutable objects like arrays, collections
and mutable classes like Date etc by:

Declaring the mutable references as private.

Not returning or exposing the mutable references to the caller (this can be done by defensive copying)

Wrong way to write a constructor:

public final class MyImmutable {
private final int[] myArray;
public MyImmutable(int[] anArray) {
this.myArray = anArray; // wrong
}
public String toString() {
StringBuffer sb = new StringBuffer("Numbers are: ");
for (int i = 0; i < myArray.length; i++) {
sb.append(myArray[i] + " ");
}
return sb.toString();
}
}
// the caller could change the array after calling the
constructor.
int[] array = {1,2};
MyImmutable myImmutableRef = new MyImmutable(array) ;
System.out.println("Before constructing " + myImmutableRef);
array[1] = 5; // change (i.e. mutate) the element
System.out.println("After constructing " + myImmutableRef);
Out put:
Before constructing Numbers are: 1 2
Right way is to copy the array before assigning in the constructor.
public final class MyImmutable {
private final int[] myArray;
public MyImmutable(int[] anArray) {
this.myArray = anArray.clone(); // defensive copy
}
public String toString() {
StringBuffer sb = new StringBuffer("Numbers are: ");
for (int i = 0; i < myArray.length; i++) {
sb.append(myArray[i] + " ");
}
return sb.toString();
}
}
// the caller cannot change the array after calling the constructor.
int[] array = {1,2};
MyImmutable myImmutableRef = new MyImmutable(array) ;
System.out.println("Before constructing " + myImmutableRef);
array[1] = 5; // change (i.e. mutate) the element
System.out.println("After constructing " + myImmutableRef);
Out put:
Before constructing Numbers are: 1 2
After constructing Numbers are: 1 5
As you can see in the output that the ?MyImmutable? object
has been mutated. This is because the object reference gets

After constructing Numbers are: 1 2
As you can see in the output that the ?MyImmutable? object has not
been mutated.

Wrong way to write an accessor. A caller could get the array
reference and then change the contents:
public int[] getArray() {
return myArray;
}
Right way to write an accessor by cloning.
public int[] getAray() {
return (int[]) myArray.clone();
}

Concept : Beware of using the clone() method on a collection like a Map, List, Set etc because they are not only difficult
to implement but also the default behavior of an object?s clone() method automatically
yields a shallow copy. You have to deep copy the mutable objects referenced by your immutable class.
section for deep vs. shallow cloning and for why you will be modifying the original object if you do not
deep copy.

Abstract class concept in Java

Concept :
we know object of abstract class can not be created. but when we create an obj
of subclass of abstract class then the constructer of super class must be run and since constucter run obj must be created then how can we say obj of abst class can not be created.

Explanation:

Regarding the Abstract Class problem, it's not that an object of an abstract class is never created. By saying that an object of an abstract classes can't be created we mean that they can't be created explicitly and independently. That means you can't have any code creating them independently.

But, as you have mentioned that while creating a subclass object the object of superclass is always created first and abstract classes are also no exceptions in this case. Otherwise you can't access the accessible members of an abstract superclass in an object of any of its subclasses. All right?

You might have noticed that any code trying to instantiate an abstract class explicitly throws a compile-time error, which means the compiler checks the corresponding classes for every direct instantiation and reports errors whenever it finds any of them being anything other than a concrete class. The error may be thrown if it's an abstract class or an interface or something of that sort. Right?

The moral is that the objects of abstract classes are certainly created (otherwise the whole concept of superclass-subclass object creation would go awry), but only implicitly :-)

What I understand is that this check is only at the compiler level, so what'll happen if somebody manages to temper the bytecodes somehow with the addition of direct instantiation code of an abstract class without disturbing the allowed bytecodes format (otherwise the Verifier component of Linker would throw an error)? I'm not sure if that's possible at all. The Verifier is quite conservative in nature and I believe it should be able to recognize even a slight bytecode tempering.

Why wait(), notify() and notifyAll() methods have been defined in the Object class?

Java concurrency model uses locks to implement mutually exclusive access to objects in a multi-threaded environment and locks are associated with every object in Java (of type 'Object'), not only with Threads.

wait, notify/notifyAll methods are used by threads to communicate with each other while trying to access a common object. Putting it differently, objects become a medium via which threads communicate with each other. For example: suppose there is a 'telephone' object, which at one point of time can be used by only one thread. Like every other object in Java, 'telephone' object would also have an intrinsic lock (monitor) associated with it which at one point of time can be acquired by only one thread. Suppose the 'telephone' object requires activation before it can be used and suppose only a few admin threads can activate the 'telephone' object.

As soon as a thread needs access to the 'telephone' object, it checks if the lock on that 'telephone' object is available or not, if yes, it acquires that and checks if the 'telephone' is active or not. If yes, it starts using it otherwise it calls 'wait()' on the telephone object which effectively releases the monitor of the 'telephone' object (eventually to be acquired by one of the admin threads for its activation) and puts the requester thread into the wait-set of the 'telephone' object. The requester thread goes into WAITING state. The way every object in Java has an intrinsic lock associated with it, it has an intrinsic wait-set associated with it as well.

Every other non-admin requester thread goes through the same process as discussed above till one of the admin threads acquire lock on the 'telephone' object and eventually activates it and subsequently calls 'notify()' or 'notifyAll()' on the 'telephone' object. 'notify()' will simply pick one of the threads from the wait-set of the 'telephone' object (which one will be picked is an implementation dependent stuff and Java Language specification doesn't enforce any restriction on which one to be picked) and the chosen thread will now get out of WAITING mode and start trying to acquire the monitor/lock of the 'telephone' object along with any other thread that might be vying to access the 'telephone' at that point of time.

The only difference between 'notify' and 'notifyAll' is that in case of the latter all the threads of the corresponding wait-set are picked and they all start trying to acquire the lock on the object (with any other incoming requester thread) at the same time.

Evidently you see that these three methods are essentially object-related and not thread-related and hence the designers of Java Language considered it wise to put them in the Object class instead of putting them into the Thread class. The usage of the 'object' (in our case 'telephone') is the particular object's prerogative and not that of the requester threads'. Putting these three methods in the Object class helps the objects owning/controlling their usage in a better way as in that case a thread needs to first acquire the lock on the object (kind of getting a license to use the object) and then calling either wait (in case the thread doesn't find the object in the state it would have wished it to be in and hence thought of waiting for some time to let the object become useful for it) or notify/notifyAll to alert other threads waiting on the object once it finishes using the object (of course in the case when the thread find the object useful in its current state).

Additionally, the communication among the interested threads becomes far too easier when the control is kept at the object's level - one common shared resource/medium and all interested threads communicating via it. Not that the communication won't be possible if these methods are kept in the Thread class, but the handling of the communication and usage of the objects in a multi-threaded environment will probably become more complex and less flexible in that case.

Use of Equals() method in ArrayList in C# | Importance of Equals() method in C# .NET

ArrayList contains method  in c#

Concept : Use of Equals()  method in C#

Look the below code and output

using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;

namespace ConsoleApplication1
{
    class employee
    {
        public string name;
        public string id;
        public employee(String name, String id)
        {
            this.name = name;
           
            this.id = id;
        }
      
    }
   
    class ArrayTest
    {
    static void Main()
        {
            ArrayList ar = new ArrayList();
           ar.Add("kumud");
           ar.Add("Raju");
           ar.Add("yugdeep");
      
          Console.WriteLine("Array Contain " + ar.Contains("kumud");
    }

    }
}


Output :
 
   Array Contain  True


Now again look the code below :

using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;

namespace ConsoleApplication1
{
    class employee
    {
        public string name;
        public string id;
        public employee(String name, String id)
        {
            this.name = name;
           
            this.id = id;
        }
   
    }
   
    class ArrayTest
    {
    static void Main()
        {
              ar.Add(new employee("sandeep","3"));
              ar.Add(new employee("yugdeep", "3"));
              ar.Add(new employee("kumud", "3"));
           
               Console.WriteLine("Array Contain " + ar.Contains(new employee("sandeep","3"));

        }

    }
}
 

Output :

Array Contain False

Concept :  In case of when we adding string object its come true but in case of adding employe and searching for that particular
           object it comes false , reason behind is that string by default override the object's Equal() method in such way that
          it compare two string and return true but in case of employee class object there is no equals() method override
          ArrayList contain method search the Equals() method in object .so in case of employee there is no Equals() method mechanism
          so it coming False

Now we override Equals() method


using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;

namespace ConsoleApplication1
{
    class employee
    {
        public string name;
        public string id;
        public employee(String name, String id)
        {
            this.name = name;
           
            this.id = id;
        }
        public override bool Equals(Object o)
        {
           
            employee e = (employee)o;
          return (e.name.Equals(this.name));
          
        }
      
    }
   
    class ArrayTest
    {
    static void Main()
        {
             ArrayList ar = new ArrayList();
           ar.Add(new employee("sandeep","3"));
             ar.Add(new employee("yugdeep", "3"));
             ar.Add(new employee("kumud", "3"));
      
              Console.WriteLine("Array Contain " + ar.Contains(new employee("sandeep","3"));    }

    }
}

Output :

Array Contain True

Multiple Scenario of try , catch and finally in exception handling in java

Following Below multiple scenario question related to try, catch and finally block in exception handling in java
Scenario #1: try throwing an exception; catch and finally both having return statements


public class TestFinally {

/**
* @param args
*/
public static void main(String[] args) {

System.out.println("Inside main method!");
int iReturned = new TestFinally().testMethod();
System.out.println("Returned value of i = " + iReturned);

}

public int testMethod(){

int i = 0;
try{
 System.out.println("Inside try block of testMethod!");
 i = 100/0;
 return i;
}catch(Exception e){
 System.out.println("Inside catch block of testMethod!");
 i = 200;
 return i;
}
finally{
 System.out.println("Inside finally block of testMethod!");
 i = 300;
 return i;
}
}
}


Output: a return (or any control transfer for that matter) in finally always rules!



Inside main method!
Inside try block of testMethod!
Inside catch block of testMethod!
Inside finally block of testMethod!
Returned value of i = 300


Scenarios #2: try having exception-free code and a return; catch and finally both have return




...
try{
System.out.println("Inside try block of testMethod!");
i = 100;
return i;
}catch(Exception e){
System.out.println("Inside catch block of testMethod!");
i = 200;
return i;
}
finally{
System.out.println("Inside finally block of testMethod!");
i = 300;
return i;
}
...


Output: did you get the first one right? This is a cakewalk then. With the same logic that any control transfer in finally always rules we can easily predict the output to be similar to that of Scenario #1 with the only difference that in this case the catch block won't be executed as no exception thrown... all right? Here is the output:



Inside main method!
Inside try block of testMethod!
Inside finally block of testMethod!
Returned value of i = 300


Scenario #3: try having exception; finally doesn't have a return



...
try{
System.out.println("Inside try block of testMethod!");
i = 100/0;
return i;
}catch(Exception e){
System.out.println("Inside catch block of testMethod!");
i = 200;
return i;
}
finally{
System.out.println("Inside finally block of testMethod!");
i = 300;
//return i;
}
...


Output: no return in finally means whatever executable return encountered on the way to finally will be executed once finally completes its execution, so the output would be:



Inside main method!
Inside try block of testMethod!
Inside catch block of testMethod!
Inside finally block of testMethod!
Returned value of i = 200


Scenario #4: try and catch both having exception; finally having a return



...
try{
System.out.println("Inside try block of testMethod!");
i = 100/0;
return i;
}catch(Exception e){
System.out.println("Inside catch block of testMethod!");
i = 200/0;
return i;
}
finally{
System.out.println("Inside finally block of testMethod!");
i = 300;
return i;
}
...


Output: control transfer in finally overrules the exceptions thrown in try/catch, hence the output would be:



Inside main method!
Inside try block of testMethod!
Inside catch block of testMethod!
Inside finally block of testMethod!
Returned value of i = 300


Scenario #5: try and catch both having exception; finally NOT having any return



...
try{
System.out.println("Inside try block of testMethod!");
i = 100/0;
return i;
}catch(Exception e){
System.out.println("Inside catch block of testMethod!");
i = 200/0;
return i;
}
finally{
System.out.println("Inside finally block of testMethod!");
i = 300;
//return i;
}
...


Output: since no return in finally, hence after the execution of the finally block the sheer need to have an executable return statement (which doesn't exist in this case as catch also has an exception) would throw the exception encountered right before the finally execution started, which would be the exception in catch block in our case...right? So, the output would be:



Exception in thread "main" java.lang.ArithmeticException: / by zero
 at TestFinally.testMethod(TestFinally.java:24)
 at TestFinally.main(TestFinally.java:10)
Inside main method!
Inside try block of testMethod!
Inside catch block of testMethod!
Inside finally block of testMethod!


Scenario #6: try, catch, and finally all three having exceptions



...
try{
System.out.println("Inside try block of testMethod!");
i = 100/0;
return i;
}catch(Exception e){
System.out.println("Inside catch block of testMethod!");
i = 200/0;
return i;
}
finally{
System.out.println("Inside finally block of testMethod!");
i = 300;
return i/0;
}
...


Output: evidently the exception would be thrown, but which one? The one which was encountered last i.e., the one encountered in the finally block. Output would be:



Inside main method!
Inside try block of testMethod!
Inside catch block of testMethod!
Inside finally block of testMethod!
Exception in thread "main" java.lang.ArithmeticException: / by zero
 at TestFinally.testMethod(TestFinally.java:30)
 at TestFinally.main(TestFinally.java:10)


Scenario #7: try and catch both fine; finally doesn't have any return



...
try{
System.out.println("Inside try block of testMethod!");
i = 100;
return i;
}catch(Exception e){
System.out.println("Inside catch block of testMethod!");
i = 200;
return i;
}
finally{
System.out.println("Inside finally block of testMethod!");
i = 300;
//return i;
}
...


Output: well... first thing first. If try is fine, do we need to even think about catch? A BIG No... right? Okay, so we have try and finally blocks to focus on. Let me first show you the output and then we would discuss if you have any doubts. Here is it:



Inside main method!
Inside try block of testMethod!
Inside finally block of testMethod!
Returned value of i = 100

Session tracking in Java application | session concept in java

Plainly because HTTP is a stateless protocol. That means a Web Server handling HTTP requests doesn't maintain contextual info about the client requests coming to it. Putting it differently, the Web Server doesn't have a built-in way to recognize whether the current request is coming from a new client or from a client which has been communicating with it for a while now. This happens because every HTTP request is treated as an altogether new request.


As we can easily imagine that such a behavior can cause so many problems - for example, if a user has logged into his Bank Account and after a successful login if he wishes to go to the Funds Transfer page then he would be required to login again as Funds Transfer would be a login-protected page and the Web Server doesn't have any built-in support for recognizing if the clinet requesting this page is the one who is alraedy logged in or if it's coming from a new client. This is just a simple example... we can easily imagine how difficult will it be to develop a Web-Application without maintaining contextual information about the clients.


What are the various ways of tracking Sessions?


There are three ways of tracking sessions. In other words, there are three ways of maintaining contextual information about clients as a session is nothing but a collection of various information about the particular client the session has been built and maintained for. Three ways of session tracking in servlets are:-

    Using Cookies - Cookies are stored at the client side (in the browser's cache) and they are used to maintain the current session. Every cookie object stores contextual information for that particular session and it's always associated with a unique Session ID, which is sent to the server on creation of the cookie. The server uses that Session ID to locate the cookie at the clinet machine and then it uses the contextual information stored in that cookie object for various purposes including client authentication, client authorization, retrieving/saving data which the client may require in subsequent steps, etc. A timeout period for the cookie objects can be set after which they will become expired. Cookies may be a security threat as the Session ID may be used to track the particular cookie and then to retrieve secure information from it. This is the reason why all the browsers provide options to either enable or disable cookies at the user's discretion. You can simply disable Cookies by updating your browser options.

    Using URL Rewriting - This approach of maintaining sessions requires an extra peice of data to be appended to each URL. This extra info is used to identify the session and the server associates this identifier with the data it has stored for that particular session. The advantage of this approach is that it works even in those cases where the user has disabled cookied for their browsers. In this approach nothing is actually stored at the client side and all the sessio tracking info travels via URLs back and forth. SO, you may obviously lose the session information (the session would have been invalid due to timeout) if you bookmark an URL first and then try to access that later on.

    Using Hidden Form Fields - This is another approach of maintaining session where the contextual data travels via hidden form fields (<INPUT TYPE="hidden" ...). There are two main disadvantages of this approach: One, one can easily see all the data (maybe some secret info) by looking at the HTML Source of the page and Two, this approach will probaly work only for dynamic web pages (how would we maintain different session with unique identifiers otherwise?).

Exception Concept in Java | how try , catch and finally block work in java during exception found

Exception Concept in java

Exception

    +--------+
                    | Object |
                    +--------+
                |
                |
                   +-----------+
           | Throwable |
                   +-----------+
                    /         \
           /           \
          +-------+          +-----------+
          | Error |          | Exception |
          +-------+          +-----------+
       /  |  \           / |        \
         \________/      \______/         \
                            +------------------+
    unchecked     checked    | RuntimeException |
                    +------------------+
                      /   |    |      \
                     \_________________/
                      
                       unchecked


Exception hadling using try, catch, finally


    try {
       // statements that might cause exceptions
       // possibly including function calls
    } catch ( exception-1 id-1 ) {
       // statements to handle this exception
    } catch ( exception-2 id-2 ) {
       // statements to handle this exception
    .
    .
    .
    } finally {
       // statements to execute every time this try block executes
    }

concept:

    Each catch clause specifies the type of one exception, and provides a name for it (similar to the way a function header specifies the type and name of a parameter). Java exceptions are objects, so the statements in a catch clause can refer to the thrown exception object using the specified name.

    The finally clause is optional.

    In general, there can be one or more catch clauses. If there is a finally clause, there can be zero catch clauses.


concept 1;


what will output :

package com.exception;
import java.util.ArrayList;
public class exceptionTest {
   
    public String getName() {
  
    try{
   
     return "kumud";
   
    }
    catch(Exception ex)
    {
    System.out.println("Finally Exception##  try in getName method");
       
    }
    finally
    {
        System.out.println("Finally Exception## finally in getName method");
        return "kumud5";
    }
   
   
    }
   
    public static void main(String [] args)
    {
        ArrayList ar= new ArrayList();
        exceptionTest exp= new exceptionTest();
        try
        {
            System.out.println("Exception is"+exp.getName());
           
               
        }
        catch(Exception ex)
        {
            System.out.println("Exception##"+ex);
           
        }
        finally
        {
            System.out.println("Finally Exception##");
        }
       
    }

}

Output:

Finally Exception## finally in getName method
Exception iskumud5
Finally Exception##

Exp:
    in try block there is return method as well as in finally block also . but output is return from finally block reason behind that finally will execute either
    exception is found or not in any any condition while return value is given in try or catch block.


concept 2:

In which case finally block will not executed

package com.exception;
import java.util.ArrayList;
public class exceptionTest {
   
    public String getName() {
 
    try{
   
        System.exit(0);
     return "kumud";
   
    }
    catch(Exception ex)
    {
    System.out.println("Finally Exception##  try in getName method");
       
    }
    finally
    {
        System.out.println("Finally Exception## finally in getName method");
        return "kumud5";
    }
   
   
    }
   
    public static void main(String [] args)
    {
        ArrayList ar= new ArrayList();
        exceptionTest exp= new exceptionTest();
        try
        {
            System.out.println("Main Try block");
            System.out.println("Exception is"+exp.getName());
           
               
        }
        catch(Exception ex)
        {
            System.out.println("Exception##"+ex);
           
        }
        finally
        {
            System.out.println("Finally Exception##");
        }
       
    }

}


Output:

Main Try block

Expl: if you written System.exit(0) in try block in only that condition finally block will not execute