David Prieto
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights New
    • Engagement control
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Note Insights Versions and GitHub Sync Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       Owned this note    Owned this note      
    Published Linked with GitHub
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    # Arrays in Java Arrays in Java work similar as we have discussed in pseudocode. They are linear, they have indexes, they cannot change in size. ```java= int[] numbers = {3, 45, 522, 1, 1, 9}; ``` The length or size of the array is the number of elements, in the case of `numbers` is 6. The index of `3` is `0`. The value of `numbers[2]` is `522`. The maximum index is always equal to [nameOfThArray].length -1. In this case is 5, whose value is 9. We can also not now the values of the numbers: ```java= int[] numbers = int[399]; ``` This is an arry of 399 elements. ## Loop through an array We usually use for loop this way: ```java= int[] numbers = {3, 45, 522, 1, 1, 9}; for (int i = 0; i < numbers.length; i++){ //do something //we use numbers[i] to access the possible values //we use i to access the possible indexes } ``` There is the possibility of using for each. ```java= int[] numbers = {3, 45, 522, 1, 1, 9}; for (int number:numbers){ //to access the possible values we use "number" } ``` I suggest don't use it unless you're too deep into python More reference on this: https://www.w3schools.com/java/java_foreach_loop.asp ## Array of objects It's very common in classes that they have an array of Objects instead of primitive. For example, makes sense that a IBClass should have an array of IBStudent ```java= Student[] students = new Student[100]; ``` ### Counter Variables in IB In IB you will find **scenarios** where they use arrays. In this scenarios they need to handle sometimes that the number of objects is variable, for example the number of students in a subject may vary from subject to subject. If we have an AirCompany, it may have a variable number of Planes in their fleet. So to deal with that you will find **counter variables**. In these cases you will have an array of objects that it's over the limit the maximum size of the actual model (so the program doesn't get out of elements). For example in the class "Subject" we might find an array of 50 students (Because 50 is already too much in IB), if we talk about a parking lot we might have an array of Cars that are entering that is just the size of the parking or in the case of a fleet of an air company we can go with 200 planes (that's already a big number). Counter variables are int that they are related to an array and count how many elements we have in that oversize array. For example: ```java= private Plane[] fleet = new Plane[200]; private int numberOfPlanes; //counter Variable ``` This counter variable sometimes has an accessor but it shouldn't have a mutator. ### Arrays in the constructor We don't usually have the array as a variable in the constructor, but you might find it. ### Encapsulation of the array We don't have direct accessors and mutators of the array. You won't see, in the case of AirCompany methods like "getFleet" or "setFleet". This is because we want to make sure that AirCompany has full control of fleet and also the counter variable. ### "Accessor" of one element of the array This accessor is different from regular accessors because they require a parameter. The index of the element that we're looking for. They have to return the object. ```java= public Plane getPlane(int index) { if (index >= 0 && index < numberOfPlanes) { return fleet[index]; } } ``` ### "Mutator" of one element of the array: AddElement() ```java= public void addPlane(Plane plane){ fleet[numberOfPlanes] = plane; numberOfPlanes++; } ``` ### "Remover" of one element of the array. This is different depending of the context. I've seen this as part of the difficult question to implement (7 marks). The idea can be "find one element, then take it out, reorder the rest of the elements so there is no extra space, update the counter". If they ask this in an exam the will give you the specific instructions to construct the method. The easier way is the input is the index. Construct the method removePlane(index) in AirCompany that given a specific index, if it's valid it's going to update the number of planes and create an array that keeps the same order and returns the deleted Plane. ```java= public Plane removePlane(int index){ //checking if valid if(index < 0 || index >= this.numberOfPlanes) { return null; //if the index is out of bound we return null } //we take the first plane before deleting it Plane deletedPlane = fleet[index]; //we loop through the only part of the array that is going to shift (move one less) for(int i = index; i < numberOfPlanes -1; i++) { fleet[i] = fleet[i+1]; } //we put the last one to null fleet[numberOfPlanes-1] = null; numberOfPlanes --; //we return the Plane that we reserved before return deletedPlane; } ``` Quite a mess, huh? Let's do the next twist Remove a plane given a specific attribute (the first one that we find) Construct the method removePlane(index) in AirCompany that given a specific modelName, if it's valid it's going to update the number of planes and create an array that keeps the same order and returns the deleted Plane. ```java= public Plane removePlane(String modelName){ //let's supose that we don't have the plane in the array, that would be that the index is -1 int index = -1; //find the plane for (int i = 0; i<numberOfPlanes; i++) //loop through the array //notice that we use the counter variable { if (fleet[i].getModelName.equals(modelName)) { index = i; break; //if we find the value we don't need to keep looking for it } } //check if we have found something if (index == -1) { return null; } //we loop through the only part of the array that is going to shift (move one less) for(int i = index; i < numberOfPlanes -1) { fleet[i] = fleet[i++]; } //we put the last one to null fleet[numberOfPlanes-1] = null; numberOfPlanes --; //we return the Plane that we reserved before return deletedPlane; } ``` Another way of implementing the same method. Both are valid but the second one is more complicated to understand and it's a bit more oneliner ```java= public Plane removePlane(String modelName){ //find the plane for (int x = 0; x<numberOfPlanes; x++) { if (fleet[i].getModelName().equals(modelName)) { //if found do stuff Plane deletedPlane = fleet[i]; //rearrange for(int i = index; i < numberOfPlanes -1) { fleet[i] = fleet[i++]; } //we put the last one to null fleet[numberOfPlanes-1] = null; numberOfPlanes --; //we return the Plane that we reserved before return deletedPlane; } } //if not found we arrive here return null; } } ``` ### "Finder" in the array Sometimes one of the methods that you can find in an class that has an array (or any given collection) is a "finder". A method that tries to find in that array a specific element that complies with a specific characteristic. This types of methods usually will have the parameter (or parameters) the finding criteria and they usually return the object itself. This is specified in the statement. They usually loop through the array and inside has an if clause with the specific condition that needs to meet. Construct the method findPlaneByPassengerCapacity() that given a given passengerCapacity returns the first plane in the fleet that complies with that value. ```java= public Plane findPlaneByModelName(String modelName) { for (int i = 0; i<numberOfPlanes; i++) //loop through the array //notice that we use the counter variable { if (fleet[i].getModelName.equals(modelName)) { return fleet[i]; } } return null; } ``` Construct the method findPlaneByPassengerCapacity() that given a given passengerCapacity returns the first plane in the fleet that complies with that value. ```java= public Plane findPlaneByPassengerCapacity(int passengerCapacity){ for (int i = 0; i<numberOfPlanes; i++) { if (fleet[i].getPassengerCapacity() == passengerCapacity) { return fleet[i]; } } return null; } ``` ### Counting exercise A specific version of the "finder" methods where you count elements that has a specific propierty. The idea is that you initialize the counter, you loop through the array, you add 1 to the counter then you return the counter. Construct a method planesAvailable in the AirCompany that counts how many planes in their fleet are active at any given time and **returns** that value. ```java= public int planesAvailable() { int count = 0; for (int i = 0; i < numberOfPlanes; i++){ if (fleet[i].isAvailable()) { count++; } //end if } //end loop return count; } ``` ### Driver class exercises This is very common in exercises in OOP exams. They give you the whole code and they say you that in the driver or main class you will have some code. Then your task is to be able to know what would be the output. ```java= public class Main { public static void main(String[] args) { AirCompany ryanair = new AirCompany("Ryanair"); System.out.println(ryanair.getName()); System.out.println(ryanair.getNumberOfPlanes()); //one way of adding a new plane Plane plane = new Plane("A380"); ryanair.addPlane(plane); //another way of adding a plane ryanair.addPlane(new Plane("Concorde")); System.out.println(ryanair.getNumberOfPlanes()); System.out.println(ryanair.getPlane(1).getModelName()); Plane plane2 = new Plane("A380"); System.out.println(ryanair.findPlaneByModelName("Concorde").isActive()); } } ``` Output 0 2 Concorde true Second exercise: --- ```java= import java.util.*; public class Main { public static void main(String[] args) { AirCompany ryanair = new AirCompany("Ryanair"); AirCompany vueling = new AirCompany("Vueling"); Plane plane1 = new Plane ( "Boeing", "747", true , 12,230 ); Plane plane2 = new Plane ( "Airbus", "380", true , 7, 123 ); ryanair.addPlane(plane1); ryanair.addPlane(plane2); vueling.addPlane(new Plane("Concorde")); ryanair.addPlane(new Plane("4433")); System.out.println(ryanair.getNumberOfPlanes()); System.out.println(vueling.getPlane(0).getCrewNeeded()); System.out.println(ryanair.getPlane(1).getManufacturer()); } } ``` Output: 3 5 Airbus :::info I suggest to use one of the scenario and tweak it and try to see what happens using the compiler. ::: #### Scenario of reference. AirCompany and plane These are the classes that I'm using as context here during May2025 Main.Java: ```java= import java.util.*; public class Main { public static void main(String[] args) { AirCompany ryanair = new AirCompany("Ryanair"); AirCompany vueling = new AirCompany("Vueling"); Plane plane1 = new Plane ( "Boeing", "747", true , 12,230 ); Plane plane2 = new Plane ( "Airbus", "380", true , 7, 123 ); ryanair.addPlane(plane1); ryanair.addPlane(plane2); vueling.addPlane(new Plane("Boeing", "Concorde", true, 14, 88)); ryanair.addPlane(new Plane("4433")); System.out.println(ryanair.getNumberOfPlanes()); System.out.println(vueling.getPlane(0).getCrewNeeded()); System.out.println(ryanair.getPlane(1).getManufacturer()); } } ``` AirCompany.java: ```java= public class AirCompany { private String name; private Plane[] fleet = new Plane[200]; private int numberOfPlanes; //counter Variable public AirCompany() { this.name = "Default Name"; } public AirCompany(String name) { this.name = name; this.numberOfPlanes = 0; } public void addPlane(Plane plane){ fleet[numberOfPlanes] = plane; numberOfPlanes++; } public Plane getPlane(int index) { if (index >= 0 && index < numberOfPlanes) { return fleet[index]; } return null; } public Plane findPlaneByModelName(String modelName) { for (int i = 0; i<numberOfPlanes; i++) //loop through the array //notice that we use the counter variable { if (fleet[i].getModelName().equals(modelName)) { return fleet[i]; } } return null; } public Plane findPlaneByPassengerCapacity(int passengerCapacity){ for (int i = 0; i<numberOfPlanes; i++) { if (fleet[i].getPassengerCapacity() == passengerCapacity) { return fleet[i]; } } return null; } public int planesActive() { int count = 0; for (int i = 0; i < numberOfPlanes; i++){ if (fleet[i].isActive()) { count++; } //end if } //end loop return count; } public String getName() { return this.name; } public void setName(String name){ this.name = name; } public int getNumberOfPlanes(){ return this.numberOfPlanes; } } ``` Plane.java: ```java= public class Plane { private int length; private int passengerCapacity; private int crewNeeded; private String manufacturer; private String modelname; private boolean active; public Plane ( String manufacturer, String modelname, boolean active, int crewNeeded, int passengerCapacity ){ this.manufacturer = manufacturer; this.modelname = modelname; this.active = active; this.crewNeeded = crewNeeded; this.passengerCapacity = passengerCapacity; this.length = length; } public Plane (String modelname){ this.modelname = modelname; this.length = 30; this.active = true; this.crewNeeded = 5; this.passengerCapacity = 40; } public int getPassengerCapacity (){ return this.passengerCapacity; } public void setPassengerCapacity (int passengerCapacity){ this.passengerCapacity = passengerCapacity; } public int getCrewNeeded(){ return this.crewNeeded; } public void setcrewNeeded(int crewNeeded){ this.crewNeeded = crewNeeded; } public String getManufacturer(){ return this.manufacturer; } public void setManufacturer(String manufacturer){ this.manufacturer = manufacturer; } public String getModelName(){ return this.modelname; } public boolean isActive(){ return this.active; } public void setActive (boolean active){ this.active = active; } } ``` ## Array exercises in Java https://www.codesdope.com/practice/java-array/ Nice option with the olutions http://www.eecs.qmul.ac.uk/~pc/teaching/introprogramming/week7/exercises7.html # Arrays in c++ https://www.w3resource.com/cpp-exercises/array/index.php

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully