Menu BAR

FEEL FREE TO ASK ANY PROGRAM and please mention any error if you find it

12 Feb 2024

JAVA PROGRAM - ADDITION OF TWO MATRICES


 ## Write a Java Program to ADD TWO MATRICES





public class MatrixAddition { 
                public static void main(String[] args) { 

                                    int[][] firstMatrix = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} }; 
                                    int[][] secondMatrix = { {9, 8, 7}, {6, 5, 4}, {3, 2, 1} }; 

                                    // Creating a matrix to store the result 
                                    int[][] result = new int[firstMatrix.length][firstMatrix[0].length]; 

                                    // Adding corresponding elements of two matrices 
                                    for (int i = 0; i < firstMatrix.length; i++) { 
                                                    for (int j = 0; j < firstMatrix[i].length; j++) { 
                                                                    result[i][j] = firstMatrix[i][j] + secondMatrix[i][j]; 
                                                    
                                    

                                    // Displaying the result matrix 
                                    System.out.println("Result of Matrix Addition:"); 

                                    for (int i = 0; i < result.length; i++) { 
                                                            for (int j = 0; j < result[i].length; j++) { 
                                                                                System.out.print(result[i][j] + " "); 
                                                            
                                   System.out.println(); 
                                  
                
}

NODE JS PROGRAM - PRINT NUMBERS FROM 1 TO 10


## Write a Node Js program to print numbers from 1 to 10



// Define the upper limit for the loop
const limit = 10;

// Print numbers from 1 to the limit using a for-loop

console.log("Printing numbers using a for loop:");
for (let i = 1; i <= limit; i++) { 
                  console.log(i);
}

11 Feb 2024

NODE JS PROGRAM - FACTORIAL OF A NUMBER


 ## Write a Node Js program to print the Factorial of a number




function factorial(n) { 
            if (n === 0 || n === 1) { 
                                return 1; 
            
            else { 
                                return n * factorial(n - 1); 
            


const number = 10;                             // Change this to calculate the factorial of a different number 
const result = factorial(number);       // Function calling

console.log(`Factorial of ${number} is: ${result}`);

NODE JS PROGRAM - PRINT EACH NUMBER OF AN ARRAY USING LOOP


 ## Write a Node Js program to iterate over an array and print each number




const arrNumber  = [1,2,3,4,5];

console.log ( "Printing numbers using a FOR Loop: "); 

for (let i = 0 ; i < arrNumber.length ; i++) {
            console.log (arrNumber[i]);
}

JAVA TUTORIAL PART 3 - DATA TYPES AND COMMENTS


Data Types in Java



1) Primitive Data Types

- These are the most basic data types in Java. They represent single values and are not objects.
There are different primitive data types - 

a) Integer Types- 
    - byte - 8-bit signed integer. Range varies from -128 to 127

    - short - 16-bit signed integer. Range varies from -32,768 to 32,767 

    - int - 32-bit signed integer. Range varies from -2^31 to 2^31-1
                    Example -         int num = 10;

    - long- 64-bit signed integer. Range varies from -2^63 to 2^63-1

b) Floating-Point types:
    - float - 32-bit floating-point number. It should be suffixed with 'f' or 'F'
    - double - 64-bit floating-point number. 
                    Example -         double pi = 3.14;

c) Other Primitive types:
    - char - 16-bit Unicode character.
                    Example -         char letter = 'H';

    - boolean - Represents the two values - true and false
                    Example -          boolean flag = true;


2) Reference Data Types

- These are used to refer to objects. They do not store the actual data but store the reference (Memory Address) of the object.
There are different reference data types - 

a) Class types- 
    - String - Represent a sequence of characters.
                    Example -         String text = "Hello";

b) Array types- 
    - Arrays - Ordered collection of elements of the same type.

c) Interface types- 
    - Interfaces - Defines a set of methods that a class must implement.



Comments in Java



Single-Line comments start with //
Multi-Line comments starts with /* and ends with */

Example- 

// This is a single-line comment

/* 
*  This is a multi-line comment
*  This is the second multi-line comment.
*/

10 Feb 2024

JAVA TUTORIAL PART 2 - JDK (Java Development Kit) INSTALLATION


1) Download the JDK



1) Visit the official Oracle website or OpenJDK website to download the JDK installer for your operating system.

2) Make sure to download the version that matches your operating system (Windows, macOS, or Linux)


