Java – Arbitrary Number of Arguments – the 3 dots

In some Java codes, you might come across, 3 dots like this: It is known as Varargs.

foo(String... values)

With varargs, a method, function or even constructor can be passed in an arbitrary number of arguments. Varargs are useful, when developers are not sure how many of a particular type of argument will be passed to the method.

Sample Implementation of Varargs

A varargs parameter is treated as an array within the defining member. So in the body of foo we could write for example:

public void foo(String... values) {
    String[] someStrings = values;
}

And now, we can call the methods with an arbitrary number of arguments, either like this

foo();

or like this

foo("a", "b", "c");

Source Codes

https://github.com/wuchiachong/java-varargs

References

Varargs

Java – What is Functional Interface

To create a functional interface

You may come across codes like this ()->{ System.out.println("Hello World"); }, a bracket first then follow by an arrow, if you have ever written JavaScript before, it is known as arrow function in JavaScript. In Java land this is known as functional interface.

To create a functional interface, all you have to do is create an interface with a SAM(Single Abstract Method), and then put a @FunctionalInterface annotation to the interface.

SimpleFuncInterface.java
@FunctionalInterface
public interface SimpleFuncInterface {
  public void execute();
}

To implement Functional Interface

SimpleFunInterfaceTest.java
/*
* Implementing the interface by creating an
* anonymous inner class versus using 
* lambda expression.
*/
public class SimpleFunInterfaceTest {
  public static void main(String[] args) {
    carryOutWork(new SimpleFuncInterface() {
      @Override
      public void execute() {
        System.out.println("Do work in SimpleFun impl...");
      }
    });
    carryOutWork(() -> System.out.println("Do work in lambda exp impl..."));
  }
  public static void carryOutWork(SimpleFuncInterface sfi){
    sfi.execute();
  }
}
Output:
Do work in SimpleFun impl...
Do work in lambda exp impl...

JavaScript – Checking against NaN

NaN stands for Not-a-Number in JavaScript. Sometimes when writing JavaScript codes, you might need to check whether a variable is a number or not.

For example, you declare a variable foo and assign NaN to the variable, i.e let foo = NaN;. Then you might think checking can be done this way:

let foo = NaN;
foo === NaN; // false
Number.NaN === foo ; // false

However, the expectation is otherwise.

isNaN(foo);  // true
Number.isNaN(foo);  // true

To avoid confusion, please use isNaN() to check whether a variable is Not-a-Number or not.

References:
NaN

Java – Pass-by-Value II

Pass By Value

Continue from the previous post. We are going to validate and verify whether this statement is true or not, which is Java is always pass-by-value.

Business Objects as Arguments

Student.java
public class Student {
	private String name;
	
	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}
}

package com.cloudberry.com.my.passbyvalue;

import static org.junit.Assert.assertEquals;

import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;

/**
 * Unit test for simple App.
 */
public class PassByValueTest {

	@Test
	public void testPassByValueBusinessObject() {
		Student student = new Student();
		
		System.out.println("Value of name before Student modification = " + student.getName());
		assertEquals(student.getName(), null);
		
		modifyStudent(student);
	    
		System.out.println("Value of name after Student modification = " + student.getName());
		assertEquals(student.getName(), "Alex");
	}
	
	@Ignore
	private void modifyStudent(Student student) {
		student.setName("Daniel");
	}
}
Output

Value of name before Student modification = null
Value of name after Student modification = Daniel

The student object is created inside the heap space, and a reference for it is defined inside the stack. When calling modifyStudent(), a copy of the reference is created inside the stack and passed to the method.

The copy of the reference and the original reference prior to modifyStudent() are pointing to the same object, thus any modifications to the object attributes inside the method are reflected in the original reference.

Collection Arguments

package com.cloudberry.com.my.passbyvalue;

import static org.junit.Assert.assertEquals;

import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;

/**
 * Unit test for simple App.
 */
public class PassByValueTest {
	
        @Test
	public void testPassByValueCollection() {
		 List<Integer> lstNums = new ArrayList<Integer>();
		 lstNums.add(777);
		 
		 System.out.println("Size of list before List modification = " + lstNums.size());
		 
		 modifyCollection(lstNums);
		 
		 System.out.println("Size of list after List modification = " + lstNums.size());
	}
	
	@Ignore
	private void modifyCollection(List<Integer> lstParam) {
		lstParam.add(333);
	}
}
Output
Size of list before List modification = 1
Size of list after List modification = 2

When defining an ArrayList or any collection in Java, a reference is created inside the stack that points to multiple objects inside the heap memory. When calling modifyList(), a copy of the reference is created and passed to the method.

The actual object data is pointed and referenced by two references, and any change done by one reference is reflected in the other.

Inside the method, we called lstParam.add(333), which actually tries to create a new Integer object in the heap memory and link it to the existing list of objects. Hence the original list reference is modified, because of both the two references are pointing to the same object in memory.

Wrapper Class Arguments

package com.cloudberry.com.my.passbyvalue;

import static org.junit.Assert.assertEquals;

import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;

/**
 * Unit test for simple App.
 */
public class PassByValueTest {
        
        @Test 
	public void testPassByValueWrapper() {
		Integer x = new Integer(222);
	    Integer y = new Integer(888);
	    
	    assertEquals(x.intValue(), 222);
	    assertEquals(y.intValue(),888);
	    
	    System.out.print("Values of x & y before wrapper modification: ");
	    System.out.println("x = " + x.intValue() + " ; y = " + y.intValue());
	    
	    modifyWrappers(x, y);
	    
	    assertEquals(x.intValue(), 222);
	    assertEquals(y.intValue(),888);
	    
	    System.out.print("Values of x & y after wrapper modification: ");
	    System.out.println("x = " + x.intValue() + " ; y = " + y.intValue());

	}
	
