Java是一種廣泛應用于軟件開發領域的編程語言。以下是一些Java的應用領域和工程示例:
1. 網絡應用
public class HttpServer {
public static void main(String[] args) throws IOException {
ServerSocket server = new ServerSocket(8080);
System.out.println("Listening for connection on port 8080...");
while (true) {
Socket client = server.accept();
InputStreamReader isr = new InputStreamReader(client.getInputStream());
BufferedReader br = new BufferedReader(isr);
String request = br.readLine();
if (request != null) {
System.out.println(request);
}
String response = "Hello from Java http server!";
DataOutputStream out = new DataOutputStream(client.getOutputStream());
out.writeBytes("HTTP/1.1 200 OK\r\n");
out.writeBytes("Content-Type: text/html\r\n");
out.writeBytes("Content-Length: " + response.length() + "\r\n");
out.writeBytes("\r\n");
out.writeBytes(response);
out.close();
br.close();
client.close();
}
}
}
上面這段代碼演示了如何使用Java編寫一個簡單的HTTP服務器,可以用于搭建網站。
2. 移動應用
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
WebView webView = findViewById(R.id.webView);
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl("https://www.google.com");
}
}
這段代碼是在Android平臺上使用Java編寫的,在一個Activity中嵌入了一個WebView,然后展示了Google的網站。
3. 數據庫應用
public class Main {
public static void main(String[] args) throws SQLException {
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb", "root", "root");
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery("SELECT * FROM users");
while (resultSet.next()) {
String name = resultSet.getString("name");
String email = resultSet.getString("email");
System.out.println(name + ": " + email);
}
connection.close();
}
}
這段代碼展示了如何使用Java編寫一個簡單的數據庫應用程序,通過JDBC連接MySQL數據庫,并執行一些查詢操作。