Chapter 4 – Methods and Encapsulation

Access Modifiers

# public – any class

# private – same class only

# protected – same class, sub classes in the same and other package

# default – package private (within package)

Ex: default void walk(){}//does not compile

In the above line, default is not a valid access modifier

#default method is only allowed in interface

Optional Specifier

# can have zero or more access specifier

Ex: static, final, abstract, synchronized, native, strictfp


# Optional specifier and access specifier can be interchanged

# But return type and optional specifier cannot be interchanged


public void final dummy(){}//DOES NOT COMPILE

final public void dummy(){}//IT COMPILES

Return Type

# void – no return type, omit return or give return statement and without value.


public void dummy(){return;}

public String walk(int a){if(a==4) return ””;}//DOES NOT  COMPILE

Working with Varargs

# different than array

# a varargs parameter must be last element in method signature

# implies only one varargs parameter per method

# pass an array or list the elements of the array or omit the values (creates array of length zero)


package chapter4;

public class ex1 {

public static void walk(int start, int… nums) {



public static void main(String[] args) {


walk(1, 2);

walk(1, 2, 3);

walk(1, new int[] { 2, 4, 5 });

walk(1, null);








Exception in thread “main” java.lang.NullPointerException

at chapter4.ex1.walk(

at chapter4.ex1.main(

Static Methods

# main can be called like any other static methods

# static methods have two main purposes:

■ For utility or helper methods that don’t require any object state. Since there is no need to access instance variables, having static methods eliminates the need for the caller to instantiate the object just to call the method.

■ For state that is shared by all instances of a class, like a counter. All instances must share the same state. Methods that merely use that state should be static as well.

Static Variable

# when we update a final variable of primitive type, compiler error is thrown


package chapter4;

public class ex2 {

public static final int NUM_BUCKETS = 45;

public static void main(String[] args) {




# a final variable of reference type are allowed to call methods


package chapter4;

import java.util.ArrayList;

public class ex3 {

public static final ArrayList<String> values = new ArrayList<>();


public static void main(String[] args) {




Static Initialization

# static initializer runs when class is first used

# statements in it run and assign a static variable as needed.

Ways of initializing final variable

#1: Direct initialization

final float PI=3.14f; static final float PI=3.14f;

#2: Instance Initializer Block


package chapter4;

public class ex4 {

final float PI;


PI = 3.14f;



#3: Static Initializer Block


package chapter4;

public class ex5 {

static final float PI;

static {

PI = 3.14f;




package chapter4;

public class ex6 {

private static int one;

private static final int two;

private static final int three = 3;

private static final int four; // DOES NOT COMPILE

static {

one = 1;

two = 2;

three = 3; // DOES NOT COMPILE

two = 4; // DOES NOT COMPILE



Static Import

# its for importing static members.

Syntax: import static java.util.Arrays.asList;


#1 if you are importing static member, you should directly access static variable,


Arrays.asList(“one”);//DOES NOT COMPILE

asList(“one”);//IT COMPILES

#2 importing same name gives compiler error


import static statics.A.TYPE;

import static statics.B.TYPE; // DOES NOT COMPILE

Rules for method signature

#1 change in type/order/number of arguments

#2 return type not considered

#3 varargs overloading

Ex: both the lines are same,

public void fly(int[] args){}

public void fly(int… args){}

#4 Primitive level overloading follows the sequence,

  • Exact match
  • If exact match not found, then autoboxing
  • If autoboxing unavailable, then Object
  • If Object unavailable, convert to high level


# if constructor is private, we cannot create instance of the class in another class

# we cannot call constructor without new keyword

# can be called followed by new keyword


package chapter4;

public class ex8_2 {

public ex8_2(int weight) {

new ex8_2(weight, “brown”);


public ex8_2(int weight, String color) {




# this() must be the first statement in constructor

Chapter 2 – Operators and Statements

Operators and Statements

# all of the arithmetic operator may be applied to any java primitive, except Boolean and String.

# only additional operator + and += may be applied to String value, which result in String concatenation.

Numeric Promotion

# conversion of a smaller numeric type to a larger numeric type.

byte,char,short => int

int => long

long,float => double


  1. If two values have different data types, Java will automatically promote one of the values to the larger of the two data types
  2. If one of the values is integral and the other is floating-point, Java will automatically promote the integral value to the floating-point value’s data type
  3. Smaller data types, namely byte, short, and char, are first promoted to int any time they’re used with a Java binary arithmetic operator, even if neither of the operands is int
  4. After all promotion has occurred and the operands have the same data

Unary Operators

# requires exactly one operand or variable

Increment and Decrement Operator

# ++, — => can be applied to numeric operands

# takes higher precedence

Assignment Operator

# throws compiler error if it detects you are trying to convert from large to smaller datatype

Ex: int n=1.0; //type mismatch: cannot convert from double to int

Compound Assignment Operator

Ex: x*=z; => x=x*z;

Ternary Operator

Ex: (n>2?n>4?10:8:7)

For loop

Ex: for(i=0;i<10;){i=i++;System.out.print(“Hello World”);}

Above line will result in infinite loop

Casing Primitive Values

long x = 10;

int y = 5;

y = y * x; // DOES NOT COMPILE


long x=10;

int y=5;


Chapter 1 – Java Building Blocks

To compile the java file

  • javac – it creates .class file(zoo)

To execute the java file

  • java zoo

Understanding package declaration and imports

Packages – logical grouping of classes. If the package is not imported, it shows following error message,

  • cannot be resolved to a type

import – this statement tells the compiler which packages to look into to find a class

wildcards –  import java.util.*;

  • * – is a wildcard that matches all classes in the package not sub-package classes

static import – feature of Java 5 used to access any static member of a class directly. There is no need to qualify it by the class name.

  1. importstaticlang.System.*;
  2. classStaticImportExample{
  3. public static void main(String args[]){
  4. //Now no need of System.out
  5.            println(“Hello”);
  6.            println(“World”);
  7. }
  8. }

import java.nio.*.* – we can have only one wildcard and it must be at the end.

import java.nio.files.paths – we cannot import methods, but we can import only classes

Naming Conflicts

Below 2 lines does not compile since the type Date is present in both the packages,

import java.util.*;

import java.sql.*;

Below 2 lines work, since class Date is explicitly imported. So, it takes precedence over wildcards.

import java.util.Date;

import java.sql.*;

Code formatting on the exam

  • Not all the questions will include the imports


# Same as class name

# No return type

# If there is no constructor, compiler will supply a “do nothing” default constructor.

# A constructor is called when we write new followed by the name of the class we want to instantiate.

  • new Dog();

Initializer Blocks
# Fields & Initializer blocks are run in the order in which they appear

# Constructor runs after all fields & initializer blocks have run

public class Chick {

private String name = “Janani”;


System.out.println(“Setting field”);


public Chick() {

name = “Velmurugan”;

System.out.println(“Constructor invoked”);


public static void main(String[] args) {

Chick chick = new Chick();





Setting field

Constructor invoked


Difference between reference objects and primitives

Primitive Types

# Java applications contain two types of data: primitive types and reference types

=> Octal (digits 0–7) – number 0 as a prefix—for example, 017

=> Hexadecimal (digits 0–9 and letters A–F) – number 0 followed by x or X as a prefix—for example, 0xFF

=> Binary (digits 0–1) – number 0 followed by b or B as a prefix—for example, 0b10

Reference Types

# refers to an object (an instance of a class).

Key Differences

Reference Type Primitive Type
Can be assigned null Compiler error when assigned with null
Call methods when they do not point to null Do not have methods declared on them
Java classes or classes we create begin with uppercase Have lowercase type names



Garbage Collection

# refers to the process of automatically freeing memory on the heap by deleting objects that are no longer reachable in your program

# System.gc() is not guaranteed to run – Java is free to ignore the request

An object is no longer reachable when one of two situations occurs:

■ The object no longer has any references pointing to it.

■ All references to the object have gone out of scope.

# finalize() call could run zero or one time.

Command Line Aruguments

# arrays index starts with 0(zero)

# string with spaces must be specified in quotes

Ex: java bird sparrow “blue jay”


Swagger – Spring Boot

Step #1: Add maven dependency


Step #2: Create a in com.janani.config

package com.revature.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

public class SwaggerConfig {

	public Docket api() {
		// @formatter:off
		return new Docket(DocumentationType.SWAGGER_2)

	// @formatter:on
	// private Predicate<String> fetchPaths() {
	// return or(regex("/holidays.*"), regex("/roles.*"),
	// regex("/employees.*"));
	// }

	private ApiInfo apiInfo() {
		// @formatter:off
		return new ApiInfoBuilder()
				.title("LMS API")
				.description("Leave Management System")
				.license("LMS License")


Step #3: http://localhost:5000/swagger-ui.html#/


Spring 01 – Introduction

Spring Framework – Overcome tightly-coupled
Dependency of Injection – Inversion of Control
Install Spring Framework (Two ways)
-> Dependency Management Tool – Maven downloads spring jars from central repository
-> download jars directly
Spring project recommends 1st way
Java Beans or Beans

Log4 j
Library for logging functionality
Speed and thread safety
Allows to set different logging levels
Download log 4 j
ALL<DEBUG<INFO<WARN<ERROR where advice is actually applied
Aspect = Advice + Pointcut
Introduct/Mixin -> introduce new methods to a class
Weaving – process of creating proxies
4 main components
 Application context
 A configuration class
 The beans
 Aspect that advice beans

Demo on $scope

<html ng-app="myApp">

    <script src="angular.min.js"></script>
        var productApp = angular.module("myApp", []);
        console.log("myApp called");
        productApp.controller("myController", function ($scope) {
            console.log("myController called");
            $scope.showProducts = function () {
                console.log("showProducts called");
                $scope.products = ["Samsung", "Apple"];

    <div ng-controller="myController">
        <a href="#" ng-click="showProducts()">Show Products</a> {{products}}