	@Ignore
	private void modifyWrappers(Integer x, Integer y) {
		  x = new Integer(555);
		  y = new Integer(777);
	}
}
Output
Values of x & y before wrapper modification: x = 222 ; y = 888
Values of x & y after wrapper modification: x = 222 ; y = 888

Wrappers are stored inside the heap memory with a correspondent reference inside the stack memory.

When calling modifyWrappers(), a copy for each reference is created inside the stack memory, and the copies are passed to the method. Any change to the reference inside the method is actually changing the reference of the copies and not the original references.

Primitive Arguments

package com.cloudberry.com.my.passbyvalue;

import static org.junit.Assert.assertEquals;

import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;

/**
 * Unit test for simple App.
 */
public class PassByValueTest {
        
    @Test
	public void testPassByValuePrimitive() {
		//Init
		int x = 1;
	    int y = 2;
	    
	    //Pre-modifyPrimitiveTypes()
	    System.out.print("Values of x & y before primitive modification: ");
	    System.out.println(" x = " + x + " ; y = " + y );
	    assertEquals(x, 1);
	    assertEquals(y, 2);
	    
	    modifyPrimitiveTypes(x,y);
	    
	    //Post-modifyPrimitiveTypes()
	    System.out.print("Values of x & y after primitive modification: ");
	    System.out.println(" x = " + x + " ; y = " + y );
	    assertEquals(x, 1);
	    assertEquals(y, 2);
	}
	
	@Ignore
	private void modifyPrimitiveTypes(int x, int y)
	{
	    x = 5;
	    y = 10;
	} 
}
Output
Values of x & y before primitive modification:  x = 1 ; y = 2
Values of x & y after primitive modification:  x = 1 ; y = 2

The two variables, x and y, are of primitive types and are thus stored inside the stack memory.

When calling modifyPrimitiveTypes(), two copies are created inside the stack memory (let’s say w and z) and are then passed to the method.

Hence, the original variables are not being sent to the method and any modification inside the method flow is affecting only the copies.

Source Codes

https://github.com/wuchiachong/java-passbyvalue

Java – Pass-by-Value I

How Arguments Are Passed in Java

No matter reference type or primitive type of arguments, Java is always pass-by-value.

Each time a method is invoked, a copy for each argument is created in the stack memory and the copy version is passed to the method.

  • If the original variable type is primitive, then simply, a copy of the variable is created inside the stack memory and then passed to the method.
  • If the original type is not primitive, then a new copy of reference or pointer is created inside the stack memory, which points to the actual object data, and the new copy of reference is then passed to the method, (at this stage, two references are pointing to the same object data).

The reason why we say Java is always is pass-by-value is because of a new copy of primitive type or reference type is always created and then pass into the invoked method. Inside the method, it is that a duplicated copy of variables are being manipulated.

Reference

Passing Information to a Method or a Constructor

Java – Variable Types Explained

There are 2 types of variables in Java, namely primitive & reference.

Primitive Type

Primitive-type variables are always stored inside the stack memory. Stack is a memory space that holds method-level variables that are short-lived in addition to references to other objects in the heap.

Example of primitive type variables:

Data Type Default Value (for fields)
byte 0
short 0
int 0
long 0L
float 0.0f
double 0.0d
char ‘\u0000’
String (or any object)   null
boolean false

Reference Type

Reference type variables aka objects or pointers are stored in two locations. The actual object data is stored inside the heap memory (the memory space that holds objects and JRE classes), and a reference aka pointer for the object is kept inside stack memory, which just points to the actual object.

Java – Unary Operator Prefix and Postfix Operand Explained

Increment/Decrement Unary Operators

The beauty of unary operators is that, they require only single operand to get the same result as compare to the arithmetic operators; they perform various operations such as increment(++)/decrement(–) a value by one, negating an expression, or inverting the value of a boolean.

Operator Description
++ Increment operator; increments a value by 1
Decrement operator; decrements a value by 1

Prefix & Postfix

(++result) evaluates to the incremented value, whereas the postfix version (result++) evaluates to the original value

Main.java
public class Main{
    public static void main(String[] args){
        int i = 3;
        System.out.println(i); // prints 3
        System.out.println(i++); // prints 3 but not 4
        System.out.println(++i); //print 5
    }
}
Output
3
3
5

JavaScript – How to temporary store value-key pair until browser tab is closed

There are times, we want to store something in a page session.

Lifespan of a page session is lasted until they (either window or tab) are closed. It lasts, even though page is refreshed. Opening a page in a new tab or window will cause a new session to be initiated, which differs from how session cookies work.

// Save data to sessionStorage
window.sessionStorage.setItem('key', 'value');

// Get saved data from sessionStorage
var data = window.sessionStorage.getItem('key');

// Remove saved data from sessionStorage
window.sessionStorage.removeItem('key');

// Remove all saved data from sessionStorage
window.sessionStorage.clear();

The above example, store a value in string type into sessionStorage, and its’ key is key. The value can be retrieve later with calling getItem() of sessionStorage.

var o = window.JSON.stringify({key:"value"});

window.sessionStorage.setItem("object", o);

var a = window.JSON.parse(window.sessionStorage.getItem("object"));

By default, the stored value is a string type. Thus, to store an object, use JSON.stringify() to convert JavaScript value to a JSON string before setting it into an item. Use JSON.parse() to retrieve and restore the item into a JavaScript value.

References

Window.sessionStorage
JSON