Hub Of Geekz

  • Home
  • About Me
  • Contact Us
  • Home
  • Languages
    • C++
    • Java
    • Perl
    • Prolog
    • Bootstrap
  • Database
    • SQL
    • PL/SQL
  • Study
    • Java
      • Java Collection
      • Java Concurrency
      • Java Interview Questions
      • Java Networking
    • Number System
  • Kavita
  • Entertainment
    • Hinglish Cafe
    • Videos
    • Jokes
  • Windows Tricks
  • How To

Thursday, 12 March 2015

ArrayList Methods in Java

 Earthcare Foundation NGO     10:14     Collection, Java     No comments   

In this pots i will explain some methods of ArrayList.
1)clone:This method is used to make a exact copy of list.This method returns object so we need to add casting to it.
Suppose list is an ArrayList and we have added some elements to it.

ArrayList<String> list=new ArrayList<String>();

list.add("First List");

list.add(1, "I");

list.add(0, "Abhishek");

So apply clone method on it
ArrayList<String> list1=new ArrayList<String>();
list1=(ArrayList<String>) list.clone();//to get the exact copy

2)clear():This method is used to clear the list means all the data present in the list will be lost and list will become empty.
list.clear();

3)contains():This method accepts object as argument to chech whether it is present in the list or not.It returns true if element is present else returns false.
boolean exist=list.contains("Abhishek");

4)containsAll():This method accepts collection as its argument and checks all the elements with the current collection to check whether every element in both of these collections are same or not.If every element is present then it returns true else returns false.
exist=list.containsAll(list1);
Note:The presence of elements of passed list is searched.
for example in above statement if list contains all the elements which are present in list1 then it will return true.It will not check the presence of all elements of list in list1.
The whole concept explained above is explained in the following program:

package examples;

import java.util.ArrayList;

public class ArrayListOther {

public static void main(String[] args) {


ArrayList<String> list=new ArrayList<String>();
System.out.println("This is an example of add method in ArrayList");
list.add("First List");
System.out.println("After adding elements list is "+list );
list.add(1, "I");
System.out.println("After adding elements list is "+list );
list.add(0, "Abhishek");
System.out.println("After adding elements list is "+list );

ArrayList<String> list1=new ArrayList<String>();
list1=(ArrayList<String>) list.clone();
System.out.println("The cloned list of list is "+list1);

boolean exist=list.contains("Abhishek");
System.out.println("List contains element Abhishek: "+exist);
list.add("hello");
exist=list.containsAll(list1);
System.out.println("List contains all elements of other list : "+exist);

list.clear();
System.out.println("After removing all the elements using clear method list is"+list);

}

}

Output:
This is an example of add method in ArrayList
After adding elements list is [First List]
After adding elements list is [First List, I]
After adding elements list is [Abhishek, First List, I]
The cloned list of list is [Abhishek, First List, I]
List contains element Abhishek: true
List contains all elements of other list : true
After removing all the elements using clear method list is[]

In the above example you can see that after cloning list and list1 both contains same elements and after that i have added another element in list and after that i have called list.containsAll(list1) and it is returning true since elements if list1 will be checked in list.
So till now i have explained some methods of ArrayList class.Hope you are able to understand.If there is any problem then you can ask me by comment or email.
Thanks
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

ArrayList Methods in Java

 Unknown     10:09     Collection, Java     No comments   

In this method i will explain some methods of ArrayList which are used frequently.

1)ensureCapacity():This method is used to increase the size of the ArrayList,if necessary to ensure that it can hold at least the number of elements specified by the minimum capacity argument.
   
    list.ensureCapacity(30);
By above statement the minimum capacity of the list will be 30.

2)get(index):This method is used to get the element at the specified index.If index<0 or index>sizeOfList then IndexOutOfBoundsException will occur.

    list.get(2);
This will return element present at index 2.Again if we will put any index which is not in list then exception will occur:
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 5, Size: 4
    at java.util.ArrayList.rangeCheck(Unknown Source)
    at java.util.ArrayList.get(Unknown Source)
    at examples.ArrayListMethods.main(ArrayListMethods.java:23)


3)hashCode():
This method returns the hash code of the given list.
    list.hashCode();
    output:1351734790


4)indexOf(object):This method searches for the specified object and returns the index of first occurence of that object.If object is not present in the list then it returns -1.
    list.indexOf("Brown");   
This will return 3.

5)isEmpty():This method is used to test whether the list is empty or not.If the list is empty it will return true.
    list.isEmpty();

Program Code:
package examples;

import java.util.ArrayList;

public class ArrayListMethods {

    public static void main(String[] args) {


        ArrayList<String> list=new ArrayList<String>();
        System.out.println("This is an example of add method in ArrayList");
        list.add("First List");
        list.add("Orange");
        list.add("Red");
        list.add("Brown");
        System.out.println("After adding elements list is "+list );
   
        list.ensureCapacity(30);
       
        String str=list.get(3);
        System.out.println("Element at index 3 is: "+str);

        System.out.println(list.hashCode());
        int loc=list.indexOf("Brown");
        if(loc>=0){
            System.out.println("The element Brown is present at location "+loc);
        }
        else{
            System.out.println("The element Brown is not present in the list");
        }
       
        System.out.println("List is Empty: "+list.isEmpty());
    }

}

Output:
This is an example of add method in ArrayList
After adding elements list is [First List, Orange, Red, Brown]
Element at index 3 is: Brown
1351734790
The element Brown is present at location 3
List is Empty: false

So above is all about some methods of ArrayList which can be used for convenience.If there is any query ask me via comment or email.
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

Tuesday, 10 March 2015

ArrayList in Java

 Earthcare Foundation NGO     10:14     Collection, Java     No comments   

Java API provides several predefined data structure which are also known as collections in Java.ArrayList is a collection which we can use conveniently in place of array because when we are using array there is a problem that array size cannot be changed automatically at runtime i.e. if we are using an array and it became full then it will throw an exception instead of increasing its size.This problem can be solved by using ArrayList.There are also other benefits as there are lot of inbuilt methods which are convenient to use for adding element,deleting an element,searching an element etc.List can also contain null and duplicate elements.So lets get some knowledge of methods of ArrayList.
1)add(element):This method is used to add an element at the last position of ArrayList.This is an efficient method to add an element in ArrayList.
2)add(index,element):This method is used to add an element at the specified position in the ArrayList.This method is not so much efficient as the elements after that position have to shift one position.
for ex list=2,3,6,7
list.add(2,56); //add 56 at 2nd position
 then list=2,3,56,6,7
So whenever possible use add(element) method for efficeincy.
3)addAll(Collection<?extends E>):This method is used to append all the elements of other collection at the end of the list.
4)addAll(index,Collection<?extends E>):This method is used to append all elements of other collection at specific position in the list.

Program Code:
package examples;

import java.util.ArrayList;

public class ArrayListExample {

public static void main(String[] args) {

ArrayList<String> list=new ArrayList<String>();
System.out.println("This is an example of add method in ArrayList");
list.add("First List");
System.out.println("After adding elements list is "+list );
list.add(1, "I");
System.out.println("After adding elements list is "+list );
list.add(0, "Abhishek");
System.out.println("After adding elements list is "+list );
System.out.println("List can also contain duplicate elements");
list.add("I");
System.out.println("After adding elements list is "+list );

ArrayList<String> list1=new ArrayList<String>();
list1.add("Second List");
System.out.println("After adding elements list is "+list1 );
list1.addAll(list);
System.out.println("We can append other list to this list");
System.out.println("After appending other list, elements of list are "+list1 );

ArrayList<String> list2=new ArrayList<String>();
list2.add("Third List");
list2.add("Hello");
System.out.println("We can also insert other list at specific location");
list2.addAll(1, list1);
System.out.println("After appending other list, elements of list are "+list2 );

}

}

Output:
This is an example of add method in ArrayList
After adding elements list is [First List]
After adding elements list is [First List, I]
After adding elements list is [Abhishek, First List, I]
List can also contain duplicate elements
After adding elements list is [Abhishek, First List, I, I]
After adding elements list is [Second List]
We can append other list to this list
After appending other list, elements of list are [Second List, Abhishek, First List, I, I]
We can also insert other list at specific location
After appending other list, elements of list are [Third List, Second List, Abhishek, First List, I, I, Hello]
So above are some methods to add elements in the ArrayList.
Hope everything is clear,if not then ask me via comments or email
Thanks.
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

Arrays Class in Java

 Earthcare Foundation NGO     10:11     Java     No comments   

In this post i will explain about the Arrays class in Java which is inbuilt and we can use many predefined methods on this Array class which makes our problem simple.
1)sort():This method is used to sort the array elements.
2)equal():This is a method for comparing two arrays.
3)binarySearch():This is a method to find an element using binary search.This method returns the location of the element.
4)fill():This is a method to assign specified value to each element of specified  array.
Arrays.fill(arr,7);
where arr is an array of type integer,then it will replace all the elements in the array with 7.
5)arrayCopy():This is a method by which we can copy elements of one array to another.

Program Code:

package examples;

import java.util.Arrays;

public class ArraysClass {

public static void main(String[] args) {

int[] arr={2,5,3,6,8,65,23,45};
System.out.println("Elements of arr are ");
for(int element:arr){
System.out.println(element);
}
Arrays.sort(arr);
System.out.println("Sorted array is ");
for(int element:arr){
System.out.println(element);
}
int[] arr1=new int[6];
Arrays.fill(arr1, 7);
System.out.println("Elements of array after insertion  are ");
for(int element:arr1){
System.out.println(element);
}
int [] arr2={1,4,6,8,9};
System.out.println("Elements of arr1 are ");
for(int element:arr2){
System.out.println(element);
}
System.arraycopy(arr2, 0, arr1, 0, arr2.length);
System.out.println("Elements of arr1 after copy ");
for(int element:arr1){
System.out.println(element);
}
int loc=Arrays.binarySearch(arr2, 3);
if(loc>=0){
System.out.println("Element 3 is found in arr2 at location "+(loc+1));
}else{
System.out.println("Element 3 is not present in the arr2");
}
loc=Arrays.binarySearch(arr2, 4);
if(loc>=0){
System.out.println("Element 4 is found in arr2 at location "+(loc+1));
}else{
System.out.println("Element 4 is not present in the arr2");
}
boolean equ=Arrays.equals(arr, arr1);
if(equ){
System.out.println("Both array arr and arr1 are same");
}else{
System.out.println("Arrays arr and arr1 are not same");
}
}

}

Output:
Elements of arr are
2
5
3
6
8
65
23
45
Sorted array is
2
3
5
6
8
23
45
65
Elements of array after insertion  are
7
7
7
7
7
7
Elements of arr1 are
1
4
6
8
9
Elements of arr1 after copy
1
4
6
8
9
7
Element 3 is not present in the arr2
Element 4 is found in arr2 at location 2
Arrays arr and arr1 are not same

One thing to note here is that in method,
System.arraycopy(srcArray,startIndex,dstArray,startIndex,length);
if we provide length which is larger than srcArray then we will get an ArrayIndexOutOfBoundsException.
So above is all about Arrays class in Java.If there is any query let me know by comments or by email.
Thanks.
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

Java Interview Question-Variable length arguments to method

 Earthcare Foundation NGO     10:07     Java, Java Interview Questions     No comments   

Do you know that we can pass a variable length argument lists in the method.This can be done by passing the datatype followed by an ellipsis(...) and then variable name.The ellipsis indicates that method can receive variable length of arguments of specific type.We can also use method overloading on this method.The ellipsis passed in the method is taken as the array of specific type.So we can apply the array operations on this variable length parameter list.
For Example:

package examples;

public class VarArguments {

public static int sum(int ... numbers){
int res=0;
for(int number:numbers){
res=res+number;
}
return res;
}

public static void main(String[] args) {
int a=12;
int b=13;
int c=14;
int d=15;
System.out.println("a="+a+"\nb="+b+"\nc="+c+"\nd="+d);
System.out.println("Sum of a and b is "+sum(a,b));
System.out.println("Sum of a,b and c is "+sum(a,b,c));
System.out.println("Sum of a,b,c and d is "+sum(a,b,c,d));

}

}
Output:
a=12
b=13
c=14
d=15
Sum of a and b is 25
Sum of a,b and c is 39
Sum of a,b,c and d is 54

In the above example i have created a method which takes a variable number of arguments.Then i have applied a for loop to get the sum of elements.In main method i have supplied 2 arguments then 3 arguments and then 4 arguments to get the sum of those numbers.
So tgis is a great thing we can apply in our programs where we don't know how much arguments have to be passed in the method which makes our problem simple.
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

Monday, 9 March 2015

Array in Java

 Unknown     09:47     Java     No comments   

An array is a group of variables of same types containing some values.In Java Arrays are objects so they are considered reference types.The elements of array can be primitive or reference types.If we want to access any element in the array, then we use the position number of that element in the array.This position number in the array is called the index or subscript of the element.
Declaration of array:
datatype[] arrayReference;   //preferred way
or
datatype arrayReference[];

For ex:   int[] arrayOfInts;
is an array which is pointing to the elements of type integer.
Defining array:
arrayReference=new datatype[arraySize];

For ex: arrayOfInts=new int[10];

We can combine the above two steps in one step as
 int[] arrayOfInts=new int[10];

So in this way we can define an array.
If the size of array is 10 then its index would be 0-9 i.e. 0 to (size-1).
For ex int[] arr=new int[5];
then its elements would be arr[0],arr[1],arr[2],arr[3],arr[4] and the array reference will be pointing to the first element that is arr[0].
The index of array can be a expression but it can't be negative.
For ex arr[a+b]=23;

How to pass an array to method?
Suppose we have an array int[] arr=new int[10];
and method declaration getArrayMethod(int[] a);
then the method call        getArrayMethod(arr);
passes the reference of array arr to method getArrayMethod().
The argument to a method can be passed as an entire array or only a single element.When a argument to the method is entire array, then it receives a copy of reference and when argument to method is an individual array element of primitive type then the method receives the value of that element.
Pass by value and pass by reference:
There are two ways to pass the arguments to the method:
1)Pass by value
2)Pass by reference

When an argument is passed by value,a copy of argument's value is passed to the called method.So if we made any changes to that argument then that changes will only be valid inside that called function since method contains the copy of that argument.So that updated value will not affect the original value of that argument outside that method.
If argument is passed by reference then called method can access the argument's value in caller directly and can modify its value.Pass by reference is used to improves the performance because in this case we don't have any need to copy the data,we only have to copy the reference of that data.
In Java,we cannot choose to pass by value or pass by reference, all arguments are passed by value.If argument is primitive type then copy of that primitive value is passed and if argument is reference type then copy of that reference is passed.
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

Data Hierarchy in Operating Systems

 Unknown     09:44     Java     No comments   

Data an important concept everywhere.Nothing exist without data.If we need to compute anything we need data.If we need to determine any result,we need data.So data is base for all the computing and we this world of computing can't exist without data.
What is data in terms of computers, at the lowest level data is stored in the computers in the form of bits which can be either 0 or 1.So anything which is stored in computers is in the form of bits.For ex 0111000111000 is a data which is stored in computers.
So we can explaining the hierarchy of data in computers:
1)Bits:It is the smallest data item in the computers.

2)Characters:It is very tedious to work with bits for a human,since we cannot remember all data in the form of 0 or 1.Instead of this we are able to remember patterns in the form of characters.So the decimal digits(0-9),letters(a-z and A-Z) and special symbols (@,#,$,%,^,&,*,? etc) are known as characters.Java uses Unicode characters that are composed of 1,2 or 4 bytes.THese Unicode characters contains characters from many languages of world.

3)Fields:Just as characters are composed of bits,fields are composed of characters or bytes.So a field can contain a sequence of characters or bytes that can convey some meaning.For ex "Abhishek" is a field which is representing a name,"23" is a field which can be the age of anyone or a number.

4)Records
:Records can contain several fields i.e. when we group some records then it can compose a record.For Ex suppose we have some fields such as name,age,address etc and if wegroup together all these fields then it can be called a record.
So i have a question, can you identify record in Java?
Yes you are right,Classes in Java can be called as records.In above example record can be called as Person which is having fields such as name,age, address etc.

5)Files:
Some records can be combined to form a file.But more generally a file can contain arbitrary formats such as in some operating systems,a file is viewed as a sequence of bytes.So we can say files as organization of data into records is a specific view whic is created by application programmer.

6)Database:
In early days data was organized in the form of files, but as soon as the size of the files increases,we felt a need for something which can organize those files.So there is database.A database is a collection of data organized for easy access to data and for its manipulation.Now a days most popular database is relational database in which data is stored in form of tables.

7)Big Data:Now a days the amount of data produced is very huge and it is growing quickly.So to deal this enormous size of data,we have Big Data applications which deals with this huge amount of data.This data hierarchy is new and it is evolving at a great rate.
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

Thursday, 5 March 2015

Synchronization in Java

 Unknown     07:14     Concurrency, Java, Thread     No comments   

What is thread synchronization?
Suppose we have a multi-threaded application i.e. our application have more than one thread.Since we know multiple threads can share an object.Suppose we have an object which is shared by multiple threads because of this unexpected results can occur unless access to shared object is managed properly.For example:We have two threads which are going to update that shared object what will happen if one thread is updating that object and another thread is in process of updating that thread and another thread is going to read that data.Then what will happen,Which data the third thread will read?
Old data or first thread's data or second thread's data.
What will happen if third thread was supposed to read that old data but has read the new data either of first or second thread.So data is not correct.
The above problem can be solved by giving only one thread access to shared thread on time exclusive basis and at the same time if another thread wants to access that shared object then it has to wait until the thread with that exclusive lock has finished its operation.So this  operation is called as Thread Synchronization.By synchronizing threads in this manner ensures that only one thread is using that shared object and other threads are waiting to access that object.This is called as Mutual Exclusion.
We need to synchronize only mutable data, there is no need to synchronize the immutable data.

How to perform synchronization?
Now we know basics of synchronization.Our next question is how to perform this synchronization in Java.
In Java,There is a concept of monitor.Each object has a monitor and a monitor lock(also known as intrinsic lock). This monitor is used to perform synchronization.Monitor ensures that the monitor lock is held by at most one thread at a time and this ensures mutual exclusion.If a thread want to access a shared object then it has to acquire the lock so that thread will be allowed to access that objects data.Other threads attempting to perform the operation which requires the same lock will be blocked until the first thread releases the lock and after that other thread can acquire the lock to perform operation.
The code which will be executed by the threads will be put in the synchronized block.The code inside the synchronized block is said to be guarded by the monitor lock.So thread has to acquire the lock in order to use that guarded block.

Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg
Newer Posts Older Posts Home

Ad


Jobsmag.inIndian Education BlogThingsGuide

Subscribe

Do you want fresh and hot updates about us? Then subscribe to our Feeds.

Total Pageviews

Popular Posts

  • Write a program in PL/SQL to print the factorial of a number.
    In this post I will explain how to get the factorial of any given number. For that first you need to know what is the procedure to find ...
  • To find the GCD of two numbers in PROLOG.
    gcd(X,Y):-X=Y,write('GCD of two numbers is '),write(X); X=0,write('GCD of two numbers is '),write(Y); Y=0,write('G...
  • Write a PL/SQL code to get the Fibonacci Sequence
    First, I will explain what is Fibonacci Sequence and how to get this series. So, Fibonacci Sequence is a series of numbers 0,1,1,2,3,5,8,1...

Label

All Articles Best Resources Blogging Boost Traffic Bootstrap C Plus Plus Collection Comedy Comedy Posts Comedy Videos Concurrency creative commons website Education Employee Entertainment Fibonacci Sequence free images GirlFriend Hinglish Cafe How To Image Websites Inspirational Java Java Interview Questions Java Networking Kavita Sangrah Life Lock Sreen Love Number System Patterns Perl Picture PL/SQL Plastic Engineering Programming Prolog public domain SEO Servlet Short Story Shortcut Keys Social Media Social Services SQL SuVichar Thread Traffic True Events Ultimate Guide Windows Tricks Windows8.1 WordPress

Blog Archive

  • ▼  2020 (43)
    • ▼  September (41)
      • कुल 33 प्रकार के देवी देवता हैँ हिँदू धर्म मे
      • तीन ऋण -
      • चारपीठ
      • चार युगों के नाम
      • चार धाम
      • चार वेद
      • चार आश्रम
      • चार अंतःकरण
      • पञ्च गव्य
      • पञ्च देव
      • पंच तत्त्व
      • छह दर्शन
      • दो पक्षो के नाम
      • सप्त ऋषियों के नाम
      • सप्त पुरी के नाम
      • आठ योग
      • आठ लक्ष्मी
      • नव दुर्गा
      • दस दिशाओ के नाम
      • प्रभु विष्णु के ११ अवतार
      • सनातन संस्कृति के अनुसार बारह महीनों के नाम
      • बारह राशियों के नाम
      • श्री मद्-भगवत गीता"के बारे में महत्वपूर्ण जानकारी
      • धृतराष्ट्र और गांधारी के सौ पुत्र….. कौरव कहलाए ज...
      • पांच पांडवो की माताओ के नाम
      • पांच पांडव के नाम
      • Important Toll Free numbers in India
      • बारह शिव ज्योतिर्लिंग
      • Full form of technical words
      • Full form of abbreviations
      • Trigonometry formulas
      • Chemistry symbols
      • भारतीय संविधान - प्रश्न उत्तर
      • General knowledge question answer
      • Physics formula and relations
      • General knowledge question answer
      • फल/फुल/सब्जी आदि का वैज्ञानिक नाम
      • Chemistry के इम्पोर्टेन्ट सिम्बल्स
      • गणित के महत्वपूर्ण चिन्ह,,
      • पंद्रह तिथियाँ
      • Phrasal Verbs :
    • ►  August (2)
  • ►  2019 (1)
    • ►  July (1)
  • ►  2018 (9)
    • ►  September (7)
    • ►  July (1)
    • ►  May (1)
  • ►  2017 (8)
    • ►  June (3)
    • ►  May (3)
    • ►  March (1)
    • ►  January (1)
  • ►  2016 (2)
    • ►  September (1)
    • ►  January (1)
  • ►  2015 (91)
    • ►  December (1)
    • ►  November (1)
    • ►  October (6)
    • ►  May (10)
    • ►  March (20)
    • ►  February (50)
    • ►  January (3)
  • ►  2014 (339)
    • ►  December (1)
    • ►  October (55)
    • ►  September (58)
    • ►  August (94)
    • ►  July (64)
    • ►  June (67)
  • ►  2013 (34)
    • ►  August (5)
    • ►  April (29)
  • ►  2012 (20)
    • ►  November (1)
    • ►  October (15)
    • ►  September (4)

Author

  • Earthcare Foundation NGO
  • Kavita house
  • Unknown
  • Unknown

Info

Copyright © Hub Of Geekz | Powered by Blogger
Design by Hardeep Asrani | Blogger Theme by NewBloggerThemes.com | Distributed By Gooyaabi Templates