• Menu
  • Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar

JavaBeat

Java Tutorial Blog

  • Java
    • Java 7
    • Java 8
    • Java EE
    • Servlets
  • Spring Framework
    • Spring Tutorials
    • Spring 4 Tutorials
    • Spring Boot
  • JSF Tutorials
  • Most Popular
    • Binary Search Tree Traversal
    • Spring Batch Tutorial
    • AngularJS + Spring MVC
    • Spring Data JPA Tutorial
    • Packaging and Deploying Node.js
  • About Us
    • Join Us (JBC)
  • Java
    • Java 7
    • Java 8
    • Java EE
    • Servlets
  • Spring Framework
    • Spring Tutorials
    • Spring 4 Tutorials
    • Spring Boot
  • JSF Tutorials
  • Most Popular
    • Binary Search Tree Traversal
    • Spring Batch Tutorial
    • AngularJS + Spring MVC
    • Spring Data JPA Tutorial
    • Packaging and Deploying Node.js
  • About Us
    • Join Us (JBC)

OCAJP – Static Methods and Fields

November 9, 2015 //  by Krishna Srinivasan//  Leave a Comment

I have published few posts about static keyword and static initializer as part of educating the core Java concepts. In this post I will explain the important points about static keyword with respect to preparing for the OCAJP certification exam.

The actual exam objective is “6.2 – Apply the static keyword to methods and fields” under the topic “Working with Methods and Encapsulation”. This exam objective is applicable for both OCAJP 7 and OCAJP 8. However, the exam objective talks about the static methods and static fields, you may be tested for using the static blocks as well in the exam.

I am going to write down all the facts and points that are required to know about the static keyword in Java. At the end of this post, you can try few sample mock exam questions for testing your knowledge on static keyword. Note that these questions replicate the real exam question patterns.OCAJP Static Methods and Fields

What is Static Keyword?

In Java, anything declared as static tells you one thing, the members are associated with class and not an instance / object of that class. The ideal situation when you require to declare static members are that the data has to be shared among all the instances of that class.
Look at the following example:

public class StaticExample {
	private static int i;
	private int j;
	public StaticExample(int j){
		this.j = j;
	}
	static {
		i = 100;
	}
	public static void main(String args[]) {
		StaticExample example1 = new StaticExample(10);
		StaticExample example2 = new StaticExample(20);
		StaticExample.i = 200;
		System.out.println(example1.j);
		System.out.println(example2.j);
		System.out.println(example1.i);
		System.out.println(example2.i);
	}
}

If you closely look at the above example:

  • Variable i is declared as static and shared among all the instances of the class StaticExample.
  • Variable j is declared as instance variable since this will be separate for each instance for the class.
  • When you run the above program, you will get the following output:
] 
10 
20 
200 
200 

With this simple explanation, we can conclude that static in other words it is a class lever declaration. So, it is utmost important to decide what to be exposed at the class level. In the next sections we will learn different way how we can initialize the static variables and methods in your class.

This tutorial going to drill down on the following three topics which are more important for the exam preparation. I would advise you to practice as much as possible to have clear understanding on different combination of usage. Most of the times exam questions test you the wrong statements and asks you to tell if the program will be compile or not.

  1. Static Methods
  2. Static Fields / Variables
  3. Static Initializers
  4. Static Imports

Static Methods

Static methods accessed at the class level and shared among all the instances of the class. Static methods are declared at class level and have the following characteristics:

  • Static methods can be accessed using the class name and not required to create the instance.
  • Though static methods can be accessed using the object reference, it is not recommended.
  • Static methods can be overloaded, but can not be overridden. That means, when you declare a static method in super class and sub class with same name, the sub class method name is not overridden. In-fact, super class method will be hidden and will not be inherited to the subclass.
  • Constructors can not be static.
  • Static methods can not access the instance variables, instance methods.

Look at the following example for using static methods:

public class StaticExample {
	public static void main(String args[]) {
		StaticMethods.method(10);
		StaticMethods.method(10.0);
		StaticMethodsSub.method(10.0);
		StaticMethods methods = new StaticMethodsSub();
		//Here the sub class method is not invoked
		methods.method(10);
	}
}
class StaticMethods{
	public static void method(int i){
		System.out.println("Static int method");
	}
	public static void method(double i){
		System.out.println("Static double method");
	}	
}
class StaticMethodsSub extends StaticMethods{
	public static void method(int i){
		System.out.println("Static int sub method");
	}
	public static void method(double i){
		System.out.println("Static double sub method");
	}	
}

Output for the above program will be:

Static int method
Static double method
Static double sub method
Static int method

The above example gives you the basic idea on how to use the static methods.

Here is the matrix for static member access restriction:

OCAJP Static Member Access Restriction

Static Fields / Variables

Static fields or variables are the one which are declared with static keyword at class level.

  • A static variable is shared by all the instances of a class.
  • A class can have multiple instances by using the new keyword. Every instance have its own instance variables. But, the static variables are shared by all the instances.
  • You have to be wise in using the static variables, since this value is shared with entire application which may cause undesirable result when used in the concurrent user environment.
  • If the variable is not defined as static, by default it is instance variable.

