15.08.2018

Exam. Java Basic

1. Static import
import static java.lang.Math.PI;
import static java.lang.Math.pow;
//or all the static members of a class:

import static java.lang.Math.*;


2. Java supports multiple type inheritance but not multiple state inheritance. Because interfaces specify only what the class is doing, not how it is doing it. The problem with multiple inheritance is that two classes may define different ways of doing the same thing, and the subclass can't choose which one to pick. See Oracle Java docs

3. What is polymorphism ?
public interface Vegetarian{}
public class Animal{}
public class Deer extends Animal implements Vegetarian{}
Now, the Deer class is considered to be polymorphic since this has multiple inheritance. Following are true for the above examples − A Deer IS-A Animal A Deer IS-A Vegetarian A Deer IS-A Deer A Deer IS-A Object When we apply the reference variable facts to a Deer object reference, the following declarations are legal −
Deer d = new Deer();
Animal a = d;
Vegetarian v = d;
Object o = d;
All the reference variables d, a, v, o refer to the same Deer object in the heap.
It makes the code more reusable.
It protects the code by preventing extension.

4. initialization order with inheritance

1a - Parent's static class variable pstatic initialized.
1b - Parent's static initialization block ran.
2a - Child's static initialization block ran.
2b - Child's static class variable cstatic initialized.
3 - Parent's non-static class variable initialized.
4 - Parent constructor ran.
5 - Child's non-static class variable initialized.
6 - Child constructor ran.

5. sout float or double
print 0.0 instead 0.0f

19.04.2018

Groovy. Convert a method of class to a closure

Output: Groovy says: Hello World! Groovy says: Hello Earth! Groovy says: Hello Mars!
class PrintIt {
    static def groovySays(s) {
        println "Groovy says: Hello ${s}!"
    }
}

def printIt = new PrintIt()
['World', 'Earth', 'Mars'].each(printIt.&groovySays)
Output:
Groovy says: Hello World!
Groovy says: Hello Earth!
Groovy says: Hello Mars!

09.12.2017

groovy Methods used with Closures

//Methods used with Closures

def lst = [1, 2, 3, 4]
println("List:" + lst)
// The find method finds the first value in a collection that matches some criterion.
println("find el>2: " + lst.find { element -> element > 2 })

// findAll
// finds all values in the receiving object matching the closure condition.
print("findAll el>2: ")
lst.findAll { it > 2 }.each { print it + " " }
println()

//any()
//Method any iterates through each element of a collection checking whether a Boolean predicate is
// valid for at least one element.
println("any el>2: " + lst.any { it > 2 })

//every()
//Method every iterates through each element of a collection checking whether a Boolean predicate is
// valid for every element.
println("every el>2: " + lst.every { it > 2 })

//collect()
//The method collect iterates through a collection, converting each element into a new value using
// the closure as the transformer.
println("collect list el*el: " + lst.collect { it * it })

Output:
List:[1, 2, 3, 4]
find el>2: 3
findAll el>2: 3 4
any el>2: true
every el>2: false
collect list el*el: [1, 4, 9, 16]

07.12.2017

Use each in groovy

//List
('a'..'c').each { println "Letter ${it}" }

['Cat', 'Dog', 'Elephant'].each { animalName -> println "Animal ${animalName}" }

//Set
Set testSet = ["a", "b", "c", "c"] as Set
testSet << 'd'
testSet.each { println "letter ${it}" }

//Map
def testMap = ['Moscow': 12.38, 'London': 8.173]
testMap.each { city, population -> println "population in ${city} is ${population} million" }
Output:
Letter a
Letter b
Letter c
Animal Cat
Animal Dog
Animal Elephant
letter a
letter b
letter c
letter d
population in Moscow is 12.38 million
population in London is 8.173 million

09.09.2017

Mockito How to use @InjectMocks

package my.home;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;

import java.util.logging.Logger;

import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.*;

@RunWith(MockitoJUnitRunner.class)
public class FirstServiceTest {

    @Mock
    private AnotherService anotherService;

    @InjectMocks
    private FirstService firstService = new FirstService();

    @Before
    public void setup() {
        when(anotherService.next()).thenReturn("test");
    }

    @Test
    public void firstServicenWork() throws Exception {
        String result = firstService.work();
        verify(anotherService, atLeastOnce()).next();
//        verify(anotherService, never()).next();
        assertEquals("test", result);
    }
}

class FirstService {
    private static final Logger LOGGER = Logger.getLogger(FirstServiceTest.class.getName());
    private AnotherService another;

    FirstService() {
        this.another = null;
    }


    String work() {
        LOGGER.info("FirstService is working");
        return another.next();
    }
}

class AnotherService {
    private static final Logger LOGGER = Logger.getLogger(FirstServiceTest.class.getName());

    String next() {
        LOGGER.info("AnotherService is working...");
        return null;
    }
}
   
Output:
сен 09, 2017 4:56:44 PM my.home.FirstService work
INFO: FirstService is working
Process finished with exit code 0

Recursion read files (find all mp3 in dirs)

    public static void main(String[] args) {
        String[] mp3FilesDirs = new String[]{"d:/media", "d:/temp"};
        ArrayList mp3Files = new ArrayList<>();
        for (String mp3FilesDir : mp3FilesDirs) {
            try {
                mp3Files.addAll(Files.walk(Paths.get(mp3FilesDir))
                        .filter(Files::isRegularFile)
                        .map(Path::toFile)
                        .filter(entry -> entry.getName().endsWith("mp3"))
                        .collect(Collectors.toList()));
            } catch (Exception e) {
                System.out.println("======" + e);
            }
        }
        mp3Files.forEach(file -> System.out.println(file.getAbsolutePath()));
    }

30.08.2017

Anonymous Inner class example

package ru.home;

interface Contents {
    int value();
}

public class Main {
    public static void main(String[] args) {
        Main p = new Main();
        Contents c = p.contents();
        System.out.println(c.value()); //Is 11
    }

    private Contents contents() {
        return new Contents() {
            private int i = 11;
            public int value() {
                return i;
            }
        };
    }
}