← Back to Advanced Java Course | Chapter 7: Networking & APIs | Lesson 1 of 4

Java Networking Basics

Networking basics are how programs find and talk to other computers using addresses, like sending letters to a house. Java can look up addresses and read from web pages.

What is an IP Address and URL?

The java.net package contains the core classes for network communication in Java. InetAddress represents IP addresses (both IPv4 and IPv6), and the URL class represents a Uniform Resource Locator, giving you a structured way to work with network addresses instead of manipulating raw strings.

Example: What is an IP Address and URL?

java
// Import java.net.InetAddress so it can be used by its short name
import java.net.InetAddress;
// Import java.net.URL so it can be used by its short name
import java.net.URL;
// Define the class Main
public class Main {
	// Program entry point: the JVM starts running here
	public static void main(String[] args) throws Exception {
		InetAddress address = InetAddress.getByName("127.0.0.1");
		// Create a new URL object and store it in url
		URL url = new URL("https://example.com/page");
		// Print a line to the console
		System.out.println(address.getHostAddress() + " " + url.getHost());
	}
}

Reading from a URL Connection

The URLConnection class lets you open a communication link to a URL and inspect metadata like headers before reading the body. You can pull the raw byte stream of a page using getInputStream(), which is the lower-level building block that higher-level HTTP clients are built on top of.

Example: Reading from a URL Connection

java
// Import java.net.URLConnection so it can be used by its short name
import java.net.URLConnection;
// Import java.io.* so it can be used by its short name
import java.io.*;
// Define the class Main
public class Main {
	// Program entry point: the JVM starts running here
	public static void main(String[] args) throws Exception {
		// Create a new File object and store it in file
		File file = new File("page.txt");
		// Try code that might throw an exception
		try (PrintWriter out = new PrintWriter(file)) { out.print("sample content"); }
		URLConnection conn = file.toURI().toURL().openConnection();
		// Try code that might throw an exception
		try (InputStream in = conn.getInputStream()) {
			// Print a line to the console
			System.out.println(new String(in.readAllBytes()));
		}
		file.delete();
	}
}

URI vs URL in Java 11+

A URI represents an abstract resource identifier (it doesn't have to be resolvable), while a URL is a specific, locatable resource. Since Java 11, the recommended pattern is to construct a URI first and only convert it to a URL with toURL() when you actually need to open a connection, since URI's constructor validates syntax more strictly and avoids some legacy URL pitfalls.

Example: URI vs URL in Java 11+

java
import java.net.URI;
import java.net.URL;
public class Main {
	public static void main(String[] args) throws Exception {
		URI uri = new URI("https://example.com/page"); // validated more strictly
		URL url = uri.toURL(); // converted only when actually needed
		System.out.println(uri + " -> " + url);
	}
}

Network Protocols Overview

Java abstracts most low-level protocol details away from application code: Sockets run over TCP for reliable, ordered delivery, and DatagramSockets run over UDP for lightweight, connectionless messaging. Knowing which protocol a given API sits on top of helps you reason about whether delivery is guaranteed and how much overhead to expect.

Example: Network Protocols Overview

java
import java.net.*;
public class Main {
	public static void main(String[] args) throws Exception {
		Socket tcpSocket = new Socket(); // TCP -- reliable, ordered
		DatagramSocket udpSocket = new DatagramSocket(); // UDP -- lightweight, connectionless
		System.out.println("TCP and UDP sockets created");
		udpSocket.close();
	}
}

Hostname Resolution

You can resolve a domain name to its underlying IP address (or addresses, since a name can map to several) using the InetAddress class's getByName() and getAllByName() methods. This is the same DNS lookup step your browser performs before it can actually open a socket to a server.

Example: Hostname Resolution

java
import java.net.InetAddress;
public class Main {
	public static void main(String[] args) throws Exception {
		InetAddress address = InetAddress.getByName("localhost");
		System.out.println(address.getHostAddress()); // same DNS-style lookup a browser performs
	}
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Using new URL(...) in new code, which is deprecated since Java 20; use URI.create(...).toURL().
  2. Not handling UnknownHostException when resolving a hostname, which happens if the name does not exist or there is no network.
  3. Opening a connection without setting connect and read timeouts, so the program can hang for a long time.
🔒

Chapter Quiz — Complete all 4 topics to unlock

0/4 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.