JavaBeat

  • Home
  • 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)
  • Privacy
  • Contact Us

OCAJP – Pass by Value or Pass by Reference

November 12, 2015 by Krishna Srinivasan Leave a Comment

One of the most debated topic on Java is whether the method arguments are pass by reference or pass by value. In this tutorial, I would like to explain the same old concept with respect to the OCAJP certification. In Java, everything is pass by value. Here is the exam objective for OCAJP 7 and OCAJP 8:

6.6 – Determine the effect upon object references and primitive values when they are passed into methods that change the values

If you are here, then probably you would have heard many other saying that in Java primitive types are pass by value and objects are pass by  references. Java is a “pass-by-value” language. This means that a copy of the variable is created and the method receives that copy. Assignments made in the method will not affect the caller. In this post, I would explain that in very detail. At the end of this post, I have few mock exam questions using the same topic.

Here I will be giving you a simple example to understand what is Pass by Value and what is Pass by Reference.

Java Pass By Value

What is Pass by Reference?

Let’s say if I want to share useful information from a web page to my colleagues. If I am providing the URL to my colleagues to refer that web page, I am passing them a reference to check the web page. If I make any changes to that page, that is always reflected to that URL whenever they open for the reference.

This is known as pass by reference in the programming world. In the technical terms, passing by reference means the called methods parameter will be the same as the callers passed argument (not the value, but the identity and the variable itself)

What is Pass by Value?

In contrast, if I am providing them a print out copy of that web page for the reference, that is completely disconnected copy of that web page where the changes updated in the page (original copy) is not at all reflected to the copy. If they don’t want that copy, they can destroy that safely and it will not impact the original source.

This is known as pass by value in programming world. In the technical terms, pass by value means the called methods parameter will be a copy of the callers’ passed argument. The value will be the same, but the identity – the variable – is different. In Java, everything is strictly pass by value without any question.

In the subsequent sections I am going to explain the pass by value in Java for primitive types and object references with simple examples.

Primitive Types

Understanding primitive type is very simple and straight forward anyone who have the basic knowledge of Java. Let’s look at the following example:

[code lang=”java”]
public class Application {
public static void main(String args[]) {
int x = 10;
int y = 20;
swap(x,y);
System.out.println(x);
System.out.println(y);

}
public static void swap(int i, int j){
int temp = i;
i = j;
j = temp;
}
}
[/code]

When you run the above example program, the values are not swapped and values of x and y are the same after executing the swap method. What happened behind the scene is that, copy of the x and y are passed to the method and stored in new address. Hence any changes inside that method will not affect the original values.

Object References

Most of the confusion around object references are lack of understanding on object manipulation and assignment. When you pass object reference to a method, the entire copy of the reference is passed to the method. That means, content of the reference (address / location of the actual object) is sent to the method and any changes to the object will reflect in the original object.

Look at the following example:

[code lang=”java”]
public class ObjectReferenceMockExam {
public static void main(String args[]) {
StringBuilder builder = new StringBuilder("Wonderful");
changeStr(builder);
System.out.println(builder.toString());
}
public static void changeStr(StringBuilder builder){
builder.append(" World");
StringBuilder builder2 = new StringBuilder("Amazing World");
builder = builder2;
}
}
[/code]

When you run the above program, you will get the output of “Wonderful World” and not “Amazing World”. This proves that object references are pass by value.

When you create a original object StringBuilder builder= new StringBuilder("Wonderful")
Here the reference “builder” would contain the memory address say “14345”. This is just the memory address (or say remote control for accessing the StringBuilder object content). When you pass to a method, the value (memory address) 14345 is actually passed. This itself not an object content, it is just a handler for modifying the object content. Then when you create a new object inside the method with reference “builder2”, say this may contain another memory location “16785”. The replacement just swap the memory location and not the content of the object.

I hope that this is good enough to understand this concept for the exam. If you are looking for further explanation, let’s look at our friend Joe has explained nicely in his post here. In the next section we will go through few mock exam.

OCAJP Mock Exam

1. Consider the following code:

[code lang=”java”]
public class Main {
public static void main(String args[]) {
int x = 10;
int y = 20;
swap(x,y);
System.out.println(x);
System.out.println(y);

}
public static void swap(int i, int j){
int temp = i;
i = j;
j = temp;
}
}
[/code]

If you run the above program, what will be the output?

A. 10 20
B. 20 10
C. 20 20
D. 10 10

2. Consider the following code:

[code lang=”java”]
public class Main {
private static String str = "Hello";
public static void main(String args[]) {
changeStr(str);
System.out.println(str);
}
public static void changeStr(String str){
str = "Hello World";
}
}
[/code]

What will be the output of the above program?

A. Hello World
B. Hello
C. Compiler Error
D. Runtime exception

3. Consider the following code:

[code lang=”java”]
public class ObjectReferenceMockExam {
public static void main(String args[]) {
StringBuilder builder = new StringBuilder("Wonderful");
changeStr(builder);
System.out.println(builder.toString());
}
public static void changeStr(StringBuilder builder){
builder.append("World");
StringBuilder builder2 = builder;
builder2.append(" for everyone");
}
}
[/code]

What will be the output of the above program?

A. Wonderful
B. Wonderful World
C. Wonderful World for everyone
D. Compiler Error

Correct Answers:

1. A

In Java, primitives are pass by value. When you call the methods, any assignment inside the method are local to that method and it doesnot affect the actual variable x and y.

2. B

The object references are pass by value, hence any assignment inside the method will not change the original value in the caller method.

An example:
Object o1 = new Object(); //Let us say, the object is stored at memory location 15000. Since o1 actually stores the address of the memory location where the object is stored, it contains 15000. Now, when you call someMethod(o1); the value 15000 is passed to the method. Inside the method someMethod(): someMethod( Object localVar) { localVar now contains 15000, which means it also points to the same memory location where the object is stored. Therefore, when you call a method on localVar, it will be executed on the same object. However, when you change the value of localVar itself, for example if you do localVar=null,
it then it starts pointing to a different memory location. But the original variable o1 still contains 15000 so it still points to the same object.

3. C

When you pass object reference in a method arguments, you actually passing the copy of that reference. That means the memory location where that actual object is stored. Any changes to the value stored in that reference would affect the original object. In the above example, though you are assigning to a local variable “builder2”, you are trying to modify the content of that reference since it modified the StringBuilder object itself.

Filed Under: OCAJP

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:

[code lang=”java”]
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);
}
}
[/code]

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:

[code lang=”java”]]
10
20
200
200
[/code]

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:

[code lang=”java”]
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");
}
}
[/code]

Output for the above program will be:

[code]
Static int method
Static double method
Static double sub method
Static int method
[/code]

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:

[code lang=”java”]
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");
}
}
[/code]

Output for the above program will be:

[code]
Block 1
Block 2
20
Block 3
Static method
[/code]

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:

[code lang=”java”]
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));
}
}
[/code]

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:

[code lang=”java”]
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);
}
}
[/code]

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

3. Consider the following class:

[code lang=”java”]
class MockExam{
int i;
public static void main(String[] args){
// lot of code.
}
}
[/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.

Filed Under: OCAJP

OCAJP – StringBuilder API

November 2, 2015 by Krishna Srinivasan Leave a Comment

StringBuilder is a alternative to the existing StringBuffer class in Java. StringBuilder class is first introduced in Java 5.0. The key difference between StringBuilder and StringBuffer is that, StringBuilder is not synchronous where as StringBuffer is synchronous. This makes the StringBuilder class offers better performance then the StringBuffer.

ocajp-exam

The new OCAJP exam added a separate objective for String Builder class. The objective of the exam is:

Manipulate data using the StringBuilder class and its methods

If you look at the above objective, there is no clear indication of what are the methods that will be asked in the exam. That means there is likely chance that they may test you any methods that are defines in the StringBuilder API. In this tutorial, I will list down the methods and which are most important for the OCAJP exam. At the end of this tutorial, I have also provided few sample StringBuilder mock exam questions for your practice.

OCAJP Javabeat Sales Promotion

StringBuilder Constructor

There are four variant of constructors defined in the StringBuilder class.

  1. StringBuilder()
  2. StringBuilder(CharSequence seq)
  3. StringBuilder(int capacity)
  4. StringBuilder(String str)

StringBuilder Methods

There are fifty methods that are defines in the StringBuilder class. Most of the methods are overloaded and used for the similar operations with varying datatypes. You are not required to remember all the methods for the OCAJP exam, but required to understand few important methods and how to use them in your application. I have provided few examples at the end of this tutorial.

  1. StringBuilder append(boolean b)
  2. StringBuilder append(char c)
  3. StringBuilder append(char[] str)
  4. StringBuilder append(char[] str, int offset, int len)
  5. StringBuilder append(CharSequence s)
  6. StringBuilder append(CharSequence s, int start, int end)
  7. StringBuilder append(double d)
  8. StringBuilder append(float f)
  9. StringBuilder append(int i)
  10. StringBuilder append(long lng)
  11. StringBuilder append(Object obj)
  12. StringBuilder append(String str)
  13. StringBuilder append(StringBuffer sb)
  14. StringBuilder appendCodePoint(int codePoint)
  15. int capacity()
  16. char charAt(int index)
  17. int codePointAt(int index)
  18. int codePointBefore(int index)
  19. int codePointCount(int beginIndex, int endIndex)
  20. StringBuilder delete(int start, int end)
  21. StringBuilder deleteCharAt(int index)
  22. void ensureCapacity(int minimumCapacity)
  23. void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)
  24. int indexOf(String str)
  25. int indexOf(String str, int fromIndex)
  26. StringBuilder insert(int offset, boolean b)
  27. StringBuilder insert(int offset, char c)
  28. StringBuilder insert(int offset, char[] str)
  29. StringBuilder insert(int index, char[] str, int offset, int len)
  30. StringBuilder insert(int dstOffset, CharSequence s)
  31. StringBuilder insert(int dstOffset, CharSequence s, int start, int end)
  32. StringBuilder insert(int offset, double d)
  33. StringBuilder insert(int offset, float f)
  34. StringBuilder insert(int offset, int i)
  35. StringBuilder insert(int offset, long l)
  36. StringBuilder insert(int offset, Object obj)
  37. StringBuilder insert(int offset, String str)
  38. int lastIndexOf(String str)
  39. int lastIndexOf(String str, int fromIndex)
  40. int length()
  41. int offsetByCodePoints(int index, int codePointOffset)
  42. StringBuilder replace(int start, int end, String str)
  43. StringBuilder reverse()
  44. void setCharAt(int index, char ch)
  45. void setLength(int newLength)
  46. CharSequence subSequence(int start, int end)
  47. String substring(int start)
  48. String substring(int start, int end)
  49. String toString()
  50. void trimToSize()