2) Run the Installer



1) Once the JDK is installed, choose the installation directory for the JDK.

2) Set the Environment Variables- 
                - JAVA_HOME (example - C:\Program Files\ Java\jdk-16)
    
    Add the JDK's bin Folder to the PATH environment variable.
                - PATH (example - %JAVA_HOME%\bin)



3) Verify the Installation



Open the terminal or Command Prompt to check the Java version.

Example -   java -version

                
                                                        

Click Here to Learn About Java Data Types

JAVA PROGRAM - RIGHT TRIANGLE STAR PATTERN


 ## Write a Java Program to print the Right Triangle Star Pattern



                                                                        *
                                                                        *  *
                                                                        *  *  *
                                                                        *  *  *  *
                                                                        *  *  *  *  *



 public class RightTriangleStarPattern { 

                        public static void main(String[] args) { 
                                            int rows = 5; 

                                            for (int i = 1; i <= rows; i++) { 
                                                            for (int j = 1; j <= i; j++) { 
                                                                                System.out.print("* "); 
                                                            
                                            System.out.println(); 
                                            
                        } 
}

JAVA PROGRAM - INVERTED PYRAMID STAR PATTERN


 ## Write a Java Program to Print an INVERTED PYRAMID STAR PATTERN


                                                        *  *  *  *  *  *  *  *  * 
                                                            *  *  *  *  *  *  * 
                                                                *  *  *  *  *
                                                                    *  *  *
                                                                        *


public class InvertedPyramidStarPattern { 

                        public static void main(String[] args) { 
                                            int rows = 5; 
                
                                            for (int i = rows; i >= 1; i--) { 
                                                                for (int j = 1; j <= rows - i; j++) { 
                                                                                System.out.print("  "); 
                                                                
                                                                
                                                                for (int k = 1; k <= 2 * i - 1; k++) { 
                                                                                System.out.print("* "); 
                                                                
                                                                System.out.println(); 
                                            
                        
}

JAVA PROGRAM - PYRAMID STAR PATTERN


## Write a Java program to print the PYRAMID STAR PATTERN? 



                                                                    *
                                                                *  *  *
                                                            *  *  *  *  *
                                                        *  *  *  *  *  *  *
                                                    *  *  *  *  *  *  *  *  *


public class PyramidStarPattern { 

                        public static void main(String[] args) { 
                                        int rows = 5; 

                                        for (int i = 1; i <= rows; i++) { 
                                                            for (int j = 1; j <= rows - i; j++) { 
                                                                            System.out.print("  "); 
                                                            
                                                            for (int k = 1; k <= 2 * i - 1; k++) { 
                                                                            System.out.print("* "); 
                                                            
                                                            System.out.println(); 
                                        
                      
}

JAVA PROGRAM - LEAP YEAR OR NOT


 ## Write a Java Program to check if the year is LEAP YEAR or NOT



 public class CheckLeapYear { 

                    public static void main(String[] args) { 
                                        int year = 2024; 

                                        if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) {
                                                             System.out.println("The year " + year + " is a leap year."); 
                                        
                                        else { 
                                                             System.out.println("The year " year + " is not a leap year."); 
                                        
                    
}

JAVA PROGRAM - LARGEST VALUE AMONG THREE NUMBERS


 ## Write a Java program to find the largest value among three variables



public class LargestAmongThreeNumbers { 

            public static void main(String[] args) { 
                            int num1 = 20; 
                            int num2 = 50; 
                            int num3 = 55; 

                            int largest = num1; 

                            if (num2 > largest) { 
                                            largest = num2; 
                            
                            if (num3 > largest) { 
                                            largest = num3; 
                            
        
                            System.out.println("The largest number among " + num1 + ", " + num2 + ", and " + num3 + " is: " + largest); 
            
}

JAVA PROGRAM - LARGEST VALUE AMONG TWO NUMBERS


## Write a Java Program to find the largest value among two numbers 



public class LargestOfTwoNumbers { 

          public static void main(String[] args) { 
                    int num1 = 10; 
                    int num2 = 20; 

                    if (num1 > num2) { 
                                    System.out.println("The largest number is: " + num1); 
                    
                    else { 
                                    System.out.println("The largest number is: " + num2); 
                    }
        
}

8 Feb 2024

JAVA TUTORIAL PART 1 - INTRODUCTION TO JAVA


1) WHAT IS JAVA?



1) Java is a multi-platformhigh-level, object-oriented programming language developed by Sun Microsystems (now owned by Oracle Corporation).

2) It is a fast, secure, reliable programming language for coding.

2) The main principle of Java is - "WRITE ONCE, RUN ANYWHERE"

3) Java programs can be compiled into Bytecode, which can then be executed on any platform that has a Java Virtual Machine (JVM).

4) Due to the ByteCode, there is no need to recompile the code for each platform.



2) Key Features of Java



1) Platform Independence - Java programs can run on any platform that has a JVM, making them very highly profitable.

2) Object-Oriented - Java is an OO language and hence it emphasizes the use of Classes and Objects for better code organization.

3) Simple and Familiar Syntax - It is similar to C and C++.

4) Memory Management - Java has a built-in garbage collector that manages memory allocation and deallocation automatically.

5) Robust and Secure - Java's strong type system, exception handling, and security features make it robust and secure. 

6) Multithreading - Java supports multithreading to perform concurrent tasks easily.


3) Common Applications of Java


1) Web Development

2) Mobile Development

3) Desktop Applications

4) Enterprise Applications

5) Embedded Systems


4) Download Java



Download Java from the official website https://www.oracle.com/java/technologies/downloads/



JAVA - SUBTRACT TWO NUMBERS


 Write a JAVA program to subtract two numbers?




public class SubtractTwoNumbers { 

                public static void main(String[] args) {
                                int num1 = 10; int num2 = 5; 
                                int difference = num1 - num2; 

                                System.out.println("Difference of " + num1 + " and " + num2 + " is: " + difference);
                 

}

7 Feb 2024

JAVA - ADD TWO NUMBERS


 ## Write a Java program to add two numbers




public class AddTwoNumbers { 

    public static void main(String[] args) {
                
                int num1 = 5; int num2 = 10; 
                int sum = num1 + num2; 

                System.out.println("Sum of " + num1 + " and " + num2 + " is: " + sum); 
                
}

NODE JS - ASYNCHRONOUS PROGRAMMING


 1) What is Asynchronous Programming?



Asynchronous programming allows tasks to be executed concurrently without blocking the execution of other tasks and this can be achieved through callbacks, promises, and async/await.

Note that JavaScript is single-threaded. It carries out asynchronous operations via the callback queue and event loop.


2) Benefits of Asynchronous Programming?



1) Improved Performance - By avoiding blocking operations, asynchronous programming allows the application to continue executing other tasks while waiting for I/O operations to complete.
(Faster response times and better resource utilization).

2) Scalability - Asynchronous programming enables Node.Js applications to handle many concurrent requests without significant performance degradation.
(High-Performance web servers and real-time applications)

3) Responsive User Interfaces - Asynchronous programming ensures the user interface remains responsive even when performing time-consuming operations.
(Enhances the overall user experience and prevents applications from freezing)


3) Callbacks


Callbacks are a fundamental mechanism in Node Js for handling asynchronous operations.
Callbacks are functions passed as arguments to other functions and they are called once the operation is completed.

Example - 

const fs = require('fs'); 

fs.readFile('example.txt', 'utf8', (err, data) => { 
            if (err) { 
                        console.error(err); 
                        return; 
            
            console.log(data); 
});


4) Promises


Promises represent a value that may be available now, in the future, or never.
They allow chaining of asynchronous operations and handling of errors more elegantly.
Promises improve code readability and make error handling easier.

Example - 

const fs = require('fs').promises; 

fs.readFile('example.txt', 'utf8').
        then((data) => { 
        console.log(data); 
        }) 
        .catch((err) => { 
                console.error(err); 
        });

5) Async/ Await


Async functions enable writing asynchronous code in a synchronous-like manner using the 'async' and 'await'.
'async' - define an asynchronous function and 'await' - waits for promises to resolve.

Example - 

const fs = require('fs').promises; 

async function testingAsync() { 
        try { 
                const data = await fs.readFile('example.txt', 'utf8'); 
                console.log(data); 
        } catch (err) { 
                console.error(err); 
         

testingAsync();

6 Feb 2024

NODE JS - NPM


 1) What is NPM?


- Node Js npm (Node Package Manager) is a package manager for JavaScript, which is used for managing dependencies in Node.js applications.

- With npm, we can easily install, manage, and update packages (Libraries/ Modules) that you can use in your applications.

- www.npmjs.com hosts thousands of packages to download and use

- To install a package using npm - 
npm install package-name

   This will download the package and add it to your node_modules directory, along with dependencies.

- Example - 
                    To install Express, you can run the below command - 
  npm install express
or
npm i express

- Always include the installed package in your package.json file by adding them to the dependencies section.

NODE JS BUILT-IN MODULE - FS

 1) What does FS module do?


1) The Node fs module provides functions for interacting with the file system on your computer.

2) It allows you to perform various operations such as reading from and writing to the files, creating and deleting files/folders, and much more.

3) Importing the 'fs' module:
var fs = require('fs');

Examples of various operations are below:

2) Reading from a file

fs.readFile('example.txt', 'utf8', (err, data) => {
         if (err) { 
                console.error(err); 
                return; 
               
        console.log(data); 
});

3) Creating a new file

There are three ways to create a new file using the fs module-

1) Using appendFile() method -  This method appends specified content to a file. If the file does not exist, a new file will be created.

fs.appendFile('mynewfile1.txt', 'Hello content!', function (err) { 
        if (err) 
                throw err; 
        console.log('Saved!'); 
});

2) Using the open() method - This method opens the specified file for writing if the flag (second argument) is passed as w which means writing. If the file does not exist, a new file will be created.

fs.open('mynewfile2.txt', 'w', function (err, file) { 
        if (err) 
                throw err; 
        console.log('Saved!'); 
});

3) Using the writeFile() method - This method replaces the specified file and content if it exists. If the file does not exist, a new file will be created.

fs.writeFile('mynewfile3.txt', 'Hello content!', function (err) { 
        if (err) 
                throw err; 
        console.log('Saved!'); 
});

4) Deleting a File

The fs.unlink() method deletes the specified file.

fs.unlink('myfile.txt', function (err) { 
        if (err) 
                throw err; 
        console.log('File deleted!'); 
});


NODE JS BUILT IN MODULE - URL


1) What does the URL Module do? 


1) Node JS 'url' module provides utilities for URL resolution and parsing.

2) It allows you to parse URLs into their components (such as protocol, hostname, port, path, hash, query parameters, and more) and format URL strings from these components.

3) To import the URL module in your application, use the require() method:
    var url = require ('url');


2) URL Parse() method


url.parse() method can parse the address and returns a URL object with each part of the address as properties.

Example:

const url = require('url'); 
const urlString = 'https://example.com:8080/path?query=value'; 

const parsedUrl = url.parse(urlString, true); 
// Pass true as the second argument to parse query parameters 

console.log(parsedUrl);


We can also print the hostname, pathname, and query as well- 

console.log (parsedUrl.host); // returns example.com:8080
console.log (parsedUrl.pathname); // returns /path
console.log (parsedUrl.search); // returns ?query=value


3) URL Resolve() method


The url.resolve() method resolves a relative URL path against a base URL.

Example:

const url = require('url'); 
const baseUrl = 'https://example.com/users'; 
const relativePath = '/profile'; 

const resolvedUrl = url.resolve(baseUrl, relativePath); 
console.log(resolvedUrl);  // returns https://example.com/profile


5 Feb 2024

NODE JS BUILT IN MODULE - HTTP


1) Creating an HTTP Server


1) We need to first import the 'http' module using the require function
                            var http = require ('http');

2) We will use the method createServer() to create an HTTP server:
                            http.createServer(function (req, res){
                            ... // your code here
                            }).listen(PORT_NUMBER); 

Example: 
// Import the built-in 'http' module 
const http = require('http'); 

// Define the hostname and port number 
const hostname = '127.0.0.1'; 
const port = 3000; 

// Create an HTTP server 
const server = http.createServer((req, res) => { 

        // Set the HTTP status code and content type in the response header 
        res.writeHead(200, {'Content-Type': 'text/plain'}); 

        // Send the response body 
        res.end('Hello, world!\n'); 

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


2) GET REQUEST to query



1) We will be using http.request() method to send an HTTP GET request to a server and handle the response.

2) Similarly, we will be importing the module using- 
                            var http = require ('http');

3) We will be defining the options for the HTTP request where we will be mentioning the hostname, port number, path (if any), and the method.
                            const options = {
                            hostname: 'jsonplaceholder.typicode.com',
                            port: 80,
                            path: '/posts',
                            method: 'GET'
                            }

4) Creating a http.request() method in which we are going to pass the above options object.

5) Store the response and display it or process it when the response is complete.

Example: 

// Import the built-in 'http' module 
const http = require('http'); 

// Define the options for the HTTP request 
const options = { 
        hostname: 'jsonplaceholder.typicode.com', 
        port: 80, 
        path: '/posts', 
        method: 'GET'
};

// Create the HTTP request 
const req = http.request(options, (res) => { 

        // Initialize a variable to store the response data 
        let data = ''; 

        // Concatenate chunks of data as they are received 
        res.on('data', (chunk) => { 
                data += chunk; 
        });
 
        // When the response is complete, log the data to the console 
        res.on('end', () => { 
            console.log(data); 
        }); 
}); 

// Handle errors that occur during the request 
req.on('error', (error) => { 
        console.error('An error occurred:', error); 
}); 

// End the request 
req.end(); 


MODULES IN NODE JS


 1) Modules in Node Js


1) In Node Js, modules are reusable blocks of code that encapsulate related functionality.

2) Modules allow you to organize your code into separate files and directories, making it easier to manage and maintain your projects.

3) We can define modules in separate files and then import and use them in other files using the 'require()' function (User-Defined Modules).

4) There are two types of modules - User-Defined Modules and Predefined Modules (Built-in Modules) 


1.1) What are User-Defined Modules?


Definition - User-defined modules are created by the developers to encapsulate and reuse the code across their own applications. These modules are typically stored in separate files within the applications's directory.

Developers can create their own modules and export them using the "module.exports".
The same modules can be imported and used in other parts of the application using the "require()" function.

Example: myFirstModule.js

function greetWithPersonName(name) {
        console.log ( `Hello ${name}! `);     
        //Here we have used the tilde operator
}

module.exports = greetWithPersonName;



1.2) What are Predefined Modules/ Built-in Modules/ Core Modules?


Definition: Predefined modules are provided by Node.js itself and are available for use without the need for installation. These modules are part of the Node.js runtime environment and provide various functionalities for common tasks such as file system operations, networking, HTTP, and more.

Developers can use the predefined modules by importing and using them in Node.js applications in the same way as user-defined modules, using the require() function.

Example: usePreDefMod.js

// We are going to use a file system module to manage the file 

const fs = require ('fs');

fs.readFile ('text.txt, 'utf8', (err, data) => {
        if (err) {
            console.error (err);
            return;
        }
        console.log (data);
});

NODE JS INTRODUCTION


1) What is Node Js?


- Node Js is an open-source server environment that runs on various platforms like Windows, Linux, Unix, Mac OS, etc.

- Node Js is a runtime environment that allows you to run JavaScript code on the server side.

- Node Js uses the V8 Javascript engine.

- Node Js is commonly used to build scalable network applications because of its event-driven, non-blocking I/O model, which makes it efficient and lightweight.



2) Why to use Node Js?

- Javascript can be used for Server-side and Client-side development (Frontend and Backend of an application).

- Node Js is an event-driven, non-blocking I/O model, which makes it efficient and scalable for handling concurrent connections. Node Js can handle multiple requests without getting blocked (Useful for real-time applications).

- V8 Javascript engine compiles JavaScript directly into machine code before executing it (High Performance).

- Since Node Js is non-blocking, and has event-driven architecture, it is inherently scalable (Can easily handle many concurrent connections).

- Plenty of resources and support available for developers who are using Node Js (Documentation, Tutorial, and more)


3) How to download Node Js?



- Node js can easily be installed from the official site - https://nodejs.org/en


4) Writing the first Node Js program.



// Import the built-in 'http' module
const http = require('http');

// Create an HTTP server that listens on port 5000
const server = http.createServer((req, res) => {
     // Set the response HTTP header with HTTP status and content type
     res.writeHead(200, {'Content-Type': 'text/plain'});

    // Write the response body ("Hello, world!")
    res.end('Hello World!!');
});

// Start the server and listen on port 5000
server.listen(5000, () => {
    console.log('Server is now running at http://localhost:5000/');
});

To run this code on your local machine:-
1) Copy and paste the above code into the file - helloworld.js
2) Open the command prompt and navigate to the folder where helloworld.js is saved
3) Run the command node helloworld.js
4) You should see the message "Server is now running at http://localhost:5000/"
5) Open any web browser and navigate to http://localhost:5000/ and you will see Hello World!!

Click Here to Learn Modules in Node Js