이 블로그 검색

2023년 4월 6일 목요일

pass by reference VS. pass by value: Which One Should You Use in Your Code?

Two ways to save data in programming

When you put data into the variable, the programming language has 2 choices to save the data.

  1. Save data into heap memory and then keep the address of the memory in the stack memory.
  2. save data into stack memory.

Why there are two ways?

Stack memory is much faster than heap memory. However, the stack memory has limited space. Thus, a computer is designed to save static data(temporary use, calculate damage when you hit monsters) in stack memory and save dynamic data(use again, you learn a new skill in the game.) in heap memory.

What is pass-by-value

  • When using the method, pass the value only. Thus, if the input data changes, the original variable’s data will not change.
  • Save data into stack memory.

What is pass-by-reference

  • When using the method, pass the value’s address. Thus, if the input data changes, the original variable’s data will be changed.
  • Save data into heap memory and then keep the address of the memory in the stack memory.

Java Vs. C++

Java is pass-by-value

However, when using the object, the object address will be used in the method. In other words, the original variable’s data will be changed.

public class Main {

    public static void main(String[] args) {
        int a = 10;

        System.out.println("A is " + a); // 10
        increaseNum(a);//pass the value only
        System.out.println("A is " + a); // 10

        Student A = new Student(24);
        System.out.println(A.getAge()); // 24
        increaseAge(A);// pass the object address
        System.out.println(A.getAge()); // 34

    }

    public static void increaseNum(int input) {
        int temp = input;
        temp++;
    }

    public static void increaseAge(Student input) {
        input.setAge(input.getAge() + 10);
    }
}

public class Student {
    int age;
    public Student(int age) {
        this.age = age;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
}

Pass-by-Value vs Pass-by-Reference in C++

C++ allows programmers to choose between pass-by-value and pass-by-reference when passing variables to functions or methods, giving them greater flexibility and control over how their programs handle data.

#include <iostream>
using namespace std;

class Student {
  private:
    int age;

  public:
    void setAge(int s) {
      age = s;
    }
    int getAge() {
      return age;
    }
};

void increaseAge(Student i) {
  i.setAge(i.getAge()+10);
}
void increaseAge2(Student &i) {
  i.setAge(i.getAge()+10);
}
void increaseNum(int i) {
  i++;
}
void increaseNum2(int &i) {
  i++;
}

int main(void) {
  int a = 10;

  cout << "A is " << a << endl; // 10
  increaseNum(a);  //pass the value
  cout << "A is " << a << endl; // 10
  increaseNum2(a); //pass by reference
  cout << "A is " << a << endl; // 11

  Student B;
  B.setAge(20);

  cout << B.getAge() << "\\\\n"; // 20
  increaseAge(B);  //pass the value
  cout << B.getAge() << "\\\\n"; // 20
  increaseAge2(B); //pass by reference
  cout << B.getAge() << "\\\\n"; // 30

  return 0;

}


2023년 4월 5일 수요일

HTTP Status Codes: A Guide to Status Codes in the Request-Response Cycle

 

Definition

HTTP status codes are codes that are generated during the request-response cycle between a client and a server. They indicate the status of the request made by the client and the response provided by the server.

HTTP Status Codes

1xx (Informational): Request received, continuing process

  • 100 Continue: The server has received the request headers and the client should proceed to send the request body.
  • 101 Switching Protocols: The server agrees to switch to the protocol specified in the Upgrade header field.

2xx (Successful): The request was successfully received, understood, and accepted

  • 200 OK: The request was successful and the server has returned the requested data.
  • 201 Created: The request was successful and a new resource has been created.
  • 204 No Content: The request was successful, but there is no response body to return.
  • 206 Partial Content: The server is delivering only a portion of the resource due to a range header sent by the client.

3xx (Redirection): Further action needs to be taken in order to complete the request

  • 301 Moved Permanently: The requested resource has been permanently moved to a new location, and all future requests should be directed to the new location.
  • 302 Found: The requested resource has been temporarily moved to a different location, but future requests may still be directed to the original location.
  • 304 Not Modified: The requested resource has not been modified since the last time it was accessed by the client, and can be retrieved from the client's cache.
  • 307 Temporary Redirect: The requested resource has been temporarily moved to a different location, but future requests should still be directed to the original location.

4xx (Client Error): The request contains bad syntax or cannot be fulfilled by the server

  • 400 Bad Request: The server cannot understand the request due to bad syntax or an invalid request message.
  • 401 Unauthorized: The request requires authentication, and the client must authenticate itself to get the requested response.
  • 403 Forbidden: The server understands the request, but the client is not authorized to access the requested resource.
  • 404 Not Found: The requested resource could not be found on the server.

5xx (Server Error): The server failed to fulfill a valid request

  • 500 Internal Server Error: The server encountered an unexpected condition that prevented it from fulfilling the request.
  • 502 Bad Gateway: The server received an invalid response from a server acting as a gateway or proxy.
  • 503 Service Unavailable: The server is currently unable to handle the request due to a temporary overload or maintenance of the server.
  • 504 Gateway Timeout: The server acting as a gateway or proxy did not receive a timely response from the upstream server.

There are many other status codes in addition to those listed above, but these are the most commonly used ones.

HTTP Protocol Requests and Responses: Communication between Client and Server

Definition

HTTP (Hyperext Transfer Protocol) is one of the communication protocols used on the internet to exchange data. HTTP is responsible for communication between web browsers and web servers, where the client requests data from the server and the server responds with the data.

How it Works

HTTP works on a request-response model, where the client typically requests a web page and the server responds with the requested HTML file, images, videos, and other resources.

Components of the HTTP Protocol

  1. HTTP Method: The method used by the client to send a request to the server. The most common HTTP methods are GET, POST, PUT, and DELETE.
  2. URI (Uniform Resource Identifier): A string used to uniquely identify a resource on the internet.
  3. Header: The part of the request or response that contains metadata. Headers can contain information about the request or response, authentication information, and cache control information.
  4. Body: The part of the request or response that contains the actual data being transmitted. Generally, the body is not used in a GET request, but in a POST or PUT request, data is sent in the body.

HTTP Request Example

[http method] [URL] [HTTP version]

[header]

GET /index.html HTTP/1.1
Host: www.example.com
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:65.0) Gecko/20100101 Firefox/65.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Connection: keep-alive
  • HTTP Method: GET
  • URI: /index.html
  • Version: HTTP/1.1
  • Header: Host, User-Agent, Accept, Accept-Language, Connection

HTTP Response Example

[HTTP version] [status code]

[Header]

[Body]

HTTP/1.1 200 OK
Date: Wed, 12 May 2021 10:12:34 GMT
Server: Apache/2.4.29 (Unix)
Last-Modified: Fri, 01 May 2020 12:34:56 GMT
ETag: "abcd1234efgh5678"
Content-Length: 1234
Content-Type: text/html

<!DOCTYPE html>
<html>
<head>
	<title>Example Web Page</title>
</head>
<body>
	<h1>Hello, World!</h1>
	<p>This is an example web page.</p>
</body>
</html>

  • Version: HTTP/1.1
  • Status Code: 200 OK
  • Header: Date, Server, Last-Modified, ETag, Content-Length, Content-Type
  • Body: HTML document

Solving Geekina Loves Order in Java

Algorithm Problem

Problem_Link

Solution(Time Complexity, Space Complexity)

O(n), O(1)


public static int validString(int N, String S) {

    // Initialize variable 'temp' to 'a' as the 
    // reference for comparison in the string.
    char temp = 'a';

    // Iterate through the length of string S.
    for (int i = 0; i < N; i++) {

        // If the i-th character of S is less than 'temp', 
	//it is not in alphabetical order, so return 0.
        if (temp > S.charAt(i)) return 0;

        // Update 'temp' to the i-th character of S.
        temp = S.charAt(i);
    }

    // If the string is in alphabetical order, return 1.
    return 1;
}

2023년 4월 4일 화요일

HTTP URI: The Component that Uniquely Identifies Web Resources

Definition

HTTP URI (Uniform Resource Identifier) is a string used to uniquely identify resources on the internet.

Components

http://www.example.com:1030/software?id=test#section-4





Scheme

Scheme represents the protocol used to retrieve the resource. Some popular schemes include http, https, ftp, SOAP, etc.

Host

Host represents the domain name or IP address of the server where the resource is located.

Port

Port represents the network port number used for communication with the server. The default port number for the HTTP protocol is 80.

Path

Path represents the directory structure or file name of the resource on the server. The path is separated by slashes (/).

Query

Query is used to pass additional parameters for the resource. The query string starts with a question mark (?) and each parameter consists of a name and a value. Parameters are separated by an ampersand (&).

Fragment

Fragment is used to refer to a specific part of the resource. It starts with a hash symbol (#) and is often used to refer to a specific location or paragraph within a web page.

These URI components enable communication between the client and server in the HTTP protocol and are used to request and retrieve web pages or other resources using web browsers or other HTTP clients.

Example of HTTP URL Components

  1. http://www.example.com/index.html
    • Scheme: http
    • Host: www.example.com
    • Port: None, default port 80 is used
    • Path: /index.html
    • Query: None
    • Fragment: None
  2. https://www.example.com/search?q=example&lang=en
    • Scheme: https
    • Host: www.example.com
    • Port: None, default port 443 is used
    • Path: /search
    • Query: q=example&lang=en
    • Fragment: None
  3. ftp://ftp.example.com/files/readme.txt#section-2
    • Scheme: ftp
    • Host: ftp.example.com
    • Port: None, default port 21 is used
    • Path: /files/readme.txt
    • Query: None
    • Fragment: section-2

REST API vs. RESTful API

REST API

Definition

Representational State Transfer Application Programming Interface (REST API)

A REST API is an API based on the REST architecture.

Components of a REST API

1. URIs should use nouns rather than verbs and should be in lowercase.

Bad Example http://eunhanspace.blogspot.com/Running/
Good Example http://eunhanspace.blogspot.com/run/

2. URIs should not end with a slash (/).

Bad Example http://eunhanspace.blogspot.com/test/
Good Example http://eunhanspace.blogspot.com/test

3. Hyphens should be used instead of underscores.

Bad Example http://eunhanspace.blogspot.com/hello_world
Good Example http://eunhanspace.blogspot.com/hello-world

4. File extensions should not be included in URIs.

Bad Example http://eunhanspace.blogspot.com/photo.jpg
Good Example http://eunhanspace.blogspot.com/photo

5. Actions should not be included in URIs.

Bad Example http://eunhanspace.blogspot.com/create-post/1
Good Example http://eunhanspace.blogspot.com/post/1

RESTful API

Definition

RESTful refers to a system that follows the principles of REST. However, not all systems that use REST are RESTful.

A system can be considered RESTful if it follows the design rules of a REST API, and an API that performs all CRUD functions with POST or an API that does not follow the URI rules of a REST API can be considered a REST API but not RESTful.

2023년 4월 3일 월요일

REST Concepts and Features: Core Technology for Web Services

 

Definition

REST (Representational State Transfer).

Rules the way data is exchanged between different devices or systems.

  1. Identification through unique HTTP URI (Uniform Resource Identifier)

  2. Use of HTTP methods (POST, GET, PUT, DELETE, PATCH, etc.) to read, modify, and delete the corresponding resource (CRUD operation)

Resource

In the HTTP protocol, a resource refers to any information or object that can be identified and requested through a unique URI (Uniform Resource Identifier).

Examples of resources include web pages, images, videos, audio files, documents, and other types of data that can be accessed via HTTP on the internet.

CRUD Operation

A term that refers to the basic data processing functions of creation, retrieval, updating, and deletion.

  1. Create (POST): Data creation

  2. Read (GET): Data retrieval

  3. Update (PUT, PATCH): Data modification

  4. Delete (DELETE): Data deletion

Characteristics of REST

  1. Server-Client Structure: The server-client structure refers to the structure between the client that requests the service and the server that provides the service on the network. The client sends a request to the server, and the server responds to the request. This structure is commonly used in internet and web technologies and is also used in various fields such as distributed systems and cloud computing.

  2. Stateless: Stateless refers to the server not storing the client's previous request contents. This allows the server to process each request independently and ensure that each request does not affect each other. This reduces server load and increases scalability.

  3. Cacheable: Cacheable means that the server's response can be stored by the client or intermediate servers. This enables faster response times and less bandwidth usage by using the stored data instead of requesting the data or resources previously requested.

  4. Layered System: A layered system allows for intermediate servers between the server and client, and these servers process requests and responses independently. This reduces the coupling between the server and client and increases the system's flexibility and scalability.

  5. Uniform Interface: Uniform interface refers to the need for a consistent interface design between the server and client. This enables the communication between different systems, allows each component of the system to be changed independently, and allows for the addition of new technologies or features without the need to change the entire system.

Pros and Cons of REST

Advantages

  • Uses the HTTP protocol infrastructure, eliminating the need for separate infrastructure for REST API use.

  • Uses HTTP protocol standards to take advantage of additional benefits.

  • Can be used on all platforms that follow the HTTP standard protocol.

  • REST API messages indicate their intent, making it easy to understand what they are intended to do.

  • Minimizes problems that may arise from different service designs.

  • Separates the roles of the server and client.

Disadvantages

  • No existing standard, so a definition is required.

  • HTTP methods are limited in form.

  • If a service requires a lot of testing through a browser, it requires the processing of header information rather than easily modifiable URLs, requiring specialized knowledge.

  • Many behaviors are not supported by older browsers such as Internet Explorer.

Logic Gate Truth Tables & Definitions

Logic Gate Truth Tables Java Code !A // NOT A&B // AND ~(A&B) // NAND A|B // OR ~(A|B) // XOR A^B // XOR ~(A^B) // XNOR ~A // Inve...