# data[].attributes.attachment_link.title
KŚ wyjaśnia: rdzenie i wątki w procesorze. Czym są i jak działają?

# data[].attributes.body
topic 2 - str. 61 - 85

# data[].attributes.attachment_link.readable_text
package com.company;

import java.util.Arrays;

public class Main {

    public static void main(String[] args) {
	    int[] a = {5, 4, 2, 6, 3, 7, 5};
	    int[] b = {5, 4, 2, 6, 3, 7, 5};
        System.out.println(Arrays.toString(bubbleSort(a)));
        System.out.println(Arrays.toString(selectionSort(b)));

        System.out.println(binarySearch(a, 6));
        System.out.println(binarySearch(a, 9));
    }

    public static int[] bubbleSort(int[] a) {
        int n = a.length;
        for (int p = n - 1; p > 0; p--) {
            for (int i = 0; i < p; i++) {
                if (a[i] > a[i + 1]) {
                    int temp = a[i];
                    a[i] = a[i + 1];
                    a[i + 1] = temp;
                }
            }
        }

        return a;
    }

    public static int[] selectionSort(int[] a) {
        for (int first = 0; first < a.length - 1; first++) {
            //finding minimum
            int min = first;
            for (int i = min + 1; i < a.length; i++) {
                if (a[min] > a[i]) {
                    min = i;
                }
            }
            //swaping
            int temp = a[min];
            a[min] = a[first];
            a[first] = temp;
        }

        return a;
    }

    public static int binarySearch(int[] a, int s) {
        int first = 0;
        int last = a.length - 1;
        while (first <= last) {
            int mid = (first + last) / 2;
            if (a[mid] == s) {
                return mid;
            }
            else if (a[mid] > s) {
                last = mid - 1;
            }
            else {
                first = mid + 1;
            }
        }
        return -1;
    }
}

# data[].attributes.attachment_link.title
Entity Relationship Diagram (ERD) Tutorial - Part 1

# data[].attributes.body
1. Zamieniamy ścieżki na bezwzględne i umieszczamy plik z baza danych w folderze na dysku C.
2. Tworzymy artefakt:
File -> Project Structure -> Project Settings -> Artifacts -> Click green plus sign -> Jar -> From modules with dependencies...
https://stackoverflow.com/questions/1082580/how-to-build-jars-from-intellij-properly
3. Budujemy projekt Build -> Build artifacts
4. Przenosimy plik jar do folderu z punktu 1.
5. Piszemy program rozruchowy (z rozszerzeniem .bat):
https://www.youtube.com/watch?v=ifBlevULGtM
W pliku java -jar nazwa_pliku_jar

# data[].attributes.body
Bezpłatne warsztaty programowania C#

# data[].attributes.attachment_link.readable_text
ONLINE - terminy wkrótce
STACJONARNIE:
Biała Podlaska (Plac Szkolny Dwór 9) - 20.09.2020

Białystok (ul. Legionowa 9/1) - 12-13.09.2020

Bielsko-Biała (ul. Legionów 30) - 20.09.2020

Brzesko (ul. Plac Kazimierza Wielkiego 8) - 19-20.09.2020

Busko-Zdrój (Bohaterów Warszawy 37) - 26-27.09.2020

Bydgoszcz (Plac Wolności 9) - 19.09.2020

Bytom (ul. Podgórna 9) - 26.09.2020

Chełm (ul. Adama Mickiewicza 41) - 19.09.2020

Częstochowa (ul. im. Jana Pawła II 126/130) - 19.09.2020

Dąbrowa Górnicza (ul. Królowej Jadwigi 12) - 19.09.2020

Elbląg (ul. Hetmańska 15 lok. C) - 12-13.09.2020 i 19-20.09.2020

Gdańsk (ul. Grunwaldzka 103) - 19-20.09.2020

Gdynia (ul. Świętojańska 34/3) - 19-20.09.2020

Gliwice (ul. Zwycięstwa 10) - 19-20.09.2020

Gniezno (ul. Bolesława Chrobrego 14)- 19.09.2020

Gorlice (ul. 11 listopada 37)- 19.09.2020

Grodzisk Mazowiecki (ul. Sienkiewicza 52/7) - 12.09.2020

Grójec (ul. Jana Pawła II 26 - "Centrum Konferencyjne i Szkoleniowe EDUSTREFA") - 13.09.2020

Jasło (ul. Szopena 10) - 19.09.2020

Jaworzno (ul. Rynek 17 - Miejska Biblioteka Publiczna) - 19.09.2020

Jędrzejów(Szkoła Podstawowa nr 3, ul. Reymonta 1) - 12-13.09.2020

Kalisz (ul. Kazimierzowska 6/7) - 12-13.09.2020

Katowice (ul. Korfantego 2) - 19-20.09.2020

Kielce (ul. IX Wieków Kielc 6/8) - 19-20.09.2020

Kraków (ul. Lubicz 3) - 19-20.09.2020

Kraków (ul. Kobierzyńska 100) - 19-20.09.2020

Krosno (ul. Grodzka 12) - 19.09.2020

Kościerzyna (ul. Sikorskiego 20) - 12.09.2020

Kozienice (ul. Radomska 14A) - 19.09.2020

Legionowo (ul. Strużańska 2b) - 12.09.2020

Lublin (ul. Niecała 1) - 19-20.09.2020

Łęczna (ul. Jawoszka 11) - 19.09.2020

Łódź (ul. Gdańska 126/128) - 19-20.09.2020

Łomianki (ul. Staszica 2 - SP nr 3) - 12-13.09.2020

Łuków (ul. ks. Brzóski 17) - 19-20.09.2020

Mielec (ul. Stefana Batorego 12) - 12.09.2020

Mysłowice (ul. Mikołowska 29) - 19.09.2020

Mińsk Mazowiecki (ul. Piłsudskiego 33 lok I) - 12-13.09.2020, 19-20.09.2020

Niepołomice (ul. Na Grobli 7) - 12.09.2020 (stacjonarnie), 13.09.2020 (online)

Olkusz (ul. Floriańska 1) - 12.09.2020

Olsztyn (ul. 1 Maja 13) - 12-13.09.2020

Opole (ul. Ozimska 48) - 12-13.09.2020

Otwock (ul. Kazimierza Pułaskiego 7) - 13.09.2020

Ostrołęka (ul. Głowackiego 33) - 12-13.09.2020

Ostrów Wielkopolski (ul. Kaliska 35) - 19.09.2020

Ożarów Mazowiecki (ul. Poznańska 258) - 12-13.09.2020

Piaseczno (ul. Młynarska 2a) - 12-13.09.2020

Płock (ul. Armii Krajowej 10 lok 8) - 13.09.2020 i 20.09.2020

Poznań (ul. Towarowa 35) - 19-20.09.2020

Pruszków (ul. Kościuszki 15) - 12-13.09.2020

Pruszcz Gdański(ul. Chopina 34 - Centrum Kultury i Sportu) - 19-20.09.2020

Puławy (ul. Górna 4b) - 12.09.2020

Radom (u. Rynek 7) - 12-13.09.2020

Ruda Śląska (ul. Główna 1) - 20.09.2020

Rybnik (ul. Tadeusza Kościuszki 54) - 20.09.2020

Rzeszów (Plac Jana. Kilińskiego 2) - 19-20.09.2020

Sanok (ul. Chopina 10) - 19.09.2020

Siedlce (ul. Piłsudskiego 18) - 12-13.09.2020

Skawina (ul. Korabnicka 3c) - 19-20.09.2020

Skierniewice (ul. Adama Asnyka 92) - 19.09.2020

Sochaczew (ul Piłsudskiego 63) -19.09.2020

Sosnowiec (ul. Kilińskiego 43) - 19.09.2020

Stalowa Wola (ul. Jana Pawła II 2a/6a) - 19.09.2020

Starachowice (ul. Witolda Lutosławskiego 6) - 19.09.2020

Starogard Gdański (ul. Jana Sobieskiego 6 - Zespół Szkół Ekonomicznych)- 19.09.2020

Strzelce Opolskie (ul. H. Pobożnego 1) - 12-13.09.2020

Sulejówek (ul. Idzikowskiego 2A) - 12-13.09.2020, 19-20.09.2020

Świdnik (Szkoła Podstawowa nr 5 im. Janusza Kusicińskiego, ul. Jarzębinowa 6) - 24-25.09.2020

Szczecin (al. Piastów 1) - 12-13.09.2020

Tarnobrzeg (ul. H. Sienkiewicza 16) - 20.09.2020

Tarnowskie Góry (ul. Gliwicka 35) - 20.09.2020

Tarnów (ul. Dąbrowskiego 21) - 19.09.2020

Toruń (ul. Jęczmienna 23) - 19.09.2020

Tychy (ul. Korczaka 6) - 19.09.2020

Warszawa (ul. Krucza 46) - 12-13.09.2020

Warszawa (ul. Górczewska 216) - 12-13.09.2020

Warszawa (ul. Wałbrzyska 11) - 12-13.09.2020

Wieliczka (Lokalizacja wkrótce) - 19-20.09.2020

Wołomin (ul. Wileńska PARK 51) - 12.09.2020

Wrocław (ul. Leszczyńskiego 4) - 12-13.09.2020

Wrocław (ul. Legnicka 52) - 12-13.09.2020

Września (ul. Szkolna 3) - 20.09.2020

Wyszków (ul. 11 Listopada 62 - SP 1) - 19.09.2020

Zabrze (ul. Henryka Sienkiewicza 33) - 19.09.2020

Zamość (ul. Legionów 52a) - 20.09.2020

Zielona Góra (al. Niepodległości 16/7) - 19-20.09.2020

Żyrardów (ul. 1 Maja 41b) - 12-13.09.2020

PROGRAM KODUJ Z GIGANTAMI

Warsztaty z programowania w blokach 1- lub 1,5- godzinnych w grupach do 12 osób

Klasy 4-6 szkoły podstawowej: Scratch, App Inventor

7, 8 kl. SP oraz szkoły ponadpodstawowe: C#, Visual Studio

Warsztaty z programowania - szkoła Giganci Programowania. Trenerami prowadzącymi zajęcia będą doświadczeni programiści.

<

POPRZEDNIE EDYCJE

# data[].attributes.attachment_link.title
Giganci Programowania - Nauka programowania dla dzieci i młodzieży.

# data[].attributes.attachment_link.description
ONLINE - terminy wkrótce STACJONARNIE: Biała Podlaska (Plac Szkolny Dwór 9) - 20.09.2020 Białystok (ul. Legionowa 9/1) - 12-13.09.2020 Bielsko-Biała (ul. Legionów 30) - 20.09.2020 Brzesko (ul. Plac Kazimierza Wielkiego 8) - 19-20.09.2020 Busko-Zdrój (Bohaterów Warszawy 37) - 26-27.09.2020 Bydgoszcz (Plac Wolności 9) - 19.09.2020 Bytom (ul. Podgórna 9) - 26.09.2020 Chełm (ul.

# data[].attributes.body
code

# data[].attributes.body
link do prezentacji OOP

# data[].attributes.body
3. Discuss the advantages and disadvantages of electronic currencies. [6]
4. Current and future technologies are likely to have a dramatic effect on the global economy. By explaining the modern advances in technology (virtual currencies), discuss the changes which citizens and customers may face in the future. [12]

# data[].attributes.body
czwartek godz. 8.00 - 10.00

# data[].attributes.attachment_link.title
Zadania z Olimpiady Lingwistyki Matematycznej | Fundacja Matematyków Wrocławskich

# data[].attributes.attachment_link.description
Strona główna/ Dla uczniów/ Lingwistyka matematyczna/ Olimpiada Lingwistyczna/ Zadania z Olimpiady Lingwistyki Matematycznej

# data[].attributes.body
1. Wtorek, godz. 15:30 - 17:00
Programowanie dla średnio-zaawansowanych w Javie:
- projektowanie prostych gier (2048, tetris, snake)

2. Czwartek, godz. 15:30 - 17:00
Sztuczna inteligencja (dla średnio-zaawansowanych):
- algorytmy genetyczne i sieci neuronowe od podstaw
- aplikacje mobilne na Androida

3. Środa, godz. 15:30 - 17:00 (zapisy u p. Głuskiego)
Nauka programowania od podstaw w C++

# data[].attributes.attachment_link.readable_text
package sample;

public class Main {

    public static void main(String[] args) {
        Train A = new Train(123);
        Engine B = new Engine(7);
        A.addEngine(B);
        Wagon C = new Wagon(23);
        A.addWagon(C);
        Wagon D = new Wagon(66);
        A.addWagon(D);
        Wagon E = new Wagon(71);
        A.addWagon(E);
        A.addEngine(new Engine(9));

        Wagon F = A.removeWagon();
        F = A.removeWagon();
        A.addWagon(new Wagon(214));
    }
}

public class Train {
    private Engine[] mEngines;
    private Wagon[] mWagons;
    private int mEngineCount;
    private int mWagonCount;
    private int mTrainNumber;
    private double mWeight;     // Total weight in kilograms

    public Train(int number) {
        mTrainNumber = number;
        mEngines = new Engine[6]; // The train can have up to 6 engines
        mEngineCount = 0;
        mWagons = new Wagon[100]; // The train can have up to 100 wagons
        mWagonCount = 0;
        mWeight = 0;
    }

    public void addEngine(Engine newEngine) {
        mEngines[mEngineCount] = newEngine;
        mEngineCount++;
    }

    public Engine removeEngine() {
        mEngineCount--;
        return mEngines[mEngineCount];
    }

    public void addWagon(Wagon newWagon) {
        mWagons[mWagonCount] = newWagon;
        mWagonCount++;
    }

    public Wagon removeWagon() {
        // Code to be written
        return null;
    }

    public double getWeight() {
        // Code to be written
        return 0;
    }

    //...
}

public class RollingStock {
    private int mIDNumber;
    private double mWeight;

    public RollingStock(int ID, double weight) {
        mIDNumber = ID;
        mWeight = weight;       // Weight is in kilograms
    }

    // Accessor methods
    public double getWeight() {
        return mWeight;
    }

    public int getID() {
        return mIDNumber;
    }

    // Other methods
}

public class Engine extends RollingStock {
    private double mPullingWeight;      // maximum weight engine can pull

    public Engine(int ID) {
        super(ID, 120000);      // Engines weigh 120000 kilograms
        mPullingWeight = 1400000;       // Engines can pull 1400000 kilograms
    }

    // Accessor methods
    public double getWeight() {
        return super.getWeight();
    }

    // Other methods
}

public class Wagon extends RollingStock {
    private Parcel[] mParcels;
    private int mParcelCount;

    public Wagon(int ID) {
        super(ID, 32000);       // Empty wagon weighs 32000 kilograms
        mParcels = new Parcel[100];
        mParcelCount = 0;
    }

    // Accessor methods
    public int getWagonID() {
        return this.getID();
    }

    public double getWeight() {
        // Code to be written
        return 0;
    }

    // Other methods
}

public class Parcel {
    private int trackingID;
    private double weight;
    public String destinationAddress;
    public String originAddress;

    public Parcel(int ID) {
        trackingID = ID;
        weight = 0;
    }

    public void setWeight(double newWeight) {
        weight = newWeight;
    }

    public double getWeight() {
        return weight;
    }
}

# data[].attributes.attachment_link.readable_text
package sample;

public class Main {

    Points[] allPoints = new Points[10000]; // declared globally

    public static void main(String[] args) {
        allPoints[0] = new Points("m100");
        allPoints[1] = new Points("m101",5000);
        allPoints[2] = new Points("m102",2000);

        Visits v1 = new Visits("h003", 3);
        Visits v2 = new Visits("h013", 1);
        Visits v3 = new Visits("h013", 2);
        Visits v4 = new Visits("h005", 6);

        allPoints[0].addVisit(v1);
        allPoints[0].addVisit(v2);
        allPoints[0].addVisit(v3);
        allPoints[0].addVisit(v4);
        allPoints[1].addVisit(v1);
        allPoints[1].addVisit(new Visits("h004",6));

        System.out.println(allPoints[2].getMemberId());
        System.out.println(allPoints[0].getBonusPoints());
        System.out.println(allPoints[1].getAllVisits(1).getDays());
    }
}

public class Points {
    private String memberId;                    // id of the hotel customer
    private int totalPoints;                    // this year's points
    private int bonusPoints;                    // any bonus points given to this year's new member
    private String statusNow;                   // current(this year's)status
    private String statusNextYear;              // following year's status
    private Visits[] allVisits = new Visits[366];//details of each visit during this year
    int y;                                      // number of visits this year

    // constructor for new member
    public Points(String id) {
        memberId = id;
        bonusPoints = 0;
        y = 0;
        statusNow = "Bronze";
    }

    //constructor for new member given bonus points (valid for current year only)
    public Points(String id, int bp) {
        memberId = id;
        bonusPoints = bp; // multiples of 1000 - maximum number is 5000
        y = 0;
        statusNow = "Bronze";
    }

    // all the accessor and mutator methods are present but not shown
    public Visits getAllVisits(int v) {
        return allVisits[v];
    }

    // adds a new Visit object to the array
    public void addVisit(Visits v)  {
        allVisits[y] = v;
        y = y + 1;
    }

    isGold() {
        //code missing
    }

    calculateTotalPoints(){
        //code missing
    }

    daysMissing(){
        //code missing
    }
}

public class Visits {
    private String hotelCode;   // id of the hotel
    private int days;           // number of days of the visit

    public Visits(String h, int d) {
        hotelCode = h;
        days = d;
    }

    public int getDays() {
        return days;
    }
}

public class Customer {
    private String memberId;
    private String email;       //email address (assume only 1 per customer)
    
    public Customer(String a, String b) {
        memberId = a;
        email = b;
    }

    public String getMemberId() {
        return memberId;
    }
    
    public String getEmail() {
        return email;
    }
}

# data[].attributes.body
homework

# data[].attributes.attachment_link.readable_text
package sample;

public class Main {

    public static void main(String[] args) {
        TrainCompany[] allCompanies = new TrainCompany[3];

        allCompanies[0] = new TrainCompany("Southern", "T290");
        allCompanies[1] = new TrainCompany("Northern", "T400");
        allCompanies[2] = new TrainCompany("Eastern", "T155");

        Journey s = new Journey("J100", 3 , false);
        Journey t = new Journey("J103", 8, true);
        Journey u = new Journey("J104", 10, true);

        allCompanies[0].addJourney(s);
        allCompanies[1].addJourney(t);
        allCompanies[0].addJourney(u);
        allCompanies[0].addJourney(new Journey("J101", 6, false));

        System.out.println(allCompanies[0].getCompanyCode());
        System.out.println(allCompanies[0].getJourney(1).getDelay());
        System.out.println(allCompanies[1].getNumberOfJourneys());
    }
}

public class TrainCompany {
    private String companyName;
    private String companyCode;
    private int numberOfJourneys;
    private Journey[] journeyHistory = new Journey[100_000];

    public TrainCompany(String x, String y) {
        this.companyName = x;
        this.companyCode = y;
        this.numberOfJourneys = 0;
    }

    public TrainCompany() {}

    // accessor and mutator methods

    Journey getJourney(int x) {
        return journeyHistory[x];
    }

    public void addJourney(Journey j) {
        journeyHistory[numberOfJourneys] = j;
        numberOfJourneys++;
    }

    public double averageDelay() {
        // returns the average delay for all of a company’s journeys
        // code missing
        return 0;
    }

    public String longestDelay(Codes[] c) {
        // returns the route name for the journey with the longest delay
        // code missing
        return null;
    }

    public String toString(Codes[] c) {
        // code missing
        return null;
    }
}

public class Journey {
    private … routeCode; // A unique identifier for a particular route
    private … delay; // Minutes late in arriving at the destination
    private … weatherRelated; // Equals true if the journey is affected by the weather, otherwise false.

    // Constructor which initializes all 3 of the above data items

    // accessor and mutator methods.
}

public class Codes {
    private String routeName; // e.g. New Amsterdam – Diamond City
    private String routeCode;

    public Codes(String a, String b) {
        this.routeName = a;
        this.routeCode = b;
    }

    public String getRouteCode() {
        return routeCode;
    }

    public String getRouteName() {
        return routeName;
    }
}

# data[].attributes.attachment_link.readable_text
package bb;

import java.util.LinkedList;

public class Main {

    public static void main(String[] args) {
	// write your code here
    }
}

public class Patient {
    private int id;
    private String name;
    private int priority;
    private String doctor;

    public Patient(int i, String n, int p) {
        id = i;
        name = n;
        priority = p;
        doctor = null;
    }

    public void setId(int i) {
        id = i;
    }

    public void setName(String n) {
        name = n;
    }

    public void setPriority(int p) {
        priority = p;
    }

    public void setDoctor(String d) {
        doctor = d;
    }

    public int getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    public int getPriority() {
        return priority;
    }

    public String getDoctor() {
        return doctor;
    }

    public String toString() {
        return id+" "+name+" "+priority+" "+doctor;
    }
}

public class WaitingRoom {
    private Patient[] patients = new Patients[10];

    // uses default constructor

    public void add(Patient newPatient) {
        // adds the new patient in the next empty array location
        int i = 0;
        while ((patients[i] != null) && (i < 10)) {
            i = i + 1;
        }
        if (i == 10) {
            System.out.println("No more space in the waiting room.");
        } else {
            patients[i] = newPatient;
        }
    }

    public void callNextPatient() {
        // finds the next patient, outputs their details
        // and removes the patient from the array
        int index = 0;
        if (patients[0] == null) {
            System.out.println("The waiting room is empty.");
        }
        else {
            index = findNextPatientIndex();
            remove(index);
        }
    }

    private int findNextPatientIndex() {
        // returns the index of the first patient with the
        // highest priority in the array patients
        int max = 0;
        //... code missing ...
        return max;
    }

    private void remove(int n) {
        // outputs the data of the patient instance at array index n
        // and removes that patient by shifting all remaining patients
        // by one index towards the front of the array

        //... code missing ...
    }
}

public class WaitingRoom2 {
    private LinkedList<Patient> PatientList = new LinkedList<Patient>();

    // methods
    public void add(Patient P) {
        // adds a patient at the end of the list
        PatientList.addLast(P);
    }

    public void remove() {
        // outputs the name of the next patient to see a doctor and
        // removes this patient instance from the list
        int index = findNextPatientIndex();
        System.out.println(PatientList.get(index).getName());
        PatientList.remove(index);
    }

    private int findNextPatientIndex() {
        int i = 0, result = 0;
        Patient current, firstup;
        firstup = new Patient();
        firstup.setPriority(0);
        while (i < PatientList.size()) {
            current = PatientList.get(i);
            if (current.getPriority() > firstup.getPriority()) {
                firstup = current;
                result = i;
            }
            i=i+1;
        }
        return result;
    }
}

# data[].attributes.body
homework

# data[].attributes.attachment_link.readable_text
public class Main {

    static Payment[] tables = new Payment[50];

    public static void main(String[] args) {
        tables[1] = new Payment();
        tables[2] = new Payment();
        FoodItem a = new FoodItem("f102", 2);
        FoodItem b = new FoodItem("f100", 1);
        DrinkItem c = new DrinkItem("d102", 3);
        tables[1].addFoodItem(a);
        tables[1].addFoodItem(b);
        tables[2].addDrinkItem(c);
        tables[2].addDrinkItem(new DrinkItem("d103",1));
        System.out.println(tables[1].getFiCount());
        System.out.println(Payment.getFoodTax());
        System.out.println(tables[2].getDi(1).getItemCode());
    }
}

public class Payment {
    private FoodItem[] fi = new FoodItem[100];
    private int fiCount;
    private static double foodTax = 0.2; // 20% sales tax added to all food prices
    private DrinkItem[] di = new DrinkItem[100];
    private int diCount;
    private static double drinkTax = 0.1; // 10% sales tax added to all drink prices

    public Payment() {
        fiCount = 0;
        diCount = 0;
    }

    public DrinkItem getDi(int x) {
        return di[x];
    }

    // all other accessor and mutator methods are included
    // addFoodItem() – this method adds a new FoodItem object
    // addDrinkItem() – this method adds a new DrinkItem object

    public static double findPrice(Item[] pl, String c) {
        //code missing
    }

    // calculateBill() – This method returns the bill (the total value of
    // the items consumed for a particular table)
}

public class FoodItem {
    private String itemCode;
    private int quantity;

    public FoodItem(String x, int y) {
        itemCode = x;
        quantity = y;
    }
    // all accessor and mutator methods are included
}

public class DrinkItem {
    private String itemCode;
    private int quantity;

    public DrinkItem(String x, int y) {
        itemCode = x;
        quantity = y;
    }
    // all accessor and mutator methods are included
}

# data[].attributes.attachment_link.title
Object Oriented Programming - zakres materiału na egzamin

# data[].attributes.body
1h (SL), 1h20min (HL)

# data[].attributes.attachment_link.readable_text
public class Flight {
    private String id;
    public String getId() {
        return this.id;
    }
    // ... more variables, accessor and mutator methods
}

public class Arrival {
    private Flight myFlight;
    private String sta; // Scheduled Time of Arrival ("hh:mm")
    private int runway;
    private String gate;
    private int delay;
    private boolean landed;

    public Arrival(Flight myFlight, String sta) {
        this.myFlight = myFlight;
        this.sta = sta;
        this.runway = 0;
        this.gate = null;
        this.delay = 0;
        this.landed = false;
    }

    public void addDelay(int newDelay) {
        this.delay = newDelay;
    }

    public String getETA() {
        // calculates the Estimated Time of Arrival (ETA) of the flight
        // by adding the delay to the sta and returning the result as a
        // String ("hh:mm")
    }

    public int compareWith(String flightID) {
        if (myFlight.getID().equals(flightID)) {
            return 0;
        }
        else {
            return 1;
        }
    }

    public int compareWith(Arrival anotherArrival) {
        // missing code
    }
// ... plus accessor and mutator methods
}

public class FlightManagement {
    private Arrival[] inbound; // array of inbound airplanes
    private int last = -1; // index of last used entry

    public FlightManagement() {
        inbound = new Arrival[200];
    }

    public void add(Arrival newArrival) {
        // missing code that adds the newArrival to the array inbound
        // sorted by ETA, and updates last
    }

    private int search (String flightID) {
        // missing code that searches the array inbound and
        // returns the index of the Arrival object with flightID
    }

    public Arrival remove(String flightID) {
        Arrival result;
        int index = search(flightID);
        result = inbound[index];
        while (index < last) {
            inbound[index] = inbound[index + 1];
            index++;
        }
        last--;
        return result;
    }
// ... many more methods
}

# data[].attributes.body
ankieta

# data[].attributes.body
programowanie Python

# data[].attributes.attachment_link.description
POLSKA EDYCJA 2020 REJESTRACJA O konkursie Pix Programming Challenge to międzynarodowy konkurs programistyczny dla dzieci i młodzieży. Jest on w pełni przeprowadza za pośrednictwem aplikacji PixBlocks. Zarówno udział w konkursie jak i aplikacja są całkowicie bezpłatne! Uczestnicy konkursu muszą rozwiązać zadania z zakresu programowania. Zadania dostosowane są do różnych grup wiekowych.

# data[].attributes.attachment_link.readable_text
public class Main {

    private static Basket[] baskets; //up to 10 baskets
	
	public static void main(String[] args) {
		//testing...
	}
	
	private static double getAverageWeight() {}
	
	private static int getMaxWeight() {}
	
	private static boolean isFruitPresentInTheBasket(Fruit fruit) {}
	
	private static Fruit[] getFruitsWithVitamin(String vitamin) {}
	
	private static String getFruitsNamesWithAllVitamins(List<String> vitamins) {}
	
	private static List<Vitamin> getVitaminsListInFruits(List<Fruit> fruits) {}
	
	private static String[] getVitaminsInFrequencyOrder() {}
	
	private static String[][] getFruitsAndVitaminsTable() {} 
	//  _      A B1 B2 B7 B12 C D
	//  apple  x     x        x 
	//  banana       x     x    x 
}


public class Fruit {

    private String name;		//starts with capital letter
    private boolean sweet;
    private int weight;         //in grams
    private List<String> vitamins;  //A, B1, B2, B7, B12, C or D
	
	//code missing
	
}

public class Vegetable {

    private String name;		//starts with capital letter
    private int weight;         //in grams
    private List<String> vitamins;  //A, B1, B2, B7, B12, C or D
	
	//code missing
	
}

public class Basket {
	
    private String name;
    private Fruit[] fruits; //up to 10 fruits
	private Vegetable[] vegetables; //up to 10 vegetables
	
	//code missing

}

//improvements:
//1) inheritance - one array in the Basket class
//2) enums instead of Strings as vitamins
//3) unit testing

# data[].attributes.body
code 2019.06.11

# data[].attributes.attachment_link.readable_text
package bb;

public class Main {

    static final int POPULATION_SIZE = 300;
    static final String GOAL = "one ring to rule them all";
    static final int CHROMOSOME_LENGTH = GOAL.length();
    static final double MUTATION_CHANCE = 0.01;
    static final int ITERATIONS = 300;

    static String[] population = new String[POPULATION_SIZE];
    static double[] fitness = new double[POPULATION_SIZE];

    public static void main(String[] args) {
        for (int p = 0; p < POPULATION_SIZE; p++) {
            StringBuilder chromosome = new StringBuilder();
            for (int g = 0; g < CHROMOSOME_LENGTH; g++) {
                chromosome.append(getRandomChar());
            }
            population[p] = chromosome.toString();
        }
        calcFitness();

        for (int i = 0; i < ITERATIONS; i++) {
            select();
            crossover();
            mutate();
            calcFitness();
            printPopulation(i);
        }
    }

    private static void printPopulation(int iteration) {
        double maxFitness = 0;
        int index = 0;
        for (int f = 0; f < POPULATION_SIZE; f++) {
            if (maxFitness < fitness[f]) {
                maxFitness = fitness[f];
                index = f;
            }
        }
        System.out.printf("iteration = %d: fitness = %f.2, text = %s\n", iteration,
                maxFitness, population[index]);
    }

    private static void calcFitness() {
         for (int p = 0; p < POPULATION_SIZE; p++) {
             fitness[p] = 1;
             for (int g = 0; g < CHROMOSOME_LENGTH; g++) {
                 if (population[p].charAt(g) == GOAL.charAt(g)) {
                     fitness[p]++;
                 }
             }
        }
    }

    private static void crossover() {
        for (int p = 0; p + 1 < POPULATION_SIZE; p += 2) {
            String parent1 = population[p];
            String parent2 = population[p + 1];
            int crossoverPoint = (int) (Math.random() * CHROMOSOME_LENGTH);
            String child1 = "";
            String child2 = "";
            for (int ch = 0; ch < CHROMOSOME_LENGTH; ch++) {
                if (ch < crossoverPoint) {
                    child1 += parent1.charAt(ch);
                    child2 += parent2.charAt(ch);
                }
                else {
                    child1 += parent2.charAt(ch);
                    child2 += parent1.charAt(ch);
                }
            }
            population[p] = child1;
            population[p + 1] = child2;
        }
    }

    private static void select() {
        double fitnessSum = 0;
        double maxFitness = 0;
        int index = 0;
        for (int f = 0; f < POPULATION_SIZE; f++) {
            fitnessSum += fitness[f];
            if (maxFitness < fitness[f]) {
                maxFitness = fitness[f];
                index = f;
            }
        }

        String[] newPopulation = new String[POPULATION_SIZE];
        newPopulation[0] = population[index];
        for (int p = 1; p < POPULATION_SIZE; p++) {
            double random = Math.random() * fitnessSum;
            double sum = 0;
            for (int f = 0; f < POPULATION_SIZE; f++) {
                sum += fitness[f];
                if (sum >= random) {
                    newPopulation[p] = population[f];
                    break;
                }
            }
        }
        population = newPopulation;
    }

    private static void mutate() {
        for (int p = 0; p < POPULATION_SIZE; p++) {
            for (int g = 0; g + 1 < CHROMOSOME_LENGTH; g++) {
                if (Math.random() < MUTATION_CHANCE) {
                    String ch = population[p];
                    population[p] = ch.substring(0, g) + getRandomChar() + ch.substring(g + 1);
                }
            }
        }
    }

    private static char getRandomChar() {
        //32 - space bar
        //97 - a
        //122 - z
        int random = (int) (Math.random() * 27);
        if (random == 0) {
            return ' ';
        }
        return (char) (96 + random);
    }
}

# data[].attributes.body
https://www.youtube.com/watch?v=nrKjSeoc7fc

# data[].attributes.body
About IA:
https://ib.compscihub.net/internal-assessment
Forms:

# data[].attributes.body
https://en.wikipedia.org/wiki/Representational_state_transfer
https://jsonplaceholder.typicode.com/
http://www.jsonschema2pojo.org/
https://www.vogella.com/tutorials/Retrofit/article.html
https://square.github.io/retrofit/
https://jsonformatter.curiousconcept.com
https://app.fake.rest/
https://chrome.google.com/webstore/search/rest%20api

# data[].attributes.attachment_link.title
JavaFX Animated Ball Example - Mkyong.com

# data[].attributes.attachment_link.description
Apart from the basic set up this code has only one important line. The line where we create the Timeline. This Timeline holds two important properties; the KeyFrame and the KeyValue. What we say to the Timeline in simple English is "move the ball from where it is, to the end of the Pane in 3 seconds".

# data[].attributes.body
2019-03-26

# data[].attributes.body
About SQL itself:
https://www.w3schools.com/sql/
Download SQLite Studio:
https://sqlitestudio.pl/index.rvt?act=download
Download SQLite Driver:
https://bitbucket.org/xerial/sqlite-jdbc/downloads/
Add this driver to your project in IntelliJ:
https://www.youtube.com/watch?v=NoPzqahrzp8
Code 2019-03-14 (in attachment)

# data[].attributes.body
List of steps:
I. Leader
- on Bitbucket:
1) create new repo and copy link to it
2) add collaborators in Bitbucket
- in IntelliJ:
1) VCS -> Enable VCS
2) add files to VCS
3) VCS -> Git -> Remotes
and copy adres of the repo

II. Team member
- on Bitbucket:
1) accept invitation link and copy link to repo
- in IntelliJ:
1) File -> Project from Version Control -> Git (past link to repo)

III. Work in IntelliJ
1) update from online repo
2) commit changes to offline repo
3) push changes to online repo

# data[].attributes.attachment_link.description
Various Git logos in PNG (bitmap) and EPS (vector) formats are available for use in online and print projects.

# data[].attributes.body
https://en.wikipedia.org/wiki/Git

# data[].attributes.attachment_link.title
Bitbucket | The Git solution for professional teams

# data[].attributes.attachment_link.description
Collaborate on code with inline comments and pull requests. Manage and share your Git repositories to build and ship software, as a team.

# data[].attributes.attachment_link.readable_text
To jest jeden z artykułów w ramach darmowego kursu programowania w Javie. Proszę zapoznaj się z pozostałymi częściami, mogą one być pomocne w zrozumieniu materiału z tego artykułu.

Czym jest serializacja

W jednym z poprzednich artykułów przeczytałeś o strumieniach danych, które pozwalały na zapisywanie oraz odczytywanie danych. Poznałeś wówczas między innymi klasy DataInputStream oraz DataOutputStream. Klasy te pomagają zapisywać typy proste i łańcuchy znaków.

Serializacja to wbudowany mechanizm zapisywania obiektów, który pozwala na binarny zapis całego drzewa obiektów. Oznacza to tyle, że jeśli mamy obiekt X, który posiada referencję do obiektu Y to serializując X również Y zostanie automatycznie zapisany w strumieniu wyjściowym.

Tak zapisany obiekt możesz później otworzyć przy kolejnym uruchomieniu programu. Jednak serializacja ma więcej zastosowań.

Dzięki temu mechanizmowi można na przykład przesyłać obiekty przez sieć. Obiekt, który stworzyliśmy na jednym komputerze (wewnątrz pamięci jednej wirtualnej maszyny Java) może być zserializowany, przesłany przez sieć i zdeserializowany na drugim komputerze tworząc nową instancję obiektu (wewnątrz pamięci drugiej wirtualnej maszyny Javy). Na obu tych komputerach wirtualna maszyna Javy musi mieć dostęp do skompilowanej wersji klasy.

Przygotowałem rozwiązania kilku zadań algorytmicznych z rozmów kwalifikacyjnych. Rozkładam je na czynniki pierwsze i pokazuję różne sposoby ich rozwiązania. Dołącz do grupy ponad 2501 Samouków, którzy jako pierwsi dowiadują się o nowych treściach na blogu, a prześlę je na Twój e-mail.

Warunki wymagane do serializacji

Chociaż serializacja dostępna jest automatycznie dla większości obiektów z biblioteki standardowej to jeśli chcesz móc serializować instancje klas, które sam napiszesz musisz spełnić kilka warunków.

Jest to tak zwany interfejs znacznikowy, innymi słowy nie zwiera on żadnej metody. Służy on do pokazania wirtualnej maszynie, że instancje danej klasy implementującej ten interfejs mogą być serializowane. Musisz implementować ten interfejs jeśli chcesz aby twoje klasy były serializowalne. Jeśli będziesz próbował zserializować klasę, która nie implementuje tego interfejsu zostanie rzucony wyjątek typu NotSerializableException.

Konstruktor bezparametrowy

Tutaj reguła niestety nie jest trywialna. Pierwsza klasa w hierarchii dziedziczenia, która nie jest serializowalna musi mieć dostępny konstruktor bezparametrowy. Łatwiej to będzie zrozumieć na przykładzie:

W przykładzie powyżej klasa Fruit musi mieć konstruktor bezparametrowy abyśmy mogli poprawnie serializować instancje klasy Apple. Natomiast ani Apple, ani Tomato takiego konstruktora już nie wymagają ( Tomato dziedziczy po Object, który taki konstruktor posiada).

Dodatkowo istnieje interfejs java.io.Externalizable (opiszę go dokładnie kilka akapitów niżej), który również zapewnia, że obiekty go implementujące są serializowalne. Jednak w tym przypadku obiekt taki musi także zapewnić konstruktor bezparametrowy, który jest wywoływany w trakcie deserializacji.

Określić pola, które nie są serializowalne

Ten krok jest opcjonalny, jednak w bardziej zaawansowanych przypadkach niezbędny. Wyobraź sobie, że napisałeś klasę Human, która jako jeden z atrybutów posiada wiek zapisany w minutach od urodzenia. Zapisanie tego pola mogłoby prowadzić do odczytania niepoprawnego stanu (zapisujemy obiekt dzisiaj, odczytujemy jutro, wiek w minutach jest zupełnie inny).

Tutaj dochodzimy do słowa kluczowego transient. Otóż słowo to może być stosowane przed atrybutami klasy. Oznacza ono, że dany atrybut nie jest serializowalny i zostanie pominięty przez mechanizm serializacji.

Przykład serializacji obiektu

Proszę zwróć uwagę na fragment kodu poniżej, który pokazuje jak mechanizm serializacji działa w praktyce.

W pierwszym bloku try-with-resources otwieramy strumień typu ObjectOutputStream, na którym następnie wywołujemy metodę writeObject zapisując do strumienia dwie liczby.

W kolejnym bloku dzięki instancji ObjectInputStream odczytujemy wcześniej zapisane obiekty. Obiekty odczytywane są w takiej samej kolejności w jakiej zostały zapisane, w naszym przypadku na konsoli zostaną wyświetlone liczby 1 a później 2.

Serializacja drzewa obiektów

Wspomniałem już wcześniej, że mechanizm serializacji automatycznie obsługuje drzewa obiektów. W przykładzie poniżej pokazana jest właśnie taka sytuacja. Instancja klasy Car posiada atrybuty typów Engine oraz Tyre[]. Serializując a następnie deserializując instancję tej klasy wszystkie jej atrybuty zostały także zapisane.

Zwróć proszę uwagę na ostatnią linię. W linijce tej porównywane są dwa adresy instancji klasy Car (pamiętasz różnicę między == a equals?). Oczywiście linijka ta wyświetli false na konsoli co dowodzi, że w procesie deserializacji został stworzony zupełnie nowy obiekt klasy Engine.

Deserializacja atrybutów transient

Zaraz, jak to? Przecież kilka akapitów wyżej napisałem, że atrybuty poprzedzone słowem kluczowym transient nie są serializowane. Tak to prawda, jednak podczas deserializacji atrybuty tego typu należy zainicjalizować pewną wartością. Otóż dla każdego typu mamy taką domyślną wartość:

W przykładzie powyżej po deserializacji pole age będzie miało wartość null ponieważ jest to wartość domyślna dla atrybutów poprzedzonych słowem kluczowym transient, które są obiektami.

Pola statyczne a serializacja

Serializacja dotyczy instancji klasy, nie samej klasy. Zatem jeśli zmodyfikowałeś pole statyczne a następnie zdeserializowałeś taki obiekt wprowadzone zmiany zostaną pominięte. Proszę spójrz na przykład poniżej.

W przykładzie tym modyfikujemy wartość pola statycznego someField a następnie serializujemy instancję klasy do pliku.

W drugim uruchomieniu programu (w którym nie zmodyfikowaliśmy wartości atrybutu statycznego someField) deserializujemy ten sam plik. W tym przypadku otrzymamy wartość 100 a nie 200, które miał obiekt zapisywany do pliku.

To co trzeba zapamiętać to to, że pola statyczne nie są serializowane a są pobierane z aktualnej definicji klasy (nie z klasy z momentu serializacji).

Możemy powiedzieć, że atrybuty static są też domyślnie transient. Jak zatem takie zmiany odzwierciedlić podczas deserializacji? Jest na to sposób :)

Specjalna obsługa serializacji/deserializacji

W specyficznych przypadkach masz możliwość zmodyfikowania domyślnego zachowania mechanizmu serializacji. Możesz to zrobić jeśli zaimplementujesz poniższe metody.

Metoda readObject(java.io.ObjectInputStream stream), którą zaimplementujesz jest automatycznie wywoływana w momencie odczytywania obiektu ze strumienia, czyli w trakcie wywołania metodyObjectInputStream.readObject().

Mechanizm ten wygląda podobnie w przypadku zapisu obiektu. Metoda writeObject(java.io.ObjectOutputStream stream), którą zaimplementujesz jest automatycznie wywoływana w momencie zapisywania obiektu do strumienia, czyli w trakcie wywołania metody ObjectOutputStream.writeObject().

Poniższy przykład powinien Ci pomóc w zrozumieniu tego mechanizmu:

Jak widzisz obie metody są tu zaimplementowane. writeObject jako argument dostaje strumień, do którego powinniśmy zapisać nasz obiekt. Metoda readObject jako jedyny argument przyjmuje strumień, z którego powinniśmy odczytać stan obiektu.

Warto tutaj zwrócić uwagę na to, że klasa ObjectInputStream posiada metodę defaultReadObject, która przeprowadza standardową deserializację, którą możesz rozszerzyć. Podobnie wygląda to w przypadku klasy ObjectOutputStream i metody defaultWriteObject. Metody te mogą być wywołane wyłącznie w trakcie (de)serializacji obiektu. Zajmują się one (de)serializacją atrybutów klasy, które nie są oznaczone jako static lub transient.

Serializacja a dziedziczenie

W poprzednich przykładach użyliśmy klasy Engine, która implementuje interfejs Serializable. Załóżmy, że utworzyliśmy klasę DieselEngine, która dziedziczy po Engine. Automatycznie instancje klasy DieselEngine będą implementowały interfejs Serializable (dziedzicząc go z Engine). Co powinniśmy zrobić jeśli nie chcielibyśmy aby nasz DieselEngine był serializowalny? Należy użyć wspomnianego już wyjątku NotSerializableException jak w przykładzie poniżej:

Pełny wpływ na mechanizm serializacji

Istnieje jeszcze jeden, dużo mniej popularny sposób zapewnienia iż obiekt może być serializowany. Jest nim interfejs Externalizable. W tym przypadku interfejs ten zawiera dwie metody, które musimy zaimplementować. Dodatkowo takie klasy muszą mieć konstruktor bezparametrowy, reszta pozostaje bez zmian. W przypadku tego podejścia cały protokół serializacji, kolejność zapisanych pól, format etc. leży po naszej stronie. Poniżej prosty przykład, w którym używam właśnie takiego podejścia.

W tym przypadku do utworzenia obiektu mechanizm serializacji używa standardowego konstruktora bezparametrowego. Po czym wywołuje na tej instancji metodę readExternal.

Pole serialVersionUID

Dodatkowo musisz wiedzieć o statycznym polu w klasie o nazwie serialVersionUID. Jego pełna definicja wygląda następująco:

Pole to ma specyficzne zastosowanie. Mechanizm serializacji używa go do upewnienia się, że deserializowany obiekt „pasuje" do danych zapisanych w strumieniu. Wie o tym na podstawie wartości tego pola. Jeśli w zdeserializowanym obiekcie wartość tego pola jest taka sama jak aktualnej definicji klasy wówczas można bezpiecznie przeprowadzić deserializację.

Kiedy taka sytuacja może wystąpić? Załóżmy, że dzisiaj napiszesz klasę Human, zdeserializujesz jej instancję i zapiszesz w pliku na dysku. Po jakimś czasie wprowadzisz zmiany w klasie i będziesz chciał odczytać starą wersję z pliku. W niektórych przypadkach taka operacja nie będzie dozwolona. Właśnie wtedy pole serialVersionUID może pomóc w wykryciu takiej sytuacji.

Pole to możesz ustawić samodzielnie, jeśli tego nie zrobisz kompilator wygeneruje tę wartość za Ciebie na podstawie definicji klasy.

Materiały dodatkowe

Na początek zestaw dokumentacji do klas, związanych z tematem, jak zwykle znajdziesz tam ogrom informacji.

Dodatkowo możesz zajrzeć do specyfikacja mechanizmu serializacji albo artykułu na stronie Oracle. Znalazłem też inne opracowanie, które poruszą także zagadnienie serializacji, także do formatu XML. Możesz też rzucić okiem na przykłady użyte w tym artykule.

Zadania

Na koniec jak zwykle zadania dla Ciebie do przećwiczenia materiału z tego artykułu.

Napisz program, który poprosi użytkownika o wprowadzenie kilku imion, imiona te zapisz w liście a następnie zserializuj ją do pliku. Napisz metodę, która odczyta ten plik i wyświetli zawartość listy na konsoli. Wiesz, że właśnie napisałeś prostą bazę danych? ;)

Napisz klasę Human, która będzie miała dwa atrybuty name typu String oraz age typu int. Jak należałoby serializować instancje tej klasy aby zawsze poprawnie deserializować wiek (z dokładnością do roku)? (Wskazówka, możesz użyć metody Calendar.getInstance().get(Calendar.YEAR), która zwraca aktualny rok)

