We've moved! — MindVault360 is now SrcForge. Better design, more content & premium notes.

Visit SrcForge →

MindVault360 has moved!

We've upgraded to SrcForge — a faster, more professional platform with better content, premium notes, and a modern design.

Visit us at SrcForge

Friday, September 27, 2024

Java FileStream

 (Tap the post to see more)


OutputStream

         Java applications use an output stream to write data to a destination; it may be a file, an array, peripheral device or socket.

InputStream

         Java applications use an input stream to read data from a source; it may be a file, an array, peripheral device or socket.

 

Below, we’ll see elaborately about these Stream.

 

OutputStream class

         OutputStream class is an abstract class. It is the superclass of all classes representing an output stream of bytes.

         An output stream accepts output bytes and sends them to some sink.

Useful methods of OutputStream

Method

Description

1) public void write(int)throws IOException

is used to write a byte to the current output stream.

2) public void write(byte[])throws IOException

is used to write an array of byte to the current output stream.

3) public void flush()throws IOException

flushes the current output stream.

4) public void close()throws IOException

is used to close the current output stream.

 

 

 

 InputStream class

         InputStream class is an abstract class.

         It is the superclass of all classes representing an input stream of bytes.

Useful methods of InputStream

Method

Description

1) public abstract int read()throws IOException

reads the next byte of data from the input stream. It returns -1 at the end of the file.

2) public int available()throws IOException

returns an estimate of the number of bytes that can be read from the current input stream.

3) public void close()throws IOException

is used to close the current input stream.

 

 


Example:

package com.java.FileStream;

import java.io.FileInputStream;

import java.io.IOException;


public class FileInputStreamExample {

public static void main(String[] args) {

FileInputStream fis = null;

try {

// Open the file

fis = new FileInputStream("example.txt");

int content;

// Read the file until the end

while ((content = fis.read()) != -1) {

// Convert byte to character and print

System.out.print((char) content);

}

} catch (IOException e) {

e.printStackTrace();

} finally {

// Close the file input stream

try {

if (fis != null) fis.close();

} catch (IOException ex) {

ex.printStackTrace();

}

}

}

}

Java FileOutputStream Class

         Java FileOutputStream is an output stream used for writing data to a file.

         If you have to write primitive values into a file, use FileOutputStream class.

         You can write byte-oriented as well as character-oriented data through FileOutputStream class.

Example:

package com.java.FileStream;

import java.io.FileOutputStream;

import java.io.IOException;


public class FileOutputStreamExample {

public static void main(String[] args) {

FileOutputStream fos = null;

try {

// Open the file in write mode (will overwrite if file exists)

fos = new FileOutputStream("output.txt");


String content = "This is an example of FileOutputStream in Java.";

// Write the string content to the file as bytes

fos.write(content.getBytes());

System.out.println("File written successfully!");

} catch (IOException e) {

e.printStackTrace();

} finally {

// Close the file output stream

try {

if (fos != null) fos.close();

} catch (IOException ex) {

ex.printStackTrace();

}

}

}

}




← Back Next →

Labels:

Thursday, September 26, 2024

Introduction to HTML


Web pages and web apps are often created and structured using HTML (HyperText Markup Language). It makes use of tags or components to specify the structure and content of a webpage. The foundation of all online development, HTML allows web browsers to display text, pictures, multimedia, and other content.

Key Concepts of HTML:

Markup Language: Not a programming language, but a markup language is HTML. It is made up of tags that "mark up" content on a webpage according to specific guidelines.

HyperText: This is the capacity to use hyperlinks to link to other web sites. You can make clickable links in HTML that take readers to other pages or specific areas of the same page.

Structure of an HTML Document:
A simple HTML document contains distinct tags that instruct the browser on how to understand the information and a well defined structure. The principal elements consist of:

DOCTYPE Declaration

The browser is informed that the page adheres to the HTML5 specification (the most recent iteration of HTML) by the declaration.

<!DOCTYPE html>


HTML Document Structure:

<!DOCTYPE html>
<html>
  <head>
    <title>Page Title</title>
  </head>
  <body>
    <h1>Hello, World!</h1>
    <p>This is a simple HTML document.</p>
  </body>
</html>


<html>: The root of an HTML document is the <html> element. It contains all other HTML elements contained within.

<head>: Metadata (information about the HTML content) such as the title, character set, and external resources (such CSS or JavaScript files) are contained in the <head> element.

<title>: describes the webpage title that appears in the browser tab.

<body>: The whole webpage's visible content, including text, photos, links, and more, is contained in the <body> element.






Labels:

Wednesday, September 25, 2024

Python Datatypes


 The various values that a variable might store are represented by data types in Python. Since Python is a dynamically-typed language, variables don't require their data type to be declared explicitly. Python uses the value that is assigned to the data to identify its type.

Numeric Data Types:

Numerous numeric kinds, such as complex numbers, floating-point numbers, and integers, are supported by Python.

int (Integer): represents complete numbers without a fractional part, both positive and negative.

Examples:

x = 10       # Positive integer
y = -5       # Negative integer
z = 0        # Zero

float (Floating-Point Number): Represents real numbers with a fractional part (decimal point).

Examples:

x = 10.5     # Positive float
y = -3.14    # Negative float
z = 0.0      # Zero as a float

complex (Complex Number): represents numbers that have two parts: an imaginary part (represented by j for the imaginary unit) and a real part.

Examples:

x = 2 + 3j   # Complex number (2 is the real part, 3j is the imaginary part)
y = -1j      # Imaginary number

Sequence Data Types:

In Python, sequences represent ordered collections of objects.

String:

A string, denoted by str, is a string that has one, two, or three quotations around it.
Strings are unchangeable once they are created; they cannot be altered.

Example:

name = "Alice"      # Using double quotes
greeting = 'Hello!' # Using single quotes
multi_line = '''This is
a multi-line string.'''  # Using triple quotes

List:

Describes a mutable, ordered set of elements. Elements in lists can be of many sorts, and their index starts at 0.

numbers = [1, 2, 3, 4]    # List of integers
mixed = [1, "apple", 3.14] # List with mixed data types
nested = [[1, 2], [3, 4]] # Nested list

Tuples:

 Denotes an immutable, ordered set of objects. A tuple's elements cannot be altered once it has been constructed.

point = (3, 4)           # Tuple of integers
info = ("Alice", 25, 5.6) # Tuple with mixed data types
single = (42,)           # Single-element tuple (note the comma)

Mapping Data Types:

Mappings are collections of key-value pairs.

Dictionary:

Indicates a mutable, unordered set of key-value pairs. Values can be any kind, but keys (such as texts, numbers, or tuples) have to be distinct and unchangeable.

person = {
    "name": "Alice",
    "age": 25,
    "is_student": False
}
print(person["name"])  # Access value by key

Set Data Types:

Sets are unordered collections of unique elements.

Set: represents a changeable, unordered set of individual objects. The curly braces {} are used to define sets; duplicates are not permitted.

Example:
fruits = {"apple", "banana", "cherry"}
fruits.add("orange")  # Add an element

frozenset: represents a set's unchangeable version. Elements cannot be added to or deleted after they are created.

Example:

frozen_fruits = frozenset(["apple", "banana", "cherry"])

Boolean Data Type: Booleans represent one of two values: True or False. The truth value of an expression is represented by the Boolean type bool. Frequently employed in flow control and conditions

Example:

is_student = True
is_adult = False

Binary Data Types: In order to handle files, pictures, and other sorts of data, these data types are necessary for working with binary data.

bytes: represents a byte sequence that is unchangeable. An integer between 0 and 255 makes up each byte.

b = b"hello"  # A byte string

Bytearray: represents a changeable byte sequence.

b_arr = bytearray(b"hello")
b_arr[0] = 72  # Modifying the first byte

memoryview: useful for big datasets, it represents a view of another binary object without transferring any data.

b = bytearray("hello", "utf-8")
mem_view = memoryview(b)


None Type: Represents the absence of a value. A null or no value is defined by using none.
frequently used to denote "nothing" or as the default value.

Example:
x = None


Dynamic Typing in Python: In Python, a variable's data type is automatically ascertained from its assigned value. Even during execution, you can modify a variable's type:

Example:
x = 10      # int
x = "Hello" # Now it's a string


















← Back Next →

Labels:

Tuesday, September 24, 2024

Date and time class in Java

(Tap the post to see more)


Java does not have a built-in Date class, but we can import the java.time package to work with the date and time API. The package includes many date and time classes. For example: 

Class

Description

LocalDate

Represents a date (year, month, day (yyyy-MM-dd))

LocalTime

Represents a time (hour, minute, second and nanoseconds (HH-mm-ss-ns))

LocalDateTime

Represents both a date and a time (yyyy-MM-dd-HH-mm-ss-ns)

DateTimeFormatter

Formatter for displaying and parsing date-time objects

Display Current Date

To display the current date, import the java.time.LocalDate class, and use its now() method:

 Example:

package com.java.DataAndTime;


import java.time.LocalDate; // import the LocalDate class


public class Current_date {


public static void main(String[] args) {

LocalDate myObj = LocalDate.now(); // Create a date object

System.out.println(myObj); // Display the current date

}


}

Display Current Time

To display the current time (hour, minute, second, and nanoseconds), import the java.time.LocalTime class, and use its now() method:

 Example

package com.java.DataAndTime;



import java.time.LocalTime; // import the LocalTime class





public class Current_time {

public static void main(String[] args) {

LocalTime myObj = LocalTime.now();

System.out.println(myObj);

}


}

Display Current Date and Time

To display the current date and time, import the java.time.LocalDateTime class, and use its now() method:

Example

package com.java.DataAndTime;


import java.time.LocalDateTime; // import the LocalDateTime class





public class Current_date_Time {


public static void main(String[] args) {

LocalDateTime myObj = LocalDateTime.now();

System.out.println(myObj);

}

}

Formatting Date and Time

We can use the DateTimeFormatter class with the ofPattern() method in the same package to format or parse date-time objects.

Example

package com.java.DataAndTime;



import java.time.LocalDateTime; // Import the LocalDateTime class

import java.time.format.DateTimeFormatter; // Import the DateTimeFormatter class




public class Formatting_Date_Time {


public static void main(String[] args) {

LocalDateTime myDateObj = LocalDateTime.now();

System.out.println("Before formatting: " + myDateObj);

DateTimeFormatter myFormatObj = DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm:ss");


String formattedDate = myDateObj.format(myFormatObj);

System.out.println("After formatting: " + formattedDate);

}

}

The ofPattern() method accepts all sorts of values, if you want to display the date and time in a different format. For example:


Value

         Example     

yyyy-MM-dd

         "1988-09-29"      

dd/MM/yyyy

         "29/09/1988"      

dd-MMM-yyyy

         "29-Sep-1988"    

E, MMM dd yyyy

         "Thu Sep 29 1988"



← Back Next →

Labels: