0% found this document useful (0 votes)
14 views4 pages

Understanding Java Static Concepts

The document explains the concepts of static variables, methods, and blocks in Java, highlighting their characteristics and usage. It also introduces the Vector class, detailing its properties, constructors, and methods, along with examples demonstrating their functionality. Additionally, it includes an assignment section with questions related to the discussed topics.

Uploaded by

Chaya Anu
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views4 pages

Understanding Java Static Concepts

The document explains the concepts of static variables, methods, and blocks in Java, highlighting their characteristics and usage. It also introduces the Vector class, detailing its properties, constructors, and methods, along with examples demonstrating their functionality. Additionally, it includes an assignment section with questions related to the discussed topics.

Uploaded by

Chaya Anu
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Java Static Method, Variable and Block

What is Static Variable in Java?

Static variable in Java is variable which belongs to the class and initialized only once at the start of
the execution. It is a variable which belongs to the class and not to object(instance). A single copy
to be shared by all instances of the class

A static variable can be accessed directly by the class name and doesn’t need any object

Syntax :

<class-name>.<variable-name>

What is Static Method in Java?

Static method in Java is a method which belongs to the class and not to the object. A static method
can access only static data. It cannot access non-static data (instance variables).

 A static method can call only other static methods and can not call a non-static method
from it.
 A static method can be accessed directly by the class name and doesn’t need any object
 A static method cannot refer to "this" or "super" keywords in anyway

Syntax :

<class-name>.<method-name>

Note: main method is static, since it must be accessible for an application to run, before any
instantiation takes place.

Example

class Student {
int a; //initialized to zero
static int b; //initialized to zero only when class is loaded not for each object created.
Student(){
//Constructor incrementing static variable b
b++;
}
public void showData(){
[Link]("Value of a = "+a);
[Link]("Value of b = "+b);
}
}
public class Demo{
public static void main(String args[]){
Student s1 = new Student();
[Link]();
Student s2 = new Student();
[Link]();
}
}

What is Static Block in Java?


The static block is a block of statement inside a Java class that will be executed when a class is
first loaded into the JVM. A static block helps to initialize the static data members, just like
constructors help to initialize instance members.

class Test{
static {
//Code goes here
}
}

Example
public class Demo {
static int a=80;
static int b=100;
static {
a = 10;
b = 20;
}
public static void main(String args[]) {
[Link]("Value of a = " + a);
[Link]("Value of b = " + b);
}
}

Vector Class
Vector implements a dynamic array. It is similar to ArrayList, but with two differences:
 Vector is synchronized.
 Vector contains many legacy methods that are not part of the collections framework.
Vector proves to be very useful if you don't know the size of the array in advance or you just need
one that can change sizes over the lifetime of a program.

Below given are the list of constructors provided by the vector class
 Vector vec = new Vector();
o It creates an empty Vector with the default initial capacity of 10.
o It means the Vector will be re-sized when the 11th elements needs to be inserted
into the Vector. Note: By default vector doubles its size. i.e. In this case the Vector
size would remain 10 till 10 insertions and once we try to insert the 11th element It
would become 20 (double of default capacity 10).
 Vector object= new Vector(int initialCapacity)
o Vector vec = new Vector(3);
o It will create a Vector of initial capacity of 3.
 Vector object= new vector(int initialcapacity, capacityIncrement)
o Vector vec= new Vector(4, 6)
o Here we have provided two arguments. The initial capacity is 4 and
capacityIncrement is 6. It means upon insertion of 5th element the size would be 10
(4+6) and on 11th insertion it would be 16(10+6).
Methods in Vector Class
1. void addElement(Object element): It inserts the element at the end of the Vector.
2. int capacity(): This method returns the current capacity of the vector.
3. int size(): It returns the current size of the vector.
4. void setSize(int size): It changes the existing size with the specified size.
5. boolean contains(Object element): This method checks whether the specified element is
present in the Vector. If the element is been found it returns true else false.
6. boolean containsAll(Collection c): It returns true if all the elements of collection c are
present in the Vector.
7. Object elementAt(int index): It returns the element present at the specified location in
Vector.
8. Object firstElement(): It is used for getting the first element of the vector.
9. Object lastElement(): Returns the last element of the array.
10. Object get(int index): Returns the element at the specified index.
11. boolean isEmpty(): This method returns true if Vector doesn’t have any element.
12. boolean removeElement(Object element): Removes the specifed element from vector.
13. boolean removeAll(Collection c): It Removes all those elements from vector which are
present in the Collection c.
14. void setElementAt(Object element, int index): It updates the element of specifed index with
the given element.

Example
import [Link].*;
public class VectorExample {
public static void main(String args[]) {
/* Vector of initial capacity(size) of 2 */
Vector<String> vec = new Vector<String>(2);

/* Adding elements to a vector*/


[Link]("Apple");
[Link]("Orange");
[Link]("Mango");
[Link]("Fig");

/* check size and capacityIncrement*/


[Link]("Size is: "+[Link]());
[Link]("Default capacity increment is: "+[Link]());
[Link]("fruit1");
[Link]("fruit2");
[Link]("fruit3");
/*size and capacityIncrement after two insertions*/
[Link]("Size after addition: "+[Link]());
[Link]("Capacity after increment is: "+[Link]());
/*Display Vector elements*/
Enumeration en = [Link]();
[Link]("\nElements are:");
while([Link]())
[Link]([Link]() + " ");
}
}

Assignment
1. What is the difference between static and instance variables? Explain with an example
2. Why static variables are not available to static methods?
3. What are static methods? Explain the importance of static method with an example.
4. Write a program to demonstrate vector class.
5. Differentiate between array and vector.
6. Differentiate between size and capacity in vector class. Explain with a program.

Common questions

Powered by AI

Vectors provide thread safety through synchronization, which is an advantage in multi-threaded applications. They also support legacy methods not present in ArrayList. However, this synchronization can introduce overhead, making vectors slower than ArrayLists in single-threaded scenarios. Additionally, ArrayLists are part of the more modern collections framework, offering more streamlined methods and interactions .

Arrays in Java have a fixed size and are not synchronized, meaning multiple threads can access them simultaneously without safety mechanisms. In contrast, vectors are dynamically resizable and synchronized, providing thread safety by ensuring that only one thread can access a vector at a time, making them suitable for concurrent modifications .

In Java's Vector class, 'size' refers to the number of elements currently stored in the vector, while 'capacity' refers to the amount of allocated space for elements, which can be greater than the size. For instance, when a vector is instantiated with a capacity of 2 and three elements are added, the size becomes 3, but the capacity doubles to accommodate additional elements .

Vectors in Java are dynamically resized by the JVM. When the number of elements exceeds the current capacity, the vector's capacity is doubled by default to accommodate new elements. For example, if a vector with an initial capacity of 10 reaches 11 elements, it will be resized to 20, unless a specific increment is defined during initialization .

The Vector class includes methods such as `addElement(Object element)` to append elements, `capacity()` to check total capacity, `size()` to check current element count, `removeElement(Object element)` to delete a specified element, and `setElementAt(Object element, int index)` to update an element at a given index. These methods facilitate manipulating the elements stored in a vector efficiently .

Static variables in Java are class-level variables, meaning they are associated with the class, not any individual instance. This structure ensures that there is only one copy of the static variable, shared and accessed by all instances of the class. This allows for consistent state or data across different instances but can lead to issues if not managed carefully, as changes by one instance affect others .

A static block in a Java class is used to initialize static variables. It is a block of code executed when the class is loaded into the JVM before the main method or any object creation. Its main purpose is to provide some common initialization of static variables that are shared among instances .

Static methods in Java are limited to accessing only static data; they cannot access instance variables. Furthermore, static methods can only call other static methods and cannot invoke non-static methods from within them. They also cannot refer to "this" or "super" keywords, which further limits their interaction with instance-specific data and behavior .

The main method in Java is declared as static to ensure it can be called by the JVM without creating an instance of the class. This is crucial as it serves as the entry point for program execution, and having it static allows the application to start without any objects being instantiated .

Static variables in Java belong to the class and are shared among all instances, whereas instance variables belong to the object and each instance has its own copy. For example, consider a class `Student` with an instance variable `int a` and a static variable `static int b`. When we create instances of `Student`, `a` will be distinct for each instance, but `b` will be incremented with each new instance, reflecting the shared nature of static variables .

You might also like