Przygotowałem też dla Ciebie przykładowe rozwiązania powyższych zadań, jednak traktuj je proszę jako ostatnią deskę ratunku :) Więcej nauczysz się próbując samemu rozwiązać powyższe zadania.

Podsumowanie

Po przeczytaniu tego artykułu wiesz już czym są klasy ObjectOutputStream i ObjectInputStream. Znasz zasady serializacji, poznałeś słowo kluczowe transient. Teraz jesteś w stanie zapisać i odczytać każdą instancję klasy, którą stworzysz.

Bardzo się cieszę, że przeczytałeś cały artykuł. Na koniec mam do Ciebie prośbę. Proszę przekaż adres bloga swoim znajomym, w grupie uczy się raźniej ;) Jeśli nie chcesz ominąć nowych artykułów dopisz się do newslettera i polub stronę Samouczka na Facebooku. Miłego dnia i do następnego razu :)

Przygotowałem rozwiązania kilku zadań algorytmicznych z rozmów kwalifikacyjnych. Rozkładam je na czynniki pierwsze i pokazuję różne sposoby ich rozwiązania. Dołącz do grupy ponad 2501 Samouków, którzy jako pierwsi dowiadują się o nowych treściach na blogu, a prześlę je na Twój e-mail.

# data[].attributes.attachment_link.description
W artykule tym dowiesz się czym jest serializacja obiektów w Javie. Przeczytasz o klasach takich jak ObjectInputStream czy ObjectOutputStream i dowiesz się czym różnią się od innych strumieni. Poznasz nowe słowo kluczowe transient. Po przeczytaniu artykułu będziesz w stanie napisać swoją mini bazę danych z użyciem mechanizmu serializacji. Zapraszam do lektury.

# data[].attributes.attachment_link.description
"Najprościej mówiąc klasę ArrayList wykorzystujemy w przypadku, gdy najważniejszy jest czas dostępu do danych, natomiast LinkedList, gdy wiemy, że często będą wykonywane operacje usuwania, dodawania itp elementów gdzieś w środku struktury" - jeżeli ArrayList to odpowiednik Vector z C++ a LinkedList to List z C++ (a to wnioskuje po artykule), to to zdanie jest całkowitą głupotą.

# data[].attributes.body
two nice exercises with 2d-arrays

# data[].attributes.body
https://www.draw.io/

Additional homework: hashing passwords.
https://www.youtube.com/watch?v=--tnZMuoK3E

https://howtodoinjava.com/security/how-to-generate-secure-password-hash-md5-sha-pbkdf2-bcrypt-examples/

# data[].attributes.attachment_link.title
JavaFX Java GUI Tutorial - 1 - Creating a Basic Window

# data[].attributes.body
homework

# data[].attributes.attachment_link.readable_text
/*Main class*/
public class Main {

    public static Student[] students = new Student[10];

    public static void main(String[] args) {
        Date d1 = new Date(29,02,2018);
        Date d2 = new Date(28,02,2018);
        Date d3 = new Date(32,03,2018);
        Date d4 = new Date(29,02,1899);
        System.out.println(d1.toString());
        System.out.println(d2.toString());
        System.out.println(d3.toString());
        System.out.println(d4.toString());
        Subject s1 = new Subject("    matEMatyka   ", 5);
        Subject s2 = new Subject("Polski", 5);
        Subject s3 = new Subject(" geoGRAFia  ", 0);
        Subject s4 = new Subject("    historia", 9);
        System.out.println(s1.toString());
        System.out.println(s2.toString());
        System.out.println(s3.toString());
        System.out.println(s4.toString());
        //random numbers
        //https://javastart.pl/static/klasy/klasa-random-generator-pseudolosowy/
        Random random = new Random();
        Grade g1 = new Grade(s1, random.nextInt(4) + 2);  //random.nextInt(4) gives 0,1,2 or 3
        Grade g2 = new Grade(s2, random.nextInt(4) + 2);
        Grade g3 = new Grade(s3, random.nextInt(4) + 2);
        Grade g4 = new Grade(s4, random.nextInt(4) + 2);
        System.out.println(g1.toString());
        System.out.println(g2.toString());
        System.out.println(g3.toString());
        System.out.println(g4.toString());
        Student s = new Student(" janeK");
        students[0] = s;
        s.addGrade(g1);
        s.addGrade(g2);
        s.addGrade(g3);
        s.addGrade(g4);
        System.out.println(s.toString());
        s.removeGrade("polski ");
        System.out.println(s.toString());
        System.out.println(s.getTotalECTS());
        System.out.println(s.getAverageMark());
        System.out.println(s.getWeightedAverageMark());
        System.out.println(s.getStandardDeviationOfMarks());
        s.setYearOfBirth(new Date(8, 03, 2000));
        System.out.println(s.isStudentAdult());
        s.setYearOfBirth(new Date(9, 03, 2000));
        System.out.println(s.isStudentAdult());
        s.setYearOfBirth(new Date(10, 03, 2000));
        System.out.println(s.isStudentAdult());
        System.out.println(s.getSubject("GEOGRAFIA"));
        System.out.println(s.getMaxGrade());
        System.out.println(Arrays.toString(s.getFailedGrades()));
    }
}

/*Student class*/
public class Student {
	
    private static int numberOfStudents = 0;
    private static final int MAX_NUMBER_OF_GRADES = 10;
    //unique id's starting from 1
    private int id;
    private String name;
    private Date yearOfBirth;
    private int gradesCount;
    private Grade[] grades;

    /*1*/public Student(String name) {}

    //constructor overloading
    /*2*/public Student(String name, Date yearOfBirth) {
        //constructor chaining
        //invoking previous one-argument constructor
    }

    /*3*/public boolean addGrade(Grade grade){}

    /*4*/public boolean removeLastGrade(){}
	
	/*5*/public Grade removeLastGradeAndReturnIt(){}

	/*6#*/public boolean removeGrade(String name){}
	
	/*7#*/public Grade removeGradeAndReturnIt(String name){}

    /*8*/public Subject getSubject(String name){}
		
	/*9##*/public boolean isStudentAdult(){}//compare to current date

    /*10*/public double getTotalECTS(){}

    /*11*/public double getAverageMark(){}

    /*12*/public double getWeightedAverageMark(){}//pointECTS as a weight

    /*13*/public double getStandardDeviationOfMarks(){}//https://en.wikipedia.org/wiki/Standard_deviation

    /*14*/public Grade getMaxGrade(){}
	
	/*15*/public Grade getMinGrade(){}
	
	/*16#*/public Grade[] getFailedGrades(){}
	
	/*17#*/public Grade[] getGradesWithPointECTS(int pointECTS){}
	
	/*18##*/public Grade[] getGradesSortedByMark(){}
	
	/*19##*/public Grade[] getGradesSortedBySubjectName(){}

	/*20##*/public Grade[] getGradesSortedByPointECTS(){}
	
	/*31#*/public Grade[] getGradesWithMark(int mark){}
	
	/*32##*/public Date getCurrentDateFromSystem(){}
	
	/*33#*/public Grade[] getGradesWithNameStartedWithLetter(String letter){}
	
	/*21*/public String getStudentMarksReport(){}
	//Student name and id
	//Subject1: mark (pointECTS)
	//Subject2: mark (pointECTS)
	//Subject3: mark (pointECTS)...
	
	/*22*/public void setName(String name) {}

    public static int getNumberOfStudents() {
        return numberOfStudents;
    }

    public static int getMaxNumberOfGrades() {
        return MAX_NUMBER_OF_GRADES;
    }

    public int getId() {
        return id;
    }

     public String getName() {
        return name;
    }

    public int getGradesCount() {
        return gradesCount;
    }

    public Grade[] getGrades() {
        return grades;
    }

    public Date getYearOfBirth() {
        return yearOfBirth;
    }

    public void setYearOfBirth(Date yearOfBirth) {
        this.yearOfBirth = yearOfBirth;
    }

    @Override
    public String toString() {
        return "Student{" +
                "id=" + id +
                ", name='" + name +
                ", yearOfBirth=" + yearOfBirth +
                ", gradesCount=" + gradesCount +
                ", grades=" + Arrays.toString(grades) +
                '}';
    }
}


/*Grade class*/
public class Grade {
	
    private Subject subject;
    private int mark;
    private Date date;
    private boolean retake = false;

    /*23*/public Grade(Subject subject, int mark) {}

    public Subject getSubject() {
        return subject;
    }

    public void setSubject(Subject subject) {
        this.subject = subject;
    }

    public int getMark() {
        return mark;
    }

    public void setMark(int mark) {
        this.mark = mark;
    }

    public Date getDate() {
        return date;
    }

    public void setDate(Date date) {
        this.date = date;
    }

    public boolean isRetake() {
        return retake;
    }

    public void setRetake(boolean retake) {
        this.retake = retake;
    }

    @Override
    public String toString() {
        return "Grade{" +
                "subject=" + subject +
                ", mark=" + mark +
                ", date=" + date +
                ", retake=" + retake +
                '}';
    }
}

/*Subject class*/
public class Subject {
    
	private static int numberOfSubjects = 0;
    //unique id's starting from 1
    private int id;
    private String name;
    private int pointECTS;

    /*24*/public Subject(String name, int pointECTS) {}

    public static int getNumberOfSubjects() {
        return numberOfSubjects;
    }

    public int getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    /*25*/public void setName(String name) {}

    public int getPointECTS() {
        return pointECTS;
    }

    /*26*/public boolean setPointECTS(int pointECTS) {}

    @Override
    public String toString() {
        return "Subject{" +
                "id=" + id +
                ", name='" + name +
                ", pointECTS=" + pointECTS +
                '}';
    }
}

/*Date class*/
public class Date {
	
    private int day;
    private int month;
    private int year;

    /*27*/public Date(int day, int month, int year) {}

    public int getDay() {
        return day;
    }

    public int getMonth() {
        return month;
    }

    public int getYear() {
        return year;
    }

    /*28*/public boolean setDate(int day, int month, int year) {}

    /*29##*/private boolean dateIsValid(int day, int month, int year){}

    @Override
    public String toString() {
        return "Date{" +
                "day=" + day +
                ", month=" + month +
                ", year=" + year +
                '}';
    }
}

/*StringFormat class*/
public class StringFormat {

    /*30##*/public static String getFormatted(String bedString){}
}

# data[].attributes.body
Shadows of the Knight - Episode 1

# data[].attributes.attachment_link.readable_text
import java.util.*;
import java.io.*;
import java.math.*;

/**
 * Auto-generated code below aims at helping you parse
 * the standard input according to the problem statement.
 **/
class Player {

    public static void main(String args[]) {
        Scanner in = new Scanner(System.in);
        int W = in.nextInt(); // width of the building.
        int H = in.nextInt(); // height of the building.
        int N = in.nextInt(); // maximum number of turns before game over.
        int X0 = in.nextInt();
        int Y0 = in.nextInt();

        int firstX = 0;
        int lastX = W - 1;
        int firstY = 0;
        int lastY = H - 1;

        int nextX = X0;
        int nextY = Y0;
        // game loop
        while (N-- > 0) {
            String bombDir = in.next(); // the direction of the bombs from batman's current location (U, UR, R, DR, D, DL, L or UL)

            if (bombDir.contains("U")) {
                lastY = nextY - 1;
            }
            else if (bombDir.contains("D")){
                firstY = nextY + 1;
            }

            if (bombDir.contains("L")) {
                lastX = nextX - 1;
            }
            else if (bombDir.contains("R")){
                firstX = nextX + 1;
            }

            nextX = (firstX + lastX) / 2;
            nextY = (firstY + lastY) / 2;

            // the location of the next window Batman should jump to.
            System.out.println(nextX + " " + nextY);
        }
    }
}

# data[].attributes.attachment_link.title
JUnit 4 with IntelliJ: A quick introduction

# data[].attributes.body
2019-01-03

# data[].attributes.attachment_link.readable_text
/*Main class*/
package bb;

public class Main {

    private static Cage[] cages = new Cage[10];
    private static int cagesCount = 0;

    public static void main(String[] args) {
	    Animal a1 = new Animal("tiger", 200);
	    Animal a2 = new Animal("lion", 100);
	    Animal a3 = new Animal("snake", 10);
	    Animal a4 = new Animal("panda", 20);
	    a1.setFed(true);
	    a3.setFed(true);

	    Cage c1 = new Cage("c1");
	    c1.addAnimal(a1);
	    c1.addAnimal(a2);

        Cage c2 = new Cage("c2");
        c2.addAnimal(a3);
        c2.addAnimal(a4);

        addCage(c1);
        addCage(c2);

        System.out.println(getAnimalsNames());
        System.out.println(getFedAnimalsNames());
        System.out.println(getTotalAnimalsWeight());
        System.out.println(getAverageWeight());
    }

    public static void addCage(Cage cage){
        if(cagesCount < cages.length){
            cages[cagesCount] = cage;
            cagesCount++;
        }
    }

    public static String getAnimalsNames(){
        String animalsNames = "";
   /*     for (int i = 0; i < cagesCount; i++) {
            animalsNames += cages[i].getAnimalsNames();
        }*/

        for (int i = 0; i < cagesCount; i++) {
            Cage cage = cages[i];
            for (int j = 0; j < cage.getAnimalsCount(); j++) {
                animalsNames += cage.getAnimals()[j].getName() + " ";
            }
        }

        return animalsNames;
    }

    public static String getFedAnimalsNames(){
        String fedAnimalsNames = "";
        for (int i = 0; i < cagesCount; i++) {
            fedAnimalsNames += cages[i].getFedAnimalsNames() + ", ";
        }
        return fedAnimalsNames;
    }

    public static double getTotalAnimalsWeight(){
        double totalWeight = 0;
        for (int i = 0; i < cagesCount; i++) {
            totalWeight += cages[i].getTotalAnimalsWeight();
        }
        return totalWeight;
    }
    public static double getAverageWeight() {
        double totalWeight = 0;
        int count = 0;
        for (int i = 0; i < cagesCount; i++) {
            totalWeight += cages[i].getTotalAnimalsWeight();
            count += cages[i].getAnimalsCount();
        }
        double average = totalWeight / count;
        return average;
    }

}



/*Cage class*/
package bb;

import java.util.Arrays;

public class Cage {
    private String name;
    private int number;
    private static int cageNumber = 0;
    private int animalsCount = 0;
    private Animal[] animals = new Animal[10];

    public Cage(String name){
        this.name = name;
        cageNumber++;
        this.number = cageNumber;
    }

    public void addAnimal(Animal animal){
        if (animalsCount < animals.length){
            animals[animalsCount] = animal;
            animalsCount++;
        }
    }

    public Animal removeAnimal(){
        if (animalsCount == 0){
            return null;
        }
        Animal temp = animals[animalsCount - 1];
        animals[animalsCount - 1] = null;
        animalsCount--;
        return temp;
    }

    public String getFedAnimalsNames(){
        String fedAnimalsNames = "";
        for (int i = 0; i < animalsCount; i++) {
            //if (animals[i] != null)
            if (animals[i].isFed() == true){
                fedAnimalsNames += animals[i].getName();
            }
        }
        return fedAnimalsNames;
    }

    public String getName() {
        return name;
    }

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

    public int getNumber() {
        return number;
    }

    public void setNumber(int number) {
        this.number = number;
    }

    public static int getCageNumber() {
        return cageNumber;
    }

    public int getAnimalsCount() {
        return animalsCount;
    }

    public Animal[] getAnimals() {
        return animals;
    }

    @Override
    public String toString() {
        return "Cage{" +
                "name='" + name + '\'' +
                ", number=" + number +
                ", animalsCount=" + animalsCount +
                ", animals=" + Arrays.toString(animals) +
                '}';
    }

    public String getAnimalsNames() {
        // TODO: 2019-01-03 method not finished
        return "nie ma mnie:(";
    }

    public double getTotalAnimalsWeight(){
        double totalWeight = 0;
        for (int i = 0; i < animalsCount; i++) {
            totalWeight += animals[i].getWeight();
        }

        return totalWeight;
    }
}





/*Animal class*/
package bb;

public class Animal {
    private String name;
    private double weight;
    private boolean fed;

    public Animal(String name, double w){
        this.name = name;
        weight = w;
        fed = false;
    }

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

    public String getName(){
        return this.name;
    }

    public double getWeight() {
        return weight;
    }

    public void setWeight(double weight) {
        this.weight = weight;
    }

    public boolean isFed() {
        return fed;
    }

    public void setFed(boolean fed) {
        this.fed = fed;
    }

    @Override
    public String toString() {
        return "Animal{" +
                "name='" + name + '\'' +
                ", weight=" + weight +
                ", fed=" + fed +
                '}';
    }
}

# data[].attributes.body
UML diagram

# data[].attributes.body
2018-12-20

# data[].attributes.attachment_link.readable_text
package bb;

public class Main {

    public static void main(String[] args) {
	    Item elixir = new Item("Elixir", 100);
	    Item sword = new Item("Sword", 10);
	    Item staff = new Item("Staff", 300);

	    Mage gandalf = new Mage();
	    gandalf.addItem(elixir);
	    gandalf.addItem(sword);
	    gandalf.addItem(staff);

        System.out.println(gandalf.toString());

		System.out.println(gandalf.getMaxAp());
		System.out.println(gandalf.getItemsNames());
		System.out.println(gandalf.getItemWithMaxAp().toString());
	}
}



/*Item*/
package bb;

public class Item {//POJO
    private String name;
    private int ap;

    public Item(String name, int ap) {
        this.name = name;
        this.ap = ap;
    }

    public String getName() {
        return name;
    }

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

    public int getAp() {
        return ap;
    }

    public void setAp(int ap) {
        this.ap = ap;
    }

    @Override
    public String toString() {
        return "Item{" +
                "name='" + name + '\'' +
                ", ap=" + ap +
                '}';
    }
}



/*Mage*/
package bb;

import java.util.Arrays;

public class Mage {
    private Item[] items = new Item[10];
    private int itemsCount = 0;

    public void addItem(Item item){
        if (itemsCount < items.length){
            items[itemsCount] = item;
            itemsCount++;
        }
    }

    public String getItemsNames(){
        String names = "";
        for (int i = 0; i < itemsCount; i++) {
            names += items[i].getName() + ", ";
        }
        return names;
    }

    public int getMaxAp(){
        int maxAp = -1;
        if (itemsCount > 0){
            maxAp = items[0].getAp();
            for (int i = 1; i < itemsCount; i++) {
                if (items[i].getAp() > maxAp){
                    maxAp = items[i].getAp();
                }
            }
        }
        return maxAp;
    }

    public Item getItemWithMaxAp(){
        Item item = null;
        if (itemsCount > 0){
            item = items[0];
            int maxAp = items[0].getAp();
            for (int i = 1; i < itemsCount; i++) {
                if (items[i].getAp() > maxAp){
                    item = items[i];
                    maxAp = items[i].getAp();
                }
            }
        }
        return item;
    }

    public Item getItemByName(String name){
        Item item = null;
        for (int i = 0; i < itemsCount; i++) {
            if (items[i].getName().equalsIgnoreCase(name)){
                item = items[i];
            }
        }
        return item;
    }

    public Item[] getItemsWithApGreaterThan(int min){
        int count = 0;
        for (int i = 0; i < itemsCount; i++) {
            if (items[i].getAp() > min){
                count++;
            }
        }
        Item[] itemsGreaterThan = new Item[count];

        count = 0;
        for (int i = 0; i < itemsCount; i++) {
            if (items[i].getAp() > min){
                itemsGreaterThan[count] = items[i];
                count++;
            }
        }

        return itemsGreaterThan;
    }

    public Item[] getItems() {
        return items;
    }

    public void setItems(Item[] items) {
        this.items = items;
    }

    public int getItemsCount() {
        return itemsCount;
    }

    public void setItemsCount(int itemsCount) {
        this.itemsCount = itemsCount;
    }

    @Override
    public String toString() {
        return "Mage{" +
                "items=" + Arrays.toString(items) +
                ", itemsCount=" + itemsCount +
                '}';
    }
}

# data[].attributes.body
Main and Mage class

# data[].attributes.attachment_link.readable_text
Java is an object-oriented programming language. It allows you to divide complex problems into smaller sets by creating objects.

These objects share two characteristics:

Let's take few examples:

You will learn about 3 main features of an object-oriented programming: data encapsulation, inheritance and polymorphism in later chapters. This article will focus on class and objects to keep things simple.

Recommended reading: What is an object?

Java Class

Before you create objects in Java, you need to define a class.

A class is a blueprint for the object.

We can think of class as a sketch (prototype) of a house. It contains all the details about the floors, doors, windows etc. Based on these descriptions we build the house. House is the object.

Since, many houses can be made from the same description, we can create many objects from a class.

How to define a class in Java?

Here's how a class is defined in Java:

class ClassName { // variables   // methods }

Here's an example:

class Lamp {   // instance variable private boolean isOn;   // method public void turnOn() { isOn = true; } // method public void turnOff() { isOn = false; } }

Here, we defined a class named Lamp.

The class has one instance variable (variable defined inside class) isOn and two methods turnOn() and turnOff(). These variables and methods defined within a class are called members of the class.

Notice two keywords, private and public in the above program. These are access modifiers which will be discussed in detail in later chapters. For now, just remember:

The private keyword makes instance variables and methods private which can be accessed only from inside the same class.

The public keyword makes instance variables and methods public which can be accessed from outside of the class.

In the above program, isOn variable is private whereas turnOn() and turnOff() methods are public.

If you try to access private members from outside of the class, compiler throws error.

Java Objects

When class is defined, only the specification for the object is defined; no memory or storage is allocated.

To access members defined within the class, you need to create objects. Let's create objects of Lamp class.

class Lamp {
 boolean isOn; void turnOn() { isOn = true; } void turnOff() { isOn = false; } } class ClassObjectsExample { public static void main(String[] args) { Lamp l1 = new Lamp(); // create l1 object of Lamp class Lamp l2 = new Lamp(); // create l2 object of Lamp class } }

This program creates two objects l1 and l2 of class Lamp.

How to access members?

You can access members (call methods and access instance variables) by using . operator. For example,

l1.turnOn();

This statement calls turnOn() method inside Lamp class for l1 object.

We have mentioned word method quite a few times. You will learn about Java methods in detail in the next chapter. Here's what you need to know for now:

When you call the method using the above statement, all statements within the body of turnOn() method are executed. Then, the control of program jumps back to the statement following l1.turnOn();

Similarly, the instance variable can be accessed as:

l2.isOn = false;

It is important to note that, the private members can be accessed only from inside the class. If the code l2.isOn = false; lies within the main() method (outside of the Lamp class), compiler will show error.

Example: Java Class and Objects

class Lamp { boolean isOn; void turnOn() { isOn = true; } void turnOff() { isOn = false; } void displayLightStatus() { System.out.println("Light on? " + isOn); } } class ClassObjectsExample { public static void main(String[] args) { Lamp l1 = new Lamp(), l2 = new Lamp(); l1.turnOn(); l2.turnOff(); l1.displayLightStatus(); l2.displayLightStatus(); } }

When you run the program, the output will be:

Light on? true Light on? false

In the above program,

Lamp class is created.

The class has an instance variable isOn and three methods turnOn(), turnOff() and displayLightStatus().

Two objects l1 and l2 of Lamp class are created in the main() function.

Here, turnOn() method is called using l1 object: l1.turnOn();

This method sets isOn instance variable of l1 object to true.

And, turnOff() method is called using l2 object: l2.turnOff();

This method sets isOff instance variable of l2 object to false.

Finally, l1.displayLightStatus(); statement displays Light on? true because isOn variable holds true for l1 object.

And, l2.displayLightStatus(); statement displays Light on? false because isOn variable holds false for l2 object

Note, variables defined within a class are called instance variable for a reason.

When an object is initialized, it's called an instance. Each instance contains its own copy of these variables. For example, isOn variable for objects l1 and l2 are different.

This article is just a basic introduction on Java Class and Objects. Check these chapters in sequence to learn more:

Java Methods

Java Constructors

Java Access Modifiers

Java this Keyword

Java garbage collection and finalize()

# data[].attributes.attachment_link.description
Java is an object-oriented programming language. It allows you to divide complex problems into smaller sets by creating objects. These objects share two characteristics: Let's take few examples: You will learn about 3 main features of an object-oriented programming: data encapsulation, inheritance and polymorphism in later chapters.

# data[].attributes.body
Dance:
https://www.youtube.com/watch?v=lyZQPjUT5B4
Comparision:
https://www.youtube.com/watch?v=kPRA0W1kECg

# data[].attributes.attachment_link.readable_text
package bb;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Scanner;

public class Main {

    public static void main(String[] args) {

        File file = new File("numbers.txt");
        try {
            //reading from a file
            Scanner scanner = new Scanner(file);
            int[] numbers = new int[scanner.nextInt()];
            int count = 0;
            while (scanner.hasNext()){
                numbers[count] = scanner.nextInt();
                count++;
            }
            scanner.close();

            //selection sort
            for (int next = 0; next < numbers.length - 1; next++) {
                int min = numbers[next];
                int index = next;
                for (int i = next + 1; i < numbers.length; i++) {
                    if (numbers[i] < min){
                        min = numbers[i];
                        index = i;
                    }
                }
                int temp = numbers[index];
                numbers[index] = numbers[next];
                numbers[next] = temp;
            }

            //bubble sort
            for (int i = 1; i < numbers.length; i++) {
                for (int p = 0; p < numbers.length - i; p++) {
                    if (numbers[p] > numbers[p + 1]){
                        int temp = numbers[p];
                        numbers[p] = numbers[p + 1];
                        numbers[p + 1] = temp;
                    }
                }   
            }

            //writing in a file
            PrintWriter printWriter = new PrintWriter("numbersSorted.txt");
            for (int i = 0; i < numbers.length; i++) {
                printWriter.println(numbers[i]);
            }
            printWriter.close();

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }
}

# data[].attributes.body
1. Leap year, checking if given number is prime number, GCD algorithm
2. Arrays of number and Strings (the sum / average / min /max / frequency)
3. Checking if given String / number is present in the array / calc how many times
4. Palindrom, reversing a String / an array
5. Conversion
6. Ceasar cipher
7. Parallel arrays
8. Change-making problem
9. File input / output
10. try-catch
11. Sequential and binary search
12. Bubble and selection sort

# data[].attributes.body
https://en.wikipedia.org/wiki/L-system

https://en.wikipedia.org/wiki/Run-length_encoding

https://stackoverflow.com/questions/8210616/printwriter-append-method-not-appending

# data[].attributes.attachment_link.readable_text
package bb;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintWriter;

public class Main {

    public static void main(String[] args) {
	    String lSystem = "A";
	    StringBuilder temp = new StringBuilder();
        for (int i = 0; i < 20; i++) {
            for (int l = 0; l < lSystem.length(); l++) {
                if (lSystem.charAt(l) == 'A') {
                    //lSystem.substring(l, l + 1).equals("A")
                    temp.append("AB");
                }
                if (lSystem.charAt(l) == 'B') {
                    temp.append("A");
                }
            }
            lSystem = temp.toString();
            temp = new StringBuilder();
            try {
                PrintWriter printWriter = new PrintWriter(new FileOutputStream(
                        new File("lSystem.txt"), true));
                printWriter.println(i + " - " + lSystem.length() + ": " + lSystem);
                printWriter.close();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
        }
    }
}

# data[].attributes.headline
2d arrays - the scope of material for test (HL only):

# data[].attributes.subject
2d arrays - the scope of material for test (HL only):

# data[].attributes.body
1. Print an array.
2. Calculate the sum / average / standard deviation / max / min value of a given array.
3. Calculate the sum of all elements in one row / column / diagonal.
4. Calculate how many times a given word / number / letter / digit is present in the array.
5. Check if an array is symmetric / skew-symmetric / stochastic / magic.
6. Check if a given array contains all numbers from 1 to n^2 inclusive.
7. Generate an array filled with random numbers / stochastic numbers / numbers from 1 to n^2 in descendant / ascendant / spiral / slash / random order.
8. Transpose a matrix.
9. Multiply two matrices.
10. Calculate a determinant of a given matrix.
11. Calculate how many neighbours have a certain cell (like the game of life or the minesweeper game).
12. Calculate shortest distance from the middle to a given number in an array.

# data[].attributes.body
code (20.11.2018)

# data[].attributes.attachment_link.readable_text
package bb;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        System.out.println(codeText("abc dxyz", new int[]{1,0,2}));
        breakCode0();
    }

    public static String readFromFile(String fileName){
        File file = new File(fileName);
        String stringFromFile = "";
        try {
            Scanner scanner = new Scanner(file);
            while (scanner.hasNext()){
                stringFromFile += scanner.nextLine();
            }
            scanner.close();
            return stringFromFile;
        } catch (FileNotFoundException ex) {
            System.out.println("File not found");
            return "File not found";
        }
    }

    public static void writeInFile(String text, String fileName){
        try {
            PrintWriter printWriter = new PrintWriter(fileName);
            printWriter.print(text);
            printWriter.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

    private static String codeText(String text, int[] key){
        //small letters a = 97, z = 122 (26 characters), space = 32
        StringBuilder codedText = new StringBuilder(text.length());
        char letter;
        int j = 0;
        for (int i = 0; i < text.length(); i++) {
            letter = text.charAt(i);
            if (letter == 32){
                codedText.append(" ");
            }
            else{
                int letterValue = letter - 97;
                letterValue = (letterValue + key[j] + 26*100) % 26 + 97;
                letter = (char) letterValue;
                codedText.append(letter);
                j = (j + 1) % key.length;
            }
        }
        return codedText.toString();
    }

    private static String decodeText(String text, int[] key){
        //small letters a = 97, z = 122 (26 characters), space = 32
        StringBuilder codedText = new StringBuilder(text.length());
        char letter;
        int j = 0;
        for (int i = 0; i < text.length(); i++) {
            letter = text.charAt(i);
            if (letter == 32){
                codedText.append(" ");
            }
            else{
                int letterValue = letter - 97;
                letterValue = (letterValue - key[j] + 26*100) % 26 + 97;
                letter = (char) letterValue;
                codedText.append(letter);
                j = (j + 1) % key.length;
            }
        }
        return codedText.toString();
    }

    private static void breakCode0(){
        String codedMessage = readFromFile("textCoded0.txt");
        for (int i = 1; i < 26; i++) {
            int[] key = {i};
            String decodedMessage = decodeText(codedMessage, new int[]{i} );
            System.out.printf("Key: %d, decoded text: %s\n", i, decodedMessage);
        }
    } 

}

# data[].attributes.body
https://en.wikipedia.org/wiki/Caesar_cipher

# data[].attributes.body
int calcDigitsSum(int number)

int calcHowManyTimesGivenDigitIsPresentInNumber(int number, int digit)

void printHowManyTimesAllDigitsArePresentInNumber(int number)

int[] addOne(int[] number, int base)

int[] convertNumberFromDecimalTo(int number, int base)

int[] convertNumberFromSystemToSystem(int[] number, int currentBase, int nextBase)

# data[].attributes.attachment_link.readable_text
package bb;

import java.util.Arrays;

public class Main {

    public static void main(String[] args) {
        System.out.println(calcDigitsSum(12_548_484));
        System.out.println(calcHowManyTimesGivenDigitIsPresentInNumber(12_564_154, 7));
        printHowManyTimesAllDigitsArePresentInNumber(1234567898);

        System.out.println(Arrays.toString(addOne(new int[]{1,15,15}, 16)));
        System.out.println(Arrays.toString(addOne(new int[]{4,13,14}, 16)));

        System.out.println(Arrays.toString(convertNumberFromDecimalTo(63, 2)));
        System.out.println(Arrays.toString(convertNumberFromDecimalTo(256, 16)));

        System.out.println(Arrays.toString(convertNumberFromSystemToSystem(new int[]{1, 3}, 10, 10)));
        System.out.println(Arrays.toString(convertNumberFromSystemToSystem(new int[]{1, 15}, 16, 2)));
        System.out.println(Arrays.toString(convertNumberFromSystemToSystem(new int[]{1,1,1,1,1}, 2, 16)));
    }

    private static int calcDigitsSum(int number){
        int sum = 0;
        while(number > 0){
            sum += number % 10;
            //number = number / 10;
            number /= 10;
        }
        return sum;
    }

    private static int calcHowManyTimesGivenDigitIsPresentInNumber(int number, int digit){
        int count = 0;
        while(number > 0){
            int currentDigit = number % 10;
            if (currentDigit == digit){
                count++;
            }
            number /= 10;
        }
        return count;
    }

    private static void printHowManyTimesAllDigitsArePresentInNumber(int number){
        for (int i = 0; i <= 9; i++) {
            System.out.printf("%d is present %d times \n", i,
                    calcHowManyTimesGivenDigitIsPresentInNumber(number, i));
        }
    }

    private static int[] addOne(int[] number, int base){
        for (int i = number.length - 1; i >= 0; i--) {
            if (number[i] < base - 1){
                number[i]++;
                return number;
            }
            else {
                number[i] = 0;
            }
        }
        return null;
    }

    private static int[] convertNumberFromDecimalTo(int number, int base){
        int count = 0;
        int number2 = number;
        while (number2 > 0){
            number2 /= base;
            count++;
        }
        int[] converted = new int[count];
        int i = converted.length - 1;
        while (number > 0){
            converted[i] = number % base;
            //number = number / base;
            number /= base;
            i--;
        }
        return converted;
    }

    private static int[] convertNumberFromSystemToSystem(int[] number, int currentBase, int nextBase){
        int decimalNumber = 0;
        for (int i = 0; i < number.length; i++) {
            decimalNumber += number[i] * Math.pow(currentBase, number.length - 1 - i);
        }
        return convertNumberFromDecimalTo(decimalNumber, nextBase);
    }
}

# data[].attributes.body
1. Conway's Game of Life
(symbolized as B3/S23)

2. Tic Tac Toe or Connect 4 (as homework)

# data[].attributes.attachment_link.description
“Conway game” redirects here. For Conway’s surreal number game theory, see Surreal number.

# data[].attributes.body
The change-making problem addresses the question of finding the minimum number of coins (of certain denominations) that add up to a given amount of money.
For the so-called canonical coin systems, like those used in the US and many other countries, a greedy algorithm of picking the largest denomination of coin which is not greater than the remaining amount to be made will produce the optimal result. This is not the case for arbitrary coin systems, though: if the coin denominations were 1, 3 and 4, then to make 6, the greedy algorithm would choose three coins (4,1,1) whereas the optimal solution is two coins (3,3).

# data[].attributes.attachment_link.description
Coin values can be modeled by a set of n distinct positive integer values (whole numbers), arranged in increasing order as through .

# data[].attributes.body
1. Mars lander.

# data[].attributes.attachment_link.readable_text
package bb;

public class Main {

    private static final int RANGE = 5;
    private static final int ROWS_NUMBER = 20;
    private static final int COLUMNS_NUMBER = 40;
    private static final int SAFE_PLACE = -1;
    private static final int CLOSEST_SAFE_PLACE = -2;

    private static int[][] landingSite = new int[ROWS_NUMBER][COLUMNS_NUMBER];

    public static void main(String[] args) {
        generateRandomLandingSite();
        printLandingSite();
        findSafeLandingSite();
        printLandingSite();
    }

    private static void printLandingSite() {
        for (int r = 0; r < ROWS_NUMBER; r++) {
            for (int c = 0; c < COLUMNS_NUMBER; c++) {
                int ls = landingSite[r][c];
                System.out.print(ls == SAFE_PLACE ? "_" : ls == CLOSEST_SAFE_PLACE ? "\'" : ls);
                System.out.print(" ");
            }
            System.out.println();
        }
    }

    private static void generateRandomLandingSite() {
        for (int r = 0; r < ROWS_NUMBER; r++) {
            for (int c = 0; c < COLUMNS_NUMBER; c++) {
                landingSite[r][c] = (int) (Math.random() * RANGE);
            }
        }
    }

    private static void findSafeLandingSite() {
        int shuttlePositionX = ROWS_NUMBER / 2;
        int shuttlePositionY = COLUMNS_NUMBER / 2;
        double minDistance = 100000;
        int minRow = -2;
        int minColumn = -2;
        for (int r = 0; r < ROWS_NUMBER - 1; r++) {
            for (int c = 0; c < COLUMNS_NUMBER - 1; c++) {
                if (landingSite[r][c] == landingSite[r][c + 1]
                        && landingSite[r][c] == landingSite[r + 1][c]
                        && landingSite[r][c] == landingSite[r + 1][c + 1]) {
                    landingSite[r][c] = landingSite[r + 1][c] = landingSite[r][c + 1] = landingSite[r + 1][c + 1] = SAFE_PLACE;
                    double distance = Math.pow(shuttlePositionX - r, 2) + Math.pow(shuttlePositionY - c, 2);
                    if (distance < minDistance) {
                        minDistance = distance;
                        minRow = r;
                        minColumn = c;
                    }
                    System.out.printf("Safe place was found in: (%d, %d) on distance %f.\n", r, c, distance);
                }
            }
        }
        if (minDistance != 100000) {
            System.out.printf("The closest safe place was found in: (%d, %d).\n", minRow, minColumn);
            landingSite[minRow][minColumn] = landingSite[minRow + 1][minColumn] = landingSite[minRow][minColumn + 1]
                    = landingSite[minRow + 1][minColumn + 1] = CLOSEST_SAFE_PLACE;
        } else {
            System.out.println("No safe place was found!");
        }
    }
}

# data[].attributes.body
1. Print all elements
2. Calculate the sum of all elements
3. Calculate the average value
4. Calculate the sum of all elements in given row / column and in the diagonals (trace for the main diagonal)
5. Transpose a matrix
6. Add two matrices
7. Multiply by scalar
8. Check if given array is unitary or symmetric matrix

# data[].attributes.attachment_link.readable_text
Before learning multidimensional array, visit Java array article to learn about one-dimensional array.

In that chapter, you learned to create and use array of primitive data types (like: Double, int etc.), String array, and array of objects. It's also possible to create an array of arrays known as multidimensional array. For example,

int[][] a = new int[3][4];

Here, a is a two-dimensional (2d) array. The array can hold maximum of 12 elements of type int.

Remember, Java uses zero-based indexing, that is, indexing of arrays in Java starts with 0 and not 1.

Similarly, you can declare a three-dimensional (3d) array. For example,

String[][][] personalInfo = new String[3][4][2];

Here, personalInfo is a 3d array that can hold maximum of 24 (3*4*2) elements of type String.

In Java, components of a multidimensional array are also arrays.

If you know C/C++, you may feel like, multidimensional arrays in Java and C/C++ works in similar way. Well, it doesn't. In Java, rows can vary in length.

You will see the difference during initialization.

How to initialize a 2d array in Java?

Here's an example to initialize a 2d array in Java.

int[][] a = {
      {1, 2, 3},
      {4, 5, 6, 9},
      {7},
};

As mentioned, each component of array a is an array in itself, and length of each rows is also different.

Let's write a program to prove it.

class MultidimensionalArray { public static void main(String[] args) { int[][] a = { {1, 2, 3}, {4, 5, 6, 9}, {7}, }; System.out.println("Length of row 1: " + a[0].length); System.out.println("Length of row 2: " + a[1].length); System.out.println("Length of row 3: " + a[2].length); } }

When you run the program, the output will be:

Length of row 1: 3 Length of row 2: 4 Length of row 3: 1

Since each component of a multidimensional array is also an array ( a[0], a[1] and a[2] are also arrays), you can use length attribute to find the length of each rows.

Example: Print all elements of 2d array Using Loop

class MultidimensionalArray { public static void main(String[] args) { int[][] a = { {1, -2, 3}, {-4, -5, 6, 9}, {7}, }; for (int i = 0; i < a.length; ++i) { for(int j = 0; j < a[i].length; ++j) { System.out.println(a[i][j]); } } } }

It's better to use for..each loop to iterate through arrays whenever possible. You can perform the same task using for..each loop as:

class MultidimensionalArray { public static void main(String[] args) { int[][] a = { {1, -2, 3}, {-4, -5, 6, 9}, {7}, }; for (int[] innerArray: a) { for(int data: innerArray) { System.out.println(data); } } } }

When you run the program, the output will be:

1
-2
3
-4
-5
6
9
7

How to initialize a 3d array in Java?

You can initialize 3d array in similar way like a 2d array. Here's an example:

// test is a 3d array
int[][][] test = {
              {
               {1, -2, 3},
               {2, 3, 4}
              },
              {
               {-4, -5, 6, 9},
               {1},
               {2, 3}
              }
};

Basically, 3d array is an array of 2d arrays.

Similar like 2d arrays, rows of 3d arrays can vary in length.

Example: Program to print elements of 3d array using loop

class ThreeArray { public static void main(String[] args) { // test is a 3d array int[][][] test = { { {1, -2, 3}, {2, 3, 4} }, { {-4, -5, 6, 9}, {1}, {2, 3} } }; // for..each loop to iterate through elements of 3d array for (int[][] array2D: test) { for (int[] array1D: array2D) { for(int item: array1D) { System.out.println(item); } } } } }

When you run the program, the output will be:

1 -2 3 2 3 4 -4 -5 6 9 1 2 3

# data[].attributes.attachment_link.title
Java Multidimensional Array (2d and 3d Array)

# data[].attributes.attachment_link.description
Before learning multidimensional array, visit Java array article to learn about one-dimensional array. In that chapter, you learned to create and use array of primitive data types (like: Double, int etc.), String array, and array of objects. It's also possible to create an array of arrays known as multidimensional array.

# data[].attributes.body
https://en.wikipedia.org/wiki/Traveler%27s_dilemma

# data[].attributes.attachment_link.readable_text
package bb;

/*The original game scenario was formulated in 1994 by Kaushik Basu and goes as follows:

An airline loses two suitcases belonging to two different travelers. Both suitcases happen to be identical and contain identical antiques.
An airline manager tasked to settle the claims of both travelers explains that the airline is liable for a maximum of $100 per suitcase
—he is unable to find out directly the price of the antiques.

To determine an honest appraised value of the antiques, the manager separates both travelers so they can't confer,
and asks them to write down the amount of their value at no less than $20 and no larger than $100.
He also tells them that if both write down the same number, he will treat that number as the true dollar value of both suitcases
and reimburse both travelers that amount. However, if one writes down a smaller number than the other,
this smaller number will be taken as the true dollar value, and both travelers will receive that amount along with a bonus/malus:
$10 extra will be paid to the traveler who wrote down the lower value and a $10 deduction will be taken from the person who wrote down the higher amount.
The challenge is: what strategy should both travelers follow to decide the value they should write down?

https://en.wikipedia.org/wiki/Traveler%27s_dilemma*/


import java.util.Arrays;

public class Main {

    private static final int MIN_PRICE = 20;
    private static final int MAX_PRICE = 100;
    private static final int BONUS = 10;
    private static final int ROUNDS = 50;

    public static void main(String[] args) {
	    int[] firstPlayerChoices = new int[ROUNDS];
	    int[] secondPlayerChoices = new int[ROUNDS];
	    int firstPlayerTotalScore = 0;
	    int secondPlayerTotalScore = 0;

        for (int currentRound = 0; currentRound < ROUNDS; currentRound++) {
            int[] firstPlayerChoicesTemp = Arrays.copyOf(firstPlayerChoices, firstPlayerChoices.length);
            int[] secondPlayerChoicesTemp = Arrays.copyOf(secondPlayerChoices, secondPlayerChoices.length);
            int firstPlayerChoice = getFirstPlayerChoice(currentRound, firstPlayerTotalScore, secondPlayerTotalScore, firstPlayerChoicesTemp, secondPlayerChoicesTemp);
            int secondPlayerChoice = getSecondPlayerChoice(currentRound, secondPlayerTotalScore, firstPlayerTotalScore, secondPlayerChoicesTemp, firstPlayerChoicesTemp);
            firstPlayerChoices[currentRound] = firstPlayerChoice;
            secondPlayerChoices[currentRound] = secondPlayerChoice;

            int firstPlayerScore = -1;
            int secondPlayerScore = -1;

            if (firstPlayerChoice < MIN_PRICE || firstPlayerChoice > MAX_PRICE){
                firstPlayerScore = 0;
                if (secondPlayerChoice >= MIN_PRICE && secondPlayerChoice <= MAX_PRICE){
                    secondPlayerScore = secondPlayerChoice + BONUS;
                }
            }
            if (secondPlayerChoice < MIN_PRICE || secondPlayerChoice > MAX_PRICE){
                secondPlayerScore = 0;
                if (firstPlayerChoice >= MIN_PRICE && firstPlayerChoice <= MAX_PRICE){
                    firstPlayerScore = firstPlayerChoice + BONUS;
                }
            }
            if (firstPlayerScore == -1 && secondPlayerScore == -1){
                if (firstPlayerChoice == secondPlayerChoice){
                    firstPlayerScore = secondPlayerScore = firstPlayerChoice;
                }
                else if (firstPlayerChoice < secondPlayerChoice){
                    firstPlayerScore = firstPlayerChoice + BONUS;
                    secondPlayerScore = firstPlayerChoice - BONUS;
                }
                else {
                    firstPlayerScore = secondPlayerChoice - BONUS;
                    secondPlayerScore = secondPlayerChoice + BONUS;
                }
            }

            firstPlayerTotalScore += firstPlayerScore;
            secondPlayerTotalScore += secondPlayerScore;

            System.out.printf("First player choice: %d and score: + %d (= %d), second player choice %d and score: + %d (= %d).\n",
                    firstPlayerChoice, firstPlayerScore, firstPlayerTotalScore, secondPlayerChoice, secondPlayerScore, secondPlayerTotalScore);
        }
        System.out.printf("\nFirst player score: %d, second player score: %d.\n\n", firstPlayerTotalScore, secondPlayerTotalScore);
        System.out.println(Arrays.toString(secondPlayerChoices));
        System.out.println(Arrays.toString(firstPlayerChoices));
    }


    private static int getFirstPlayerChoice(int currentRound, int yourScore, int enemyScore, final int[] yourChoices, final int[] enemyChoices){
        int choice;
        if (currentRound == 0){
            choice = MAX_PRICE;
        }
        else {
            choice = enemyChoices[currentRound - 1];
            enemyChoices[currentRound - 1] = 5;
        }
        return choice;
    }

    private static int getSecondPlayerChoice(int currentRound, int yourScore, int enemyScore, final int[] yourChoices, final int[] enemyChoices){
        int choice;
        if (currentRound == 0){
            choice = MAX_PRICE;
        }
        else {
            choice = enemyChoices[currentRound - 1];
            enemyChoices[currentRound - 1] = 5;
        }
        return choice;
    }


/*    private static int getSecondPlayerChoice(int currentRound, int yourScore, int enemyScore, final int[] yourChoices, final int[] enemyChoices){
        return (int) (Math.random() * 120);
    }*/


/*    private static int getSecondPlayerChoice(int currentRound, int yourScore, int enemyScore, final int[] yourChoices, final int[] enemyChoices){
        return 60;
    }*/


/*    private static int getSecondPlayerChoice(int currentRound, int yourScore, int enemyScore, final int[] yourChoices, final int[] enemyChoices){
      int choice;
        if (currentRound == 0){
            choice = MAX_PRICE;
        }
        else {
            choice = enemyChoices[currentRound - 1];
            enemyChoices[currentRound - 1] = 5;
        }
        return choice;
    }*/
}

# data[].attributes.attachment_link.readable_text
What is a method?

In mathematics, you might have studied about functions. For example, is a function that returns squared value of x.

If x = 2, then f(2) = 4
If x = 3, f(3) = 9
and so on.

Similarly, in programming, a function is a block of code that performs a specific task.

In object-oriented programming, method is a jargon used for function. Methods are bound to a class and they define the behavior of a class.

Recommended Reading: Java Class and Objects

Types of Java methods

Depending on whether a method is defined by the user, or available in standard library, there are two types of methods:

Standard Library Methods

User-defined Methods

Standard Library Methods

The standard library methods are built-in methods in Java that are readily available for use. These standard libraries come along with the Java Class Library (JCL) in a Java archive (*.jar) file with JVM and JRE.

For example,

print() is a method of java.io.PrintSteam. The print("...") prints the string inside quotation marks.

sqrt() is a method of Math class. It returns square root of a number.

Here's an working example:

public class Numbers { public static void main(String[] args) { System.out.print("Square root of 4 is: " + Math.sqrt(4)); } }

When you run the program, the output will be:

Square root of 4 is: 2.0

User-defined Method

You can also define methods inside a class as per your wish. Such methods are called user-defined methods.

How to create a user-defined method?

Before you can use (call a method), you need to define it.

Here is how you define methods in Java.

public static void myMethod() {
	System.out.println("My Function called");
}

Here, a method named myMethod() is defined.

You can see three keywords public, static and void before the function name.

The public keyword makes myMethod() method public. Public members can be accessed from outside of the class. To learn more, visit: Java public and private Modifiers.

The static keyword denotes that the method can be accessed without creating the object of the class. To learn more, visit: Static Keyword in Java

The void keyword signifies that the method doesn't return any value. You will learn about returning value from the method later in this article.

In the above program, our method doesn't accept any arguments. Hence the empty parenthesis (). You will learn about passing arguments to a method later in this article.

The complete syntax for defining a Java method is:

modifier static returnType nameOfMethod (Parameter List) {
	// method body
}

Here,

modifier - defines access type whether the method is public, private and so on.

static - If you use static keyword in a method then it becomes a static method. Static methods can be called without creating an instance of a class.

For example, thesqrt() method of standard Math class is static. Hence, we can directly call Math.sqrt() without creating an instance of Math class.

returnType - A method can return a value.

It can return native data types (int, float, double etc.), native objects (String, Map, List etc.), or any other built-in and user defined objects.

If the method does not return a value, its return type is void.

nameOfMethod - The name of the method is an identifier.

You can give any name to a method. However, it is more conventional to name it after the tasks it performs. For example,calculateInterest, calculateArea, and so on.

Parameters (arguments) - Parameters are the values passed to a method. You can pass any number of arguments to a method.

Method body - It defines what the method actually does, how the parameters are manipulated with programming statements and what values are returned. The codes inside curly braces { } is the body of the method.

How to call a Java Method?

Now you defined a method, you need to use it. For that, you have to call the method. Here's how:

myMethod();

This statement calls the myMethod() method that was declared earlier.

1. While Java is executing the program code, it encounters myMethod(); in the code.

2. The execution then branches to the myFunction() method, and executes code inside the body of the method.

3. After the codes execution inside the method body is completed, the program returns to the original state and executes the next statement.

Example: Complete Program of Java Method

Let's see a Java method in action by defining a Java class.

class Main { public static void main(String[] args) { System.out.println("About to encounter a method."); // method call myMethod(); System.out.println("Method was executed successfully!"); } // method definition private static void myMethod(){ System.out.println("Printing from inside myMethod()!"); } }

When you run the program, the output will be:

About to encounter a method. Printing from inside myMethod(). Method was executed successfully!

The method myMethod() in the above program doesn't accept any arguments. Also, the method doesn't return any value (return type is void).

Note that, we called the method without creating object of the class. It was possible because myMethod() is static.

Here's another example. In this example, our method is non-static and is inside another class.

class Main { public static void main(String[] args) { Output obj = new Output(); System.out.println("About to encounter a method."); // calling myMethod() of Output class obj.myMethod(); System.out.println("Method was executed successfully!"); } } class Output { // public: this method can be called from outside the class public void myMethod() { System.out.println("Printing from inside myMethod()."); } }

When you run the program, the output will be:

About to encounter a method. Printing from inside myMethod(). Method was executed successfully!

Note that, we first created instance of Output class, then the method was called using obj object. This is because myMethod() is a non-static method.

Java Methods with Arguments and Return Value

A Java method can have zero or more parameters. And, they may return a value.

Example: Return Value from Method

Let's take an example of method returning a value.

class SquareMain { public static void main(String[] args) { int result; result = square(); System.out.println("Squared value of 10 is: " + result); } public static int square() { // return statement return 10 * 10; } }

When you run the program, the output will be:

Squared value of 10 is: 100

In the above code snippet, the method square() does not accept any arguments and always returns the value of 10 squared.

Notice, the return type of square() method is int. Meaning, the method returns an integer value.

As you can see, the scope of this method is limited as it always returns the same value.

Now, let's modify the above code snippet so that instead of always returning the squared value of 10, it returns the squared value of any integer passed to the method.

Example: Method Accepting Arguments and Returning Value

public class SquareMain { public static void main(String[] args) { int result, n; n = 3 result = square(n); System.out.println("Square of 3 is: " + result); n = 4 result = square(n); System.out.println("Square of 4 is: " + result); } static int square(int i) { return i * i; } }

When you run the program, the output will be:

Squared value of 3 is: 9 Squared value of 4 is: 16

Now, the square() method returns the squared value of whatever integer value passed to it.

Java is a strongly-typed language. If you pass any other data type except int (in the above example), compiler will throw an error.

The argument passed n to the getSquare() method during the method call is called actual argument.

result = getSquare(n);

The parameter i accepts the passed arguments in the method definition getSquare(int i). This is called formal argument (parameter). The type of the formal argument must be explicitly typed.

You can pass more than one argument to the Java method by using commas. For example,

public class ArithematicMain { public static int getIntegerSum (int i, int j) { return i + j; } public static int multiplyInteger (int x, int y) { return x * y; } public static void main(String[] args) { System.out.println("10 + 20 = " + getIntegerSum(10, 20)); System.out.println("20 x 40 = " + multiplyInteger(20, 40)); } }

When you run the program, the output will be:

10 + 20 = 30 20 x 40 = 800

The data type of actual and formal arguments should match, i.e., the data type of first actual argument should match the type of first formal argument. Similarly, the type of second actual argument must match the type of second formal argument and so on.

Example: Get Squared Value Of Numbers from 1 to 5

public class JMethods { // method defined private static int getSquare(int x){ return x * x; } public static void main(String[] args) { for (int i = 1; i <= 5; i++) { // method call result = getSquare(i) System.out.println("Square of " + i + " is : " + result); } } }

When you run the program, the output will be:

Square of 1 is : 1 Square of 2 is : 4 Square of 3 is : 9 Square of 4 is : 16 Square of 5 is : 25

In above code snippet, the method getSquare() takes int as a parameter. Based on the argument passed, the method returns the squared value of it.

Here, argument i of type int is passed to the getSquare() method during method call.

result = getSquare(i);

The parameter x accepts the passed argument [in the function definition getSquare(int x)].

return i * i; is the return statement. The code returns a value to the calling method and terminates the function.
Did you notice, we reused the getSquare method 5 times?
What are the advantages of using methods?

The main advantage is code reusability. You can write a method once, and use it multiple times. You do not have to rewrite the entire code each time. Think of it as, "write once, reuse multiple times."

Methods make code more readable and easier to debug. For example, getSalaryInformation() method is so readable, that we can know what this method will be doing than actually reading the lines of code that make this method.

# data[].attributes.attachment_link.description
In mathematics, you might have studied about functions. For example, is a function that returns squared value of x. If x = 2, then f(2) = 4 If x = 3, f(3) = 9 and so on. Similarly, in programming, a function is a block of code that performs a specific task.

# data[].attributes.body
For arrays of ints, chars and Strings:
1) check if an array contains given element
2) calculate the sum
3) calculate an average
4) find max / min value

# data[].attributes.body
code from class (2018.10.04)

# data[].attributes.attachment_link.readable_text
package bb;

import java.util.Arrays;

public class Main {

    public static void main(String[] args) {
//        Ctrl + /

        String[] names = {"Adama", "Ola", "Ela", "Ewa", "adam", ""};
//        1. Check if the array contains given string.
        String name = "Adam";
        boolean isPresent = false;
        for (int i = 0; i < names.length; i++) {
            if (names[i].equals(name)){  // use .equals() instead of ==
                isPresent = true;
            }
        }
        System.out.println(isPresent);

//        2. Calculate how many times given name is present in the array.
        int count = 0;
        for (int i = 0; i < names.length; i++) {
            if (names[i].equalsIgnoreCase(name)){
                count++;
            }
        }
        System.out.println(count);

//        3. Calculate how many times the array contains name starting with given letter.
        char givenChar = 'A';
        String givenLetter = "A";
        int countString = 0;
        for (int i = 0; i < names.length; i++) {
/*            if (names[i].toLowerCase().startsWith(givenLetter.toLowerCase())){
                countString++;
            }*/
            if ( ! names[i].isEmpty() && names[i].substring(0, 1).equalsIgnoreCase(givenLetter)){
                countString++;
            }
        }
        System.out.println(countString);

//        4. Construct an array with names starting with given letter.
        String[] chosenNames = new String[countString];
        int chosenCount = 0;
        for (int i = 0; i < names.length; i++) {
            if (names[i].toLowerCase().startsWith(givenLetter.toLowerCase())){
                chosenNames[chosenCount] = names[i];
                chosenCount++;
            }
        }
        System.out.println(Arrays.toString(chosenNames));

//        5. Find the longest word in the array.
        String longestString = "";
        int maxLength = -1;
        for (int i = 0; i < names.length; i++) {
            if (maxLength < names[i].length()  ){
                maxLength = names[i].length();
                longestString = names[i];
            }
        }
        System.out.println(longestString + ": " + maxLength);


//        6. Find the shortest word(!) in the array.
//        7. Correct names in the array.
//        8. Check how many times given letter is present in the array.


    }
}

# data[].attributes.headline
Classic Puzzle - Easy (October challenge and homework)

# data[].attributes.subject
Classic Puzzle - Easy (October challenge and homework)

# data[].attributes.body
The Descent,
Temperatures,
Power of Thor,
Chuch Norris,
Mars Lander,
ASCII Art,
MIME Type,
Defibrillators,
Horse-racing Duals

https://www.codingame.com

# data[].attributes.attachment_link.readable_text
Practice & learn the fun way

Practice pure code

Learn new concepts by solving fun challenges in 25+ languages addressing all the hot programming topics.

Learn from the best

In a matter of hours, discover new languages, algorithms or tricks in courses crafted by top developers.

Become the expert

Our approach has been designed to lead advanced developers to the next level.
Level up your skills
We're smarter together

Belong

We're developers just like you.

Join the community and feel at home.

Get insights

Meet like-minded enthusiasts, ask for help and have your code reviewed. We're here for each other.

Be inspired

Compare solutions and learn tips from the best programmers.
Join the community
Challenge your friends

Play

Have fun with friends, schoolmates or co-workers on multiplayer programming games and show them who's the boss!

Compete

Join our international online programming contests for fun, prizes or glory.

Rise & Shine

Hit the Leaderboard and get recognition from your peers.
Rediscover fun
Get hired at awesome companies

Build up

Strengthen your developer profile as you code and play.

Control

Choose which companies can see your profile and set your conditions.

Stand out

Prove your worth as a developer and get noticed by top companies for a career change and jobs you deserve.
Get the job you deserve

# data[].attributes.attachment_link.title
Coding Games and Programming Challenges to Code Better

# data[].attributes.attachment_link.description
Learn new concepts by solving fun challenges in 25+ languages addressing all the hot programming topics. In a matter of hours, discover new languages, algorithms or tricks in courses crafted by top developers. Our approach has been designed to lead advanced developers to the next level.

# data[].attributes.body
Past papers

# data[].attributes.body
1. Take a number n from the user. Print n-first elements of the Fibonacci sequence.
2. Collect two numbers a and b from the user. Compute a^b.
3. Take another number n from the user. Execute previous exercise n-times.
4. Produce triangles filled with numbers and stars (normal and upside-down).
5*. Create the Pascal triangle (normal and colorised).

# data[].attributes.body
1. For a given array of numbers find:
a. the sum of the elements
b. the average value (arithmetic mean)
c. the geometric mean
d. the standard deviation
e. the max value
f. the min value
g*. the mode (the value that appears most often)
2. For a given array of numbers and a number:
a. check if this numer is present in the array or not (T/F)
b. calculate how many times
c. return index of first appearance
d. return indexes of all appearances
https://docs.oracle.com/javase/8/docs/api/java/util/Arrays.html
Important methods: equals, fill, sort, toString.

# data[].attributes.attachment_link.description
Java Arrays - Learn Java in simple and easy steps starting from basic to advanced concepts with examples including Java Syntax Object Oriented Language, Methods, Overriding, Inheritance, Polymorphism, Interfaces, Packages, Collections, Networking, Multithreading, Generics, Multimedia, Serialization, GUI.

# data[].attributes.body
1. Add numbers from 1 to 100 inclusive.
2. Add even numbers from 1 to 100 inclusive.
3. Add numbers from 1 to 100 that are divided by 7.

# data[].attributes.attachment_link.readable_text
Loop is used in programming to repeat a specific block of code until certain condition is met (test expression is false).

Loops are what makes computers interesting machines. Imagine you need to print a sentence 50 times on your screen. Well, you can do it by using print statement 50 times (without using loops). How about you need to print a sentence one million times? You need to use loops.

It's just a simple example. You will learn to use while and do..while loop to write some interesting programs in this article.

Java while Loop

The syntax of while loop is:

while (testExpression) {
    // codes inside body of while loop
}

How while loop works?

The test expression inside parenthesis is a boolean expression.

If the test expression is evaluated to true,

statements inside the while loop are executed.

then, the test expression is evaluated again.

This process goes on until the test expression is evaluated to false.

If the test expression is evaluated to false,

while loop is terminated.

Flowchart of while Loop

Example 1: while Loop

// Program to print line 10 times class Loop { public static void main(String[] args) { int i = 1; while (i <= 10) { System.out.println("Line " + i); ++i; } } }

When you run the program, the output will be:

Line 1 Line 2 Line 3 Line 4 Line 5 Line 6 Line 7 Line 8 Line 9 Line 10

Notice, ++i; statement inside the while loop. After 10 iterations, variable i will be 11. Then, the test expression i <= 10 is evaluated to false and while loop terminates.

Example 2: Java while Loop

// Program to find the sum of natural numbers from 1 to 100. class AssignmentOperator { public static void main(String[] args) { int sum = 0, i = 100; while (i != 0) { sum += i; // sum = sum + i; --i; } System.out.println("Sum = " + sum); } }

When you run the program, the output will be:

Here, the variable sum is initialized to 0 and i is initialized to 100. In each iteration of while loop, variable sum is assigned sum + i, and the value of i is decreased by 1 until i is equal to 0. For better visualization,

1st iteration: sum = 0+100 = 100, i = 99
2nd iteration: sum = 100+99 = 199, i = 98
3rd iteration: sum = 199+98 = 297, i = 97
... .. ...
... .. ...
99th iteration: sum = 5047+2 = 5049, i = 1
100th iteration: sum = 5049+1 = 5050, i = 0

To learn more about test expression and how it is evaluated, visit relational and logical operators.

Java do...while Loop

The do...while loop is similar to while loop with one key difference. The body of do...while loop is executed for once before the test expression is checked.

The syntax of do..while loop is:

do {
   // codes inside body of do while loop
} while (testExpression);

How do...while loop works?

The body of do...while loop is executed once (before checking the test expression). Only then, the test expression is checked.

If the test expression is evaluated to true, codes inside the body of the loop are executed, and the test expression is evaluated again. This process goes on until the test expression is evaluated to false.

When the test expression is false, the do..while loop terminates.

Flowchart of do...while Loop

Example 3: do...while Loop

The program below calculates the sum of numbers entered by the user until user enters 0.

To take input from the user, Scanner object is used. Visit Java Basic Input to learn more on how to take input from the user.

import java.util.Scanner; class Sum { public static void main(String[] args) { Double number, sum = 0.0; Scanner input = new Scanner(System.in); do { System.out.print("Enter a number: "); number = input.nextDouble(); sum += number; } while (number != 0.0); System.out.println("Sum = " + sum); } }

When you run the program, the output will be:

Enter a number: 2.5 Enter a number: 23.3 Enter a number: -4.2 Enter a number: 3.4 Enter a number: 0 Sum = 25.0

Infinite while Loop

If the test expression never evaluates to false, the body of while and do..while loop is executed infinite number of times (at least in theory). For example,

while (true) { // body of while loop }

Let's take another example,

 int i = 100; while (i == 100) { System.out.print("Hey!"); }

The infinite do...while loop works in similar way like while loop.

# data[].attributes.attachment_link.description
Loop is used in programming to repeat a specific block of code until certain condition is met (test expression is false). Loops are what makes computers interesting machines. Imagine you need to print a sentence 50 times on your screen. Well, you can do it by using print statement 50 times (without using loops).

# data[].attributes.body
1. JDK 10 (Java Development Kit)
http://www.oracle.com/technetwork/java/javase/downloads/jdk10-downloads-4416644.html
2. IntelliJ IDEA Community (IDE)
https://www.jetbrains.com/idea/download/#section=windows

# data[].attributes.body
https://ideone.com/

https://www.tutorialspoint.com/compile_java_online.php

# data[].attributes.attachment_link.readable_text
Java Variables

A variable is a location in memory (storage area) to hold data.

To indicate the storage area, each variable should be given a unique name (identifier). Learn more about Java identifiers.

How to declare variables in Java?

Here's an example to declare a variable in Java.

int speedLimit = 80;

Here, speedLimit is a variable of int data type, and is assigned value 80. Meaning, the speedLimit variable can store integer values. You will learn about Java data types in detail later in the article.

In the example, we have assigned value to the variable during declaration. However, it's not mandatory. You can declare variables without assigning the value, and later you can store the value as you wish. For example,

int speedLimit;
speedLimit = 80;

The value of a variable can be changed in the program, hence the name 'variable'. For example,

int speedLimit = 80;
... .. ...
speedLimit = 90;

Java is a statically-typed language. It means that all variables must be declared before they can be used.

Also, you cannot change the data type of a variable in Java within the same scope. What is variable scope? Don't worry about it for now. For now, just remember you cannot do something like this.

int speedLimit = 80;
... .. ...
float speedLimit;

To learn more, visit: Can I change declaration type for a variable in Java?

Rules for Naming Variables in Java

Java programming language has its own set of rules and conventions for naming variables. Here's what you need to know:

Variables in Java are case-sensitive.

A variable's name is a sequence of Unicode letters and digits. It can begin with a letter, $ or _. However, it's convention to begin a variable name with a letter. Also, variable name cannot use whitespace in Java.

When creating variables, choose a name that makes sense. For example, score, number, level makes more sense than variable name such as s, n, and l.

If you choose one word variable name, use all lowercase letters. For example, it's better to use speed rather than SPEED, or sPEED.

If you choose variable name having more than one word, use all lowercase letters for the first word and capitalize the first letter of each subsequent word. For example, speedLimit.

There are 4 types of variables in Java programming language:

Instance Variables (Non-Static Fields)

Class Variables (Static Fields)

Local Variables

Parameters

You will learn about in later chapters. If you are interested to learn more about it now, visit Java Variable Types.

Java Primitive Data Types

As mentioned above, Java is a statically-typed language. This means that, all variables must be declared before they can be used.

int speed;

Here, speed is a variable, and the data type of the variable is int. The int data type determines that the speed variable can only contain integers.

In simple terms, a variable's data type determines the values a variable can store. There are 8 data types predefined in Java programming language, known as primitive data types.

In addition to primitive data types, there are also referenced data types in Java (you will learn about it in later chapters).

8 Primitive Data Types

boolean

The boolean data type has two possible values, either true or false.

Default value: false.

They are usually used for true/false conditions.

Example:

class BooleanExample { public static void main(String[] args) { boolean flag = true; System.out.println(flag); } }

When you run the program, the output will be:

byte

The byte data type can have values from -128 to 127 (8-bit signed two's complement integer).

It's used instead of int or other integer data types to save memory if it's certain that the value of a variable will be within [-128, 127].

Default value: 0

Example:

class ByteExample { public static void main(String[] args) { byte range; range = 124; System.out.println(range); // Error code below. Why? // range = 200 } }

When you run the program, the output will be:

short

The short data type can have values from -32768 to 32767 (16-bit signed two's complement integer).

It's used instead of other integer data types to save memory if it's certain that the value of the variable will be within [-32768, 32767].

Default value: 0

Example:

class ShortExample { public static void main(String[] args) { short temperature; temperature = -200; System.out.println(temperature); } }

When you run the program, the output will be:

int

The int data type can have values from -2³¹ to 2³¹-1 (32-bit signed two's complement integer).

If you are using Java 8 or later, you can use unsigned 32-bit integer with minimum value of 0 and maximum value of 2³²-1. If you are interested in learning more about it, visit: How to use the unsigned integer in java 8?

Default value: 0

Example:

class IntExample { public static void main(String[] args) { int range = -4250000; System.out.println(range); } }

When you run the program, the output will be:

long

The long data type can have values from -2⁶³ to 2⁶³-1 (64-bit signed two's complement integer).

If you are using Java 8 or later, you can use unsigned 64-bit integer with minimum value of 0 and maximum value of 2⁶⁴-1.

Default value: 0

Example:

class LongExample { public static void main(String[] args) { long range = -42332200000L; System.out.println(range); } }

When you run the program, the output will be:

-42332200000

Notice, the use of L at the end of -42332200000. This represents that it's an integral literal of long type. You will learn about integral literals later in this article.

double

The double data type is a double-precision 64-bit floating point.

It should never be used for precise values such as currency.

Default value: 0.0 (0.0d)

Example:

class DoubleExample { public static void main(String[] args) { double number = -42.3; System.out.println(number); } }

When you run the program, the output will be:

float

class FloatExample { public static void main(String[] args) { float number = -42.3f; System.out.println(number); } }

When you run the program, the output will be:

Notice that, we have used -42.3f instead of -42.3in the above program. It's because -42.3 is a double literal. To tell compiler to treat -42.3 as float rather than double, you need to use f or F.

char

It's a 16-bit Unicode character.

The minimum value of char data type is '\u0000' (0). The maximum value of char data type is ''.

Default value: '\u0000'

Example:

class CharExample { public static void main(String[] args) { char letter = 'Q'; System.out.println(letter); } }

When you run the program, the output will be:

You get the output Q because the Unicode value of Q is 'Q'.

Here is another example:

class CharExample { public static void main(String[] args) { char letter1 = '9'; System.out.println(letter1); char letter2 = 65; System.out.println(letter2); } }

When you run the program, the output will be:

When you print letter1, you will get 9 because letter1 is assigned character '9'.

When you print letter2, you get A because the ASCII value of 'A' is 65. It's because java compiler treats character as integral type. Learn more about ASCII.

Java also provides support for character strings via java.lang.String class. Here's how you can create a String object in Java:

myString = "Programming is awesome";

Java String is an important topic which you will learn in detail in later chapters. However, if you are not a newbie in programming and want to learn it now, visit Java String.

Java literals

To understand literals, let's take an example to assign value to a variable.

boolean flag = false;

Here,

boolean - is data type.

flag - is variable

false - is literal.

A Literal is the source code representation of a fixed value.

Values like 1.5, 4, true, 'P' that appears directly in a program without requiring computation are literals.

In the above example, flag is a variable. Since, it's a boolean type variable, it may store either false or true. For compiler to understand it, it requires computation. However, literals like -5, 'a', true represents fixed value.

Integer Literals

Integer literals are used to initialize variables of integer data types byte, short, int and long.

If an integer literal ends with l or L, it's of type long. Tip: it is better to use L instead of l.

// Error! literal 42332200000 of type int is out of range
long myVariable1 = 42332200000;

// 42332200000L is of type long, and it's not out of range
long myVariable2 = 42332200000L;

Integer literals can be expressed in decimal, hexadecimal and binary number systems.

The numbers starting with prefix 0x represents hexadecimal. Similarly, numbers starting with prefix 0b represents binary.

// decimal
int decNumber = 34;

// 0x represents hexadecimal
int hexNumber = 0x2F;

// 0b represents binary
int binNumber = 0b10010;

Floating-point Literals

Floating-point literals are used to initialize variables of data type float and double.

If a floating-point literal ends with f or F, it's of type float. Otherwise, it's of type double. A double type can optionally end with D or d. However, it's not necessary.

They can also be expressed in scientific notation using E or e.

 class DoubleExample { public static void main(String[] args) { double myDouble = 3.4; float myFloat = 3.4F; // 3.445*10^2 double myDoubleScientific = 3.445e2; System.out.println(myDouble); System.out.println(myFloat); System.out.println(myDoubleScientific); } }

When you run the program, the output will be:

Character and String Literals

They contain Unicode (UTF-16) characters.

For char literals, single quotation is used. For example, 'a', 'đ' etc.

For String literals, double quotation is used. For example, "programming", "Java 8"

Java also supports a few special escape sequences. For example, \b (backspace), \t (tab), \n (line feed), \f (form feed), \r (carriage return), \" (double quote), \' (single quote), and \\ (backslash).

class DoubleExample { public static void main(String[] args) { char myChar = 'g'; char newLine = '\n'; String myString = "Java 8"; System.out.println(myChar); System.out.println(newLine); System.out.println(myString); } }

When you run the program, the output will be:

# data[].attributes.attachment_link.title
Java Variables and (Primitive) Data Types

# data[].attributes.attachment_link.description
A variable is a location in memory (storage area) to hold data. To indicate the storage area, each variable should be given a unique name (identifier). Learn more about Java identifiers. Here's an example to declare a variable in Java. int speedLimit = 80; Here, speedLimit is a variable of int data type, and is assigned value 80.

# data[].attributes.body
+ tutorials
https://javastart.pl/static/darmowy-kurs-java/
+ tutorials
https://www.tutorialspoint.com/java/
+ tutorials
https://netjs.blogspot.com/2015/04/java-basics.html
+ video tutorials
https://www.youtube.com/watch?v=Hl-zzrqQoSE&list=PLFE2CE09D83EE3E28
+ documentation
https://docs.oracle.com/javase/tutorial/

# data[].attributes.body
1. Java. Fundamentals

https://helion.pl/ksiazki/java-podstawy-wydanie-x-cay-s-horstmann,javp10.htm
2. Java. Head first

https://helion.pl/ksiazki/java-rusz-glowa-wydanie-ii-kathy-sierra-bert-bates,javrg2.htm

# data[].attributes.body
Construct a truth table for the following Boolean expressions:
(A AND B) NOR C
A XOR (B OR C)
NOT (A OR B) AND (A NOR B)
(NOT A OR A) XOR (B AND NOT B)
((P NOR Q) NAND S) AND (P XOR S)

You can check your answers here:
http://www.wolframalpha.com/widget/widgetPopup.jsp?p=v&id=4c86f3bbcab249f879058d1825887571&title=Boolean%20Algebra%20Calculator&theme=green

More info here:
http://ib.compscihub.net/wp-content/uploads/2018/06/2.1.12.pdf

# data[].attributes.headline
Exercises (conditionals and math functions)

# data[].attributes.subject
Exercises (conditionals and math functions)

# data[].attributes.body
1. Print a sign of a given number (whether it is positive, negative or zero).
2. Give a test grade (A, B, C, D or F) for a student with marks from 0 to 100. State your own boundaries.
2. Find max value from 3 given numbers.
3. Find min value from 4 given numbers.
4. Solve the quadratic equation from the coefficients.
5. Test whether 3 given numbers can be the sides of a triangle (do they respect the triangular inequality?). Check whether this is a right triangle or not. Compute its area, perimeter and angles.
6*. Print number of days from a given month and year. Note a leap year.  Compute the date of the next day.

# data[].attributes.attachment_link.description
By default many of the Math methods simply call the equivalent method in StrictMath for their implementation. Code generators are encouraged to use platform-specific native libraries or microprocessor instructions, where available, to provide higher-performance implementations of Math methods. Such higher-performance implementations still must conform to the specification for Math.

# data[].attributes.attachment_link.readable_text
Welcome to our International Baccalaureate Diploma's Computer Science resource site.

This site is for students taking the Computer Science course (either HL or SL) as a part of the IB Diploma. The site provides teaching & learning resources for eight key topics of the HL course (topics 1 to 7 and Option D - OOP).

Having scoured the web for information and resources regarding the Computer Science SL/HL course and found very little, we decided to collate all known resources, add in a few of our own and publish it for all to see and use. If we have accidentally used a resource that you own without your consent, please let us know and we will take it down immediately.

Also, please send us your resources so that we can add/update the ones posted here. By working together, we hope to support teachers and benefit students across the world.

Happy computing!
Chris Coetzee
Head of Department: Computer Science

# data[].attributes.attachment_link.title
IB CompSci Hub - Resources for teaching the IB Computer Science HL and SL courses

# data[].attributes.attachment_link.description
Welcome to our International Baccalaureate Diploma's Computer Science resource site. This site is for students taking the Computer Science course (either HL or SL) as a part of the IB Diploma. The site provides teaching & learning resources for eight key topics of the HL course (topics 1 to 7 and Option D - OOP).

# data[].attributes.body
Strings:
{"Adam", "Ola", "Ela", "Ewa", "adam", ""}
1. Check if the array contains given string.
2. Calculate how many times given name is present in the array.
3. Calculate how many times the array contains name starting with given letter.
4. Construct an array with names starting with given letter.
5. Find the longest word in the array.
6. Find the shortest word(!) in the array.
7. Correct names in the array.
8. Check how many times given letter is present in the array.

User input:
"  aDam"
"nowak, andrzej "
" 600 600-600 "
9. Transform user inputs to more appropriate form.

Important methods:
charAt, concat, compareTo, contains, endsWith, equals, indexOf, isEmpty, length, replace, split, startsWith, substring, toLowerCase, toUpperCase, trim.

# data[].attributes.attachment_link.description
The implementation of the string concatenation operator is left to the discretion of a Java compiler, as long as the compiler ultimately conforms to The Java™ Language Specification. For example, the javac compiler may implement the operator with StringBuffer, StringBuilder, or java.lang.invoke.StringConcatFactory depending on the JDK version.