Friday 15 December 2017

Difference: Array vs Vector in java

Array and Vector differs based on the following parameters:

Basic:

Array in java is an object that contains data of homogeneous (similar) type.
example, int a[]={5,6,4,55}; //this array can only store int data type

Vector can store heterogeneous data types, if restriction is not put using generics concept. See the example below:

package string;

import java.util.Iterator;
import java.util.Vector;

public class splitDemo {

      public static void main(String[] args) {

            Vector v = new Vector();
            v.add(1);    //integer
            v.addElement("xyz");  //string
            v.add('s');  //char

            Iterator itr = v.iterator();
            while(itr.hasNext()){
                  System.out.println(itr.next());
            }
      }
}

OUTPUT:
1
xyz

In above example, you can see we have stored int, String and char objects in vector. 

Note: To make vector store homogeneous data type do the following:

Vector<String> v = new Vector<String>();

This will only allow storage of String object in vector.

Family:

Array does not belongs to Collection family. It is a primitive data type.

Vector implements List interface which is a part of collection hierarchy. Thus vector is a part of collection family.

Size:

Array needs to be assigned with the fixed size during initialization thus making it static in nature.

Vector resizes itself dynamically as per the need. Thus it is dynamic in nature.

Synchronized:

Array is non-synchronized in java.

Vector is synchronized in java.

Traversal:

Array can be traversed using for loop or enhanced for loop. It cannot use iterator or enumeration interface like vector or arraylist.

Vector can be traversed using iterator or enumeration interface

Declare/Instantiate/Initialization:

Array
Integer array
int a[]={5,6,4,55};

String array
String a[]={"Ajay","vijay","Rajesh","Mukesh"};

Similarly you can do for other data types like double, float, char, etc

Vector
Vector<String> vec=new Vector<String>();  //create vector
vec.add("Ajay");      //add element to vector
vec.add("vijay");




You may also like to read:

Wednesday 13 December 2017

Difference: ArrayList vs CopyOnWriteArrayList in java

ArrayList and CopyOnWriteArrayList in java differ based on following parameters:

1. Inclusion in java

Arraylist was added in Java 1.2 version.

CopyOnWriteArrayList was added in Java 1.5 or Java 5.


2. Thread-safety

Arraylist in java is not synchronized thus is not at all thread safe.

CopyOnWriteArrayList is synchronized in nature. Thus it is thread safe and for the same reason only one thread can access the resources in this class at a time.


3. Performance

As arraylist is non-synchronized so it is better performance wise as multiple threads can access the resources of arraylist at the same time simultaneously.

Being synchronized means only one thread can have access to CopyOnWriteArrayList resources thus impacting its performance speed.


4. ConcurrentModificationException

Arraylist throws ConcurrentModificationException.

CopyOnWriteArrayList doesnot throw ConcurrentModificationException.


5. Fail fast or fail safe

 Arraylist's  iterator and list iterator are fail fast in nature.

CopyOnWriteArrayList iterator are fail safe in nature.



You may also like to read:


Tuesday 12 December 2017

Which collection classes are synchronized or thread-safe?

Collection framework provides lots of classes to work with. Among them some are synchronized while other are non synchronized.

Recently one of my colleague was asked the same question in Deloitte interview. So you could also be asked the same in your next interview.

Lets come to the point.


All the synchronized collection classes are stated below:


1. Vector


Vector implements grow able array of objects. The elements in vector can be accessed using integer index just as we do in array.

Vector is synchronized so it should be used if thread-safety is concern of the developer. 
Due to synchronized nature, it does not allow multiple threads to access and modify its resources concurrently. If one thread has access to the vector then other thread wanting to access and operate on it must wait for its turn until the vector is released by the thread in action.

On other hand, this synchronized nature affects Vector’s performanceSo ArrayList is preferred over Vector if performance is to be considering factor.

To read about Vector in details. please follow the link Vector in java 

2. Hashtable

Hashtable extends Dictionary class and implements Map interface. Hashtable stores elements in key-value pair.

Hashtable is synchronized in nature.
Due to synchronized nature, it does not allow multiple threads to access and modify itself concurrently. 


Note: Both vector and hashtable are legacy classes and are not recommended for use.

3. CopyOnWriteArrayList

CopyOnWriteArrayList is a thread-safe variant of ArrayList which was included in java version 1.5 or java 5.
Here thread-safe indicates that this collection class is synchronized.



Advantage of synchronization:
If you don't want any resource to be shared simultaneously by multiple threads then mark the resource Synchronized. This makes sure that only one thread can access the resource at one instance and others has to wait for their turn in the queue.


Disadvantage of synchronization:
Because of being synchronized in nature these classes are slow in terms of performance. Reason is simple. Because of synchronization only single thread is able to access the class resource at a time. Other thread has to wait in queue till the first thread completes its task on the resource. Thus multitasking is not possible which in turn impacts speed.



You may also like to read:

Sunday 19 November 2017

Practice Programs on String in java

Given below are all the possible programs that will help you get a good grasp on String concept in java. (Update in Progress)

Note: Follow all the business rules where applicable.

  1. Write a method that takes a String and calculates the total number of characters in the String. Business Rules :- 
    Rule 1 : If any special characters is present in the string , print -1. Rule 2 : String should contain only alphanumeric values and white spaces.
  2. Write a method which takes a string as input and returns true if its a valid IP address and false if not a valid IP.
    Business Rules :-                                                                                                                          Rule 1 : IP address should be like 10.10.23.56
    Rule 2 : All the digit must be between 0 to 255 except for the first digit which is 1 to 255.
    Rule 3 : Total 4 numbers would be there separated by only dots.
    Rule 4 : All the fields must be either dot or digits(no white space or symbols or alphabets allowed).
  3. Write a method that accepts a string and returns the total number of vowels in that string.
  4. Write a method that takes a string array and returns the count of palindromes in the string array.
  5. Write a method that will accept a string and will return the string after removing all characters other than alphabets.
  6. Write a method which accepts a string(ex. This is a pen and is used to write) and returns a list<int> where the index of all occurrences of "is" is stored. 
  7. Write a method that will take two strings and will return an integer which is the frequency of first string in second string .
    Input1:- is
    Input2:-He is a good boy,but his brother is not.
    Output:- 2
  8. Write a method that will take a string and will remove duplicate characters keeping only the first occurrence.
    Input:- Kolkataaaaa   Output:- Kolat
  9. Write a method that will take a string and will return an int array that contains the length of the largest and smallest words.
  10. Write a method that will take a string which will be the password for a very secured account.
    Business Rules:-The string should be maximum 10 characters long,minimum 8 characters long, should have a minimum 1 special character, 1 uppercase character , 1 lowercase character and 1 digit. The string should not start with digit or special symbols. No space is allowed. If all conditions satisfy return true and otherwise false.

Thursday 2 November 2017

Can we keep more than one class in a single java source file?

We can have more than one class in a single java source file but with certain restriction.

Among multiple classes that you create in a single source file, only one can be public. Find an example given below,


package basic;

public class MultiplePublic {

      public static void main(String[] args) {
            //By java radar
            System.out.println("Executing main method");
            AnotherMultiplePublic amp = new AnotherMultiplePublic();
            amp.sampleMethod();
      }

}

class AnotherMultiplePublic {

      public void sampleMethod(){
            System.out.println("Print sample method");
      }

}

OUTPUT:
Executing main method

Print sample method


As shown above, write both classes in same source file with MultiplePublic class being public. As stated above if only one class is declared public then the code will run fine. So in this case the code will be executed without any glitches and produce output as stated under output header.

 Second Scenario:

Now, we will try to assign public access modifier to more than one class. Say two classes will have public modifier.

In this scenario, look at the below given screen-shot, to find out the result:

java radar examples
Multiple public class in same source file


See the red under line below AnotherMultiplePublic class in the screenshot above. Place the mouse cursor above it and you will see the error message:

                'The public type AnotherMultiplePublic must be defined in its own file'


Conclusion: That means in the same source file one cannot have more than one public class. 
Though there is no problem if you want to keep more than one class in same source file and you restrict the application of public modifier to only one class as we did in our first scenario.


Note for Readers: Please share your valuable thoughts on this post's question to help others.


You may also like to read:

Saturday 28 October 2017

Pascal triangle in java

Program: Write a program to enter number of rows and create a Pascal Triangle.
Input: 5
Output:
     1               row=1
    1 1              row=2
   1 2 1             row=3
  1 3 3 1            row=4
 1 4 6 4 1           row=5



Source FilePascalTriangle.java

package triangle;

public class PascalTriangle
{
      public static void main(String args[])
      {
            int rows, i, k, number=1, j;
            rows = 5;  //change number of rows as per need

            for(i=0;i<rows;i++)
            {
                  for(k=rows; k>i; k--)
                  {
                        System.out.print(" ");
                  }
                  number = 1;
                  for(j=0;j<=i;j++)
                  {
                        System.out.print(number+ " ");
                        number = number * (i - j) / (j + 1);
                  }
                  System.out.println();
            }
      }
}



OUTPUT:

     1
    1 1
   1 2 1
  1 3 3 1
 1 4 6 4 1




 You may also like to read about:

Friday 20 October 2017

Calculator Application in java

Project Detail: Create calculator application which accepts two numbers from user and perform addition, subtraction, multiplication and division on given numbers.
                                     --------------------------  *  -----------------------------


SourceCalculation.java

package calculator;

public class Calculation {
      int result;
      //Method for addition
      public int add(int num1, int num2){
            result = num1+num2;
            return result;
      }
      //Method for subtraction
      public int substract(int num1, int num2){
            result = num1-num2;
            return result;
      }
      //Method for multiplication
      public int multiply(int num1, int num2){
            result = num1*num2;
            return result;
      }
      //Method for division
      public float divide(int num1, int num2){
            result = num1/num2;
            return result;
      }
     
}

SourceCalculatorVO.java

package calculator;

public class CalculatorVO {
      private int firstNumber;
      private int secondNumber;
     
      public int getFirstNumber() {
            return firstNumber;
      }
      public void setFirstNumber(int firstNumber) {
            this.firstNumber = firstNumber;
      }
      public int getSecondNumber() {
            return secondNumber;
      }
      public void setSecondNumber(int secondNumber) {
            this.secondNumber = secondNumber;
      }
     

}

SourceMainClass.java

package calculator;

public class MainClass {

      public static void main(String[] args) {
           
            CalculatorVO calVO = new CalculatorVO();
            //Input can be taken from user
            calVO.setFirstNumber(100);
            calVO.setSecondNumber(11);
           
            Calculation cal = new Calculation();
           
            int addResult = cal.add(calVO.getFirstNumber(), calVO.getSecondNumber());
            System.out.println("Addition Result ="+addResult);
           
            int subResult = cal.substract(calVO.getFirstNumber(), calVO.getSecondNumber());
            System.out.println("Subtraction Result ="+subResult);
           
            int mulResult = cal.multiply(calVO.getFirstNumber(), calVO.getSecondNumber());
            System.out.println("Multiplication Result ="+mulResult);
           
            float divResult = cal.divide(calVO.getFirstNumber(), calVO.getSecondNumber());
            System.out.println("Division Result ="+divResult);

      }

}


OUTPUT:
Addition Result =111
Subtraction Result =89
Multiplication Result =1100
Division Result =9.0

-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
If you are looking for a reference book on java then we recommend you to go for → Java The Complete Reference
Click on the image link below to get it now.