You can look at the other examples in this tutorial to understand how to use the static variables.

Static Initializers

Static initializers are the static blocks declared inside any Java class with the static keyword. This block gets executed at the class loading time. This block is used for initializing the static variables.

The following are the important features of the static blocks:

  1. Only static variables can be initialized inside static blocks. Instance variables are not allowed inside static blocks.
  2. Any number of static blocks can be defined, that will be executed in the order of definition.
  3. Static methods can be called from the static initializers.
  4. Static blocks are used for initializing the static or class level variables.
  5. Static initializers can not call instance methods or refer instance variables.

Look at the following example code for using static initializer:

package org;

public class StaticExample {	
	public static void main(String args[]) throws ClassNotFoundException{
		//Loading a class
		StaticInitializer.class.forName("org.StaticInitializer");
	}
}

class StaticInitializer{
	int i;
	static int j;
	static{
		//i = 10; - compiler error. Instance variable not allowed inside static initializer
		System.out.println("Block 1");
	}
	static{
		j = 20;// This is fine
		System.out.println("Block 2");
	}
	static{
		System.out.println(j);
		System.out.println("Block 3");
		staticmethod();// This is fine
		//instancemethod(); - compiler error. Instance method not allowed inside static initializer
	}	
	public static void staticmethod(){
		System.out.println("Static method");
	}
	public void instancemethod(){
		System.out.println("Instance method");		
	}
}

Output for the above program will be:

Block 1
Block 2
20
Block 3
Static method

Static Imports

Static imports are used for importing the static members from any class or interface. Static Imports is all about importing all the static entities – like static classes, static methods and static objects and directly accessing them in code. This is convenient since you are not required to know from where the variables are accessed. Once you use static imports, the variable name or method name can be used within that class. This featue has been added as part of the Java 5.0 Features.
Here is a simple exame for static import:

import static java.lang.Math.*;
import static java.lang.System.*;
public class StaticTest {
	public static void main(String[] args)
	{
		gc();
		out.println("Testing static object");
		out.println("max of 10 and 20 is " + max(10, 20));
	}
}

In the above example, static members are imported from the classes Math and System. Later on the class members are directly used without using the class name like System.gc(). I hope this helps you to understand the use of static imports in Java application.

OCAJP – Static Methods / Fields Mock Exam Questions

Here is the few sample mock exam questions using the static keyword. If you would like to try more questions, please buy our OCAJP certification kit.

1. Which of the following statements are true?

A. Static method can invoke a instance method
B. Static method can not invoke a instance method
C. Static variable can be accessed inside an instance method
D. Static variable can not be accessed inside an instance method
E. Static method can be overridden

2. What will be the output of the following program:

public class StaticExample {
	private static int j = 10;

	public static void method(int i) {
		i = 20;
	}

	public static void main(String args[]) {
		method(j);
		System.out.println(j);
	}
}

A. 20
B. 10
C. 30
D. No output
E. None of the above

3. Consider the following class:

class MockExam{
int i;
   public static void main(String[] args){
       // lot of code.
   }
}

Which of the following statements are correct:

A. By declaring i as static, main can access this.i
B. By declaring i as public, main can access this.i
C. By declaring i as protected, main can access this.i
D. main cannot access this.i.
E. By declaring i as private, main can access this.in

Correct Answers:

1. B, C
2. B

In case of primitives such an an int, it is the value of the primitive that is passed. For example, in this question, when you pass “i” to method, you are
actually passing the value 10 to the method, which is then assigned to method variable ‘i’. In the method, you assign 20 to ‘i’. However, this does not change the value contained in someInt. someInt still contains 10. Therefore, 10 is printed. Theoretically, java supports Pass by Value for everything ( i.e. primitives as well as Objects). Primitives are always passed by value. Object “references” are passed by value. So it looks like the object is passed by
reference but actually it is the value of the reference that is passed.

3. D

i is a instance variable, hence this can not be accessed inside a static method. Remember that rule that, static methods and variables are loaded at class loading time. They can not directly access any of the instance variables for that class. Also note that “this” keyword can not be used inside a static method.

Category: OCAJP

About Krishna Srinivasan

He is Founder and Chief Editor of JavaBeat. He has more than 8+ years of experience on developing Web applications. He writes about Spring, DOJO, JSF, Hibernate and many other emerging technologies in this blog.

Previous Post: «New Features in Spring Boot 1.4 Spring and JSON Example
Next Post: OCAJP – Pass by Value or Pass by Reference »

Reader Interactions

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Primary Sidebar

Follow Us

  • Facebook
  • Pinterest

FEATURED TUTORIALS

New Features in Spring Boot 1.4

Difference Between @RequestParam and @PathVariable in Spring MVC

What is new in Java 6.0 Collections API?

The Java 6.0 Compiler API

Introductiion to Jakarta Struts

What’s new in Struts 2.0? – Struts 2.0 Framework

JavaBeat

Copyright © by JavaBeat · All rights reserved
Privacy Policy | Contact