StringBuilder Example

Here is very simple example for using StringBuilder class. I have used only very few important methods defined in the API, but it is easy to learn and use any of the methods by yourself. One of the important point tested in the real exam is that extending StringBuilder class. It is a final class, so developer can not extend this class.

StringBuilder Example Program:

[code lang=”java”]
package net.javabeat;
public class StringBuilderExample{
public static void main(String[] args) {
StringBuilder stringBuilder = new StringBuilder(50);
stringBuilder.append("This");
stringBuilder.append(" ");
stringBuilder.append("is");
stringBuilder.append(" ");
stringBuilder.append("a sample");
stringBuilder.append(" ");
stringBuilder.append("string");
stringBuilder.append("!!");
System.out.println("StringBuilder String : " + stringBuilder.toString());
System.out.println("StringBuilder Capacity : " + stringBuilder.capacity());
System.out.println("StringBuilder Length : " + stringBuilder.length());
System.out.println("StringBuilder Substring : " + stringBuilder.substring(3));
System.out.println("StringBuilder Char At : " + stringBuilder.charAt(5));
System.out.println("StringBuilder Capacity : " + stringBuilder.indexOf("sample"));
System.out.println("StringBuilder Replace : " + stringBuilder.replace(2, 6, "replaced"));
}
}
[/code]

Here is the output:

[code]
StringBuilder String : This is a sample string!!
StringBuilder Capacity : 50
StringBuilder Length : 25
StringBuilder Substring : s is a sample string!!
StringBuilder Char At : i
StringBuilder Replace : Threplaceds a sample string!!
[/code]

StringBuilder Mock Exam Questions

1. What will be the output of the following program?

[code lang=”java”]
public class JavaBeatStringBuilderMock1{
public static void main(String args[]) {
String s = "hello";
StringBuilder sb = new StringBuilder("hello");
sb.reverse();
s.reverse();
if (s == sb.toString())
System.out.println("Equal");
else
System.out.println("Not Equal");
}
}
[/code]

  • A. It will print ‘Not Equal’.
  • B. Runtime error.
  • C. Compilation error.
  • D. It will print ‘Equal’.
  • E. None of the above.

Correct Answer : (C) is the correct answer.

There is no reverse() method in String class

2. Consider the following code:

[code lang=”java”]
public class JavaBeatStringBuilderMock2 extends StringBuilder{
JavaBeatStringBuilderMock2(){ super(); }
}
[/code]

The above code will not compile.

  • A. True
  • B. False

Correct Answer: (A) is the correct answer.

This will not compile because StringBuilder class is a final class and final classes cannot be extended. Hence the compiler will not allow this program to successfully compile. You would see the questions like this in real exam and so you should remember that StringBuffer and StringBuilder are also final. All Primitive wrappers are also final (i.e. Boolean, Integer, Byte etc).
java.lang.System is also final.

3. How can you initialize a StringBuilder to have a capacity of at least 50 characters?

  • A. StringBuilder sb = new StringBuilder(50);
  • B. StringBuilder sb = StringBuilder.getInstance(50);
  • C. StringBuilder sb = new StringBuilder();sb.setCapacity(50);
  • D. StringBuilder sb = new StringBuilder();sb.ensureCapacity(50);

Correct Answer: (A) and (D) is the correct answer.

StringBuilder(50) is one of the constructor takes capacity as the parameter and initializes the StringBuilder’s capacity. Also you can change the capacity of StringBuilder using the setCapacity(int) method.

Filed Under: OCAJP

Follow Us

  • Facebook
  • Pinterest

As a participant in the Amazon Services LLC Associates Program, this site may earn from qualifying purchases. We may also earn commissions on purchases from other retail websites.

JavaBeat

FEATURED TUTORIALS

Answered: Using Java to Convert Int to String

What is new in Java 6.0 Collections API?

The Java 6.0 Compiler API

Copyright © by JavaBeat · All rights reserved