Chapter 5: Specific Language Features and Use Cases

Python: Versatility and Ease of Use

Key Features of Python

Python’s syntax is clean and easy to read. Defining a function:

python

def greet(name):
return f"Hello, {name}!"

print(greet("Alice"))

Python supports multiple programming paradigms, including object-oriented and functional programming. Creating a class and using inheritance:

python

class Animal:
def speak(self):
pass

class Dog(Animal):
def speak(self):
return "Bark"

dog = Dog()
print(dog.speak())

Python’s dynamic typing and duck typing allow flexible coding. Example of dynamic typing:

python

x = 10
x = "Ten"
print(x)

Python has extensive standard libraries. Using datetime:

python

from datetime import datetime

now = datetime.now()
print(now.strftime("%Y-%m-%d %H:%M:%S"))

Python has a strong support for third-party libraries. Using requests for HTTP requests:

python

import requests

response = requests.get("https://api.github.com")
print(response.status_code)

Use Cases in Data Science, Web Development, and Automation

Data science with Python using pandas:

python

import pandas as pd

data = {'Name': ['Alice', 'Bob'], 'Age': [24, 27]}
df = pd.DataFrame(data)
print(df)

Web development with Python using Flask:

python

from flask import Flask

app = Flask(__name__)

@app.route('/')
def home():
return "Hello, World!"

if __name__ == '__main__':
app.run(debug=True)

Automation with Python using selenium:

python

from selenium import webdriver

driver = webdriver.Chrome()
driver.get("http://www.google.com")
driver.quit()

Scientific computing with Python using numpy:

python

import numpy as np

array = np.array([1, 2, 3])
print(array * 2)

Machine learning with Python using scikit-learn:

python

from sklearn.linear_model import LinearRegression

X = [[1], [2], [3]]
y = [1, 2, 3]
model = LinearRegression().fit(X, y)
print(model.predict([[4]]))

JavaScript: The Language of the Web

Key Features of JavaScript

JavaScript is interpreted and runs in the browser. Example of embedding JavaScript in HTML:

html

<!DOCTYPE html>
<html>
<head>
<title>JavaScript Example</title>
</head>
<body>
<script>
document.write("Hello, World!");
</script>
</body>
</html>

JavaScript is event-driven. Handling a button click event:

html

<!DOCTYPE html>
<html>
<head>
<title>Event Handling</title>
</head>
<body>
<button onclick="displayMessage()">Click me</button>
<script>
function displayMessage() {
alert("Button clicked!");
}
</script>
</body>
</html>

JavaScript supports asynchronous programming. Using fetch for asynchronous operations:

javascript

fetch('https://api.github.com')
.then(response => response.json())
.then(data => console.log(data));

JavaScript has first-class functions. Passing functions as arguments:

javascript

function greet(name) {
return `Hello, ${name}!`;
}

function displayGreeting(greetFunction, name) {
console.log(greetFunction(name));
}

displayGreeting(greet, 'Alice');

JavaScript supports prototypal inheritance. Creating and using prototypes:

javascript

function Animal(name) {
this.name = name;
}

Animal.prototype.speak = function() {
console.log(`${this.name} makes a noise.`);
};

function Dog(name) {
Animal.call(this, name);
}

Dog.prototype = Object.create(Animal.prototype);
Dog.prototype.constructor = Dog;

Dog.prototype.speak = function() {
console.log(`${this.name} barks.`);
};

let dog = new Dog('Rex');
dog.speak();

Use Cases in Front-End and Back-End Web Development

Front-end development with JavaScript using React:

javascript

import React from 'react';
import ReactDOM from 'react-dom';

function App() {
return <h1>Hello, World!</h1>;
}

ReactDOM.render(<App />, document.getElementById('root'));

Front-end development with JavaScript using Vue.js:

html

<!DOCTYPE html>
<html>
<head>
<title>Vue.js Example</title>
<script src="https://cdn.jsdelivr.net/npm/vue@2"></script>
</head>
<body>
<div id="app">{{ message }}</div>
<script>
new Vue({
el: '#app',
data: {
message: 'Hello, Vue!'
}
});
</script>
</body>
</html>

Back-end development with JavaScript using Node.js:

javascript

const http = require('http');

const hostname = '127.0.0.1';
const port = 3000;

const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Hello, World!\n');
});

server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});

Using Express.js for back-end development:

javascript

const express = require('express');
const app = express();

app.get('/', (req, res) => {
res.send('Hello, World!');
});

app.listen(3000, () => {
console.log('Server is running on port 3000');
});

Using MongoDB with Node.js:

javascript

const { MongoClient } = require('mongodb');
const url = 'mongodb://localhost:27017';
const dbName = 'mydatabase';

MongoClient.connect(url, function(err, client) {
if (err) throw err;
const db = client.db(dbName);
db.collection('customers').findOne({}, function(findErr, result) {
if (findErr) throw findErr;
console.log(result);
client.close();
});
});

Java: Enterprise Applications and Portability

Key Features of Java

Java is platform-independent. Writing a simple Java application:

java

public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}

Java has strong memory management with automatic garbage collection:

java

public class Main {
public static void main(String[] args) {
MyClass obj = new MyClass();
obj = null;
System.gc(); // Requesting garbage collection
}
}

class MyClass {
// class definition
}

Java is object-oriented. Defining and using classes and objects:

java

class Animal {
void makeSound() {
System.out.println("Some sound");
}
}

class Dog extends Animal {
void makeSound() {
System.out.println("Bark");
}
}

public class Main {
public static void main(String[] args) {
Dog dog = new Dog();
dog.makeSound();
}
}

Java supports multithreading. Creating and running threads:

java

public class MyThread extends Thread {
public void run() {
System.out.println("Thread is running");
}

public static void main(String[] args) {
MyThread t = new MyThread();
t.start();
}
}

Java provides a rich set of APIs. Using ArrayList from the Collections Framework:

java

import java.util.ArrayList;

public class Main {
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<>();
list.add("Apple");
list.add("Banana");
System.out.println(list);
}
}

Use Cases in Enterprise Software and Android Development

Enterprise application development with Java using Spring Boot:

java

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}

@RestController
class HelloController {
@GetMapping("/")
public String hello() {
return "Hello, World!";
}
}

Creating a simple Android app with Java:

java

package com.example.helloworld;

import android.os.Bundle;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TextView textView = new TextView(this);
textView.setText("Hello, World!");
setContentView(textView);
}
}

Building RESTful web services with Java using JAX-RS:

java

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Application;

@Path("/hello")
public class HelloResource {
@GET
@Produces(MediaType.TEXT_PLAIN)
public String hello() {
return "Hello, World!";
}
}

import javax.ws.rs.ApplicationPath;

@ApplicationPath("/api")
public class HelloApplication extends Application {
}

Connecting to a MySQL database with Java using JDBC:

java

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

public class Main {
public static void main(String[] args) {
try {
Connection con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/mydatabase", "user", "password");

Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM customers");

while (rs.next())
System.out.println(rs.getString(1) + " " + rs.getString(2));
con.close();
} catch (Exception e) {
System.out.println(e);
}
}
}

Using Maven for project management and build automation:

xml

<!-- pom.xml -->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>myapp</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
</project>

C#: The Microsoft Ecosystem

Key Features of C#

C# supports strong typing and object-oriented programming. Defining a class and creating an object:

csharp

public class Animal {
public void Speak() {
Console.WriteLine("Some sound");
}
}

public class Dog : Animal {
public new void Speak() {
Console.WriteLine("Bark");
}
}

class Program {
static void Main() {
Dog dog = new Dog();
dog.Speak();
}
}

C# integrates seamlessly with the .NET framework. Using LINQ for data queries:

csharp

using System;
using System.Collections.Generic;
using System.Linq;

class Program {
static void Main() {
List<int> numbers = new List<int> { 1, 2, 3, 4, 5 };
var evenNumbers = numbers.Where(n => n % 2 == 0).ToList();
evenNumbers.ForEach(Console.WriteLine);
}
}

C# supports asynchronous programming with async and await:

csharp

using System;
using System.Threading.Tasks;

class Program {
static async Task Main() {
await SayHello();
}

static async Task SayHello() {
await Task.Delay(1000);
Console.WriteLine("Hello, World!");
}
}

C# has properties and indexers for more intuitive data manipulation:

csharp

public class Person {
private string name;
public string Name {
get { return name; }
set { name = value; }
}
}

class Program {
static void Main() {
Person person = new Person();
person.Name = "Alice";
Console.WriteLine(person.Name);
}
}

C# supports event-driven programming. Defining and handling an event:

csharp

using System;

public class Publisher {
public event EventHandler RaiseEvent;

public void DoSomething() {
OnRaiseEvent(EventArgs.Empty);
}

protected virtual void OnRaiseEvent(EventArgs e) {
RaiseEvent?.Invoke(this, e);
}
}

public class Subscriber {
public void HandleEvent(object sender, EventArgs e) {
Console.WriteLine("Event handled");
}
}

class Program {
static void Main() {
Publisher pub = new Publisher();
Subscriber sub = new Subscriber();
pub.RaiseEvent += sub.HandleEvent;
pub.DoSomething();
}
}

Use Cases in Game Development with Unity and Enterprise Applications

Creating a simple Unity game with C#:

csharp

using UnityEngine;

public class HelloWorld : MonoBehaviour {
void Start() {
Debug.Log("Hello, World!");
}
}

Developing an enterprise application with ASP.NET Core:

csharp

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

public class Startup {
public void ConfigureServices(IServiceCollection services) {
services.AddControllers();
}

public void Configure(IApplicationBuilder app, IWebHostEnvironment env) {
if (env.IsDevelopment()) {
app.UseDeveloperExceptionPage();
}
app.UseRouting();
app.UseEndpoints(endpoints => {
endpoints.MapControllers();
});
}
}

public class Program {
public static void Main(string[] args) {
CreateHostBuilder(args).Build().Run();
}

public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder => {
webBuilder.UseStartup<Startup>();
});
}

Using Entity Framework Core for data access in a C# application:

csharp

using Microsoft.EntityFrameworkCore;

public class MyContext : DbContext {
public DbSet<Customer> Customers { get; set; }
}

public class Customer {
public int Id { get; set; }
public string Name { get; set; }
}

class Program {
static void Main() {
using (var context = new MyContext()) {
context.Database.EnsureCreated();
context.Customers.Add(new Customer { Name = "Alice" });
context.SaveChanges();
}
}
}

Building a Windows desktop application with WPF:

xml

<!-- MainWindow.xaml -->
<Window x:Class="WpfApp.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="200" Width="400">
<Grid>
<Button Content="Click me" Click="Button_Click" HorizontalAlignment="Center" VerticalAlignment="Center"/>
</Grid>
</Window>
csharp

// MainWindow.xaml.cs
using System.Windows;

namespace WpfApp {
public partial class MainWindow : Window {
public MainWindow() {
InitializeComponent();
}

private void Button_Click(object sender, RoutedEventArgs e) {
MessageBox.Show("Hello, World!");
}
}
}

Using Azure Functions with C# for serverless computing:

csharp

using System.IO;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;

public static class Function {
[FunctionName("HttpTriggerCSharp")]
public static async Task<IActionResult> Run(
[HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
ILogger log) {
log.LogInformation("C# HTTP trigger function processed a request.");
string name = req.Query["name"];
string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
dynamic data = JsonConvert.DeserializeObject(requestBody);
name = name ?? data?.name;
return name != null
? (ActionResult)new OkObjectResult($"Hello, {name}")
: new BadRequestObjectResult("Please pass a name on the query string or in the request body");
}
}

These examples illustrate the unique features and practical applications of Python, JavaScript, Java, and C#. They demonstrate the versatility of each language and provide hands-on examples for various use cases, from web development to enterprise software and game development.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *