Curriculum
Course: Java Basic
Login

Curriculum

Java Basic

Java Home

0/1

Java Introduction

0/1

Java Get Started

0/1

Java Syntax

0/1

Java Comments

0/1

Java Type Casting

0/1

Java Operators

0/1

Java Booleans

0/1

Java Switch

0/1

Java Break / Continue

0/1

Java Errors and Exception

0/1
Text lesson

put()

Example

Insert entries into a map.

import java.util.HashMap;
public class Main {
  public static void main(String[] args) {
    HashMap<String, String> capitalCities = new HashMap<String, String>();
    capitalCities.put("England", "London");
    capitalCities.put("Germany", "Berlin");
    capitalCities.put("Norway", "Oslo");
    capitalCities
.put("USA", "Washington DC");             
   System.out.println(capitalCities);
  }
}

Definition and Usage

The put() method inserts an entry into the map. If an entry with the same key already exists, its value will be replaced.

Syntax

public V put(K key, V value)

K and V represent the data types of the keys and values stored in the map.

Parameter Values

Parameter

Description

key

Required: Specifies the key of the entry.

value

Required: Specifies the value of the entry.

Technical Details

Returns:

If an entry already existed with the specified key, it returns the value of that entry before overwriting it; otherwise, it returns null.