Skip to main content
Programming from zero

Print a server's hostname and IP from variables

easyFirst steps

Problem statement

Last problem, the text you printed was fixed, typed straight into the print line. Most of the time you want to print something that can change, like a server's hostname or IP address you looked up moments ago. For that, you store the value in a variable first, then print the variable.

  • Python: hostname = "web-01"
  • Java: String hostname = "web-01";
  • C++: std::string hostname = "web-01";

A variable is just a name pointing at a value. Once it's set, you can use that name anywhere instead of retyping the value.

flowchart LR A["hostname = 'web-01'"] --> C[Combine into one line] B["ip = '10.0.0.5'"] --> C C --> D["print: web-01 - 10.0.0.5"] classDef store fill:#DBEAFE,stroke:#2563EB,color:#1E3A8A classDef combine fill:#E0E7FF,stroke:#4F46E5,color:#312E81 classDef output fill:#D1FAE5,stroke:#059669,color:#065F46 class A store class B store class C combine class D output

Common mistake: in Java and C++, forgetting the type keyword before the variable name.

  • Wrong (Java): hostname = "web-01";
  • Right (Java): String hostname = "web-01";

Python doesn't need a type keyword at all, which is why this mistake only bites you in Java and C++ - the compiler won't know what kind of value hostname is supposed to hold, and refuses to build.

Your task: create two variables, hostname = "web-01" and ip = "10.0.0.5", then print them on one line with - between them.

Expected output:

TEXT
web-01 - 10.0.0.5

Approach

Each language needs the value's type stated differently:

  • Python doesn't ask for a type at all. hostname = "web-01" just works.
  • Java and C++ need the type written before the name: String hostname = ... in Java, std::string hostname = ... in C++ (this needs #include <string> at the top).

To combine two variables into one line of text, each language has its own way to join, or concatenate, strings:

  • Python: an f-string, print(f"{hostname} - {ip}") - see the f-string docs.
  • Java: the + operator, System.out.println(hostname + " - " + ip);
  • C++: the << operator again, chained: std::cout << hostname << " - " << ip << std::endl;
hostname = "web-01"
ip = "10.0.0.5"
print(f"{hostname} - {ip}")