Comparison of types in Java
Source:
Theflashreads In this post, you will learn about several types comparison options in Java. The most common way to determine whether a given object is
an instance of a given class, superclass, or interface is to use the binary
instanceof operator . It includes an implicit null check and generates a compile-time error if the types are not bound. However, it does not allow the use of primitives and requires that the types be known at compile time.
If you need dynamic runtime checking
In this case, use the equivalent boolean isInstance(Object obj) method in
Class . It also includes null checking, but allows primitives:
a instanceof B
null instanceof B
a.getClass().isInstance(b);
Class<T> type = b.getClass();
type.isInstance(a);
int x = 4;
Integer.class.isInstance(x);
Checking compatibility of two types
If you need to check the subtype relationship, use the
boolean isAssignableFrom(Class<?> cls) method in
Class . This will help catch
NullPointerException .
Class<?> aClass = CharSequence.class;
Class<?> bClass = String.class;
bClass.isAssignableFrom(aClass());
CharSequence[].class.isAssignableFrom(String[].class);
Integer[].class.isAssignableFrom(String[].class);
Pattern Matching (Java 14)
if(a instanceof B b) {
b.toString();
}
Special types
enum Color { WHITE, GRAY, BLACK }
Color.class.isEnum();
Color.WHITE instanceof Enum;
String[].class.isArray();
Class<?> componentType = obj.getComponentType();
int.class.isPrimitive();
Java.io - I/O Operations in Java
Source:
Medium The content of this article is about I/O operations in Java. In Android and Java application development, input/output (Java I/O) is one of the topics that is often used, but for some reason is rarely mentioned. However, its scope of application is wide: for example, we perform I/O operations when converting a bitmap image to JPEG format or while reading/writing a regular file. The Java package java.io has all the necessary classes required to perform I/O operations. These operations are performed using threads. In turn, threads help perform read or write operations. For example, writing a message to a file.
Types of streams
There are two types of threads in Java:
- Byte Stream (byte stream)
- Character Stream
Byte stream
A Byte Stream is used to read and write one byte of data. It includes the Java
InputStream and
OutputStream classes .
InputStream helps to read data and
OutputStream helps to write data to a target (possibly a file).
Character stream
Character Stream is used to read and write one character of data. It includes
the Reader and
Writer Java classes . To understand
Reader and
Writer , you must understand derived classes such as
InputStreamReader ,
FileReader ,
OutputStreamWriter ,
FileWriter and others.
InputStream and OutputStream
InputStream is used to read data from a source (possibly a file). It's not useful on its own, but it has several derived classes such as
FileInputStream ,
ByteArrayInputStream , and
ObjectInputStream .
OutputStream is used to write data to a target (possibly a file). Its derived classes are
FileOutputStream ,
ByteArrayOutputStream , and
ObjectOutputStream .
class InputOutput {
data class Car(val name: String): java.io.Serializable
fun fileStream() {
val outputStream = FileOutputStream("kotlin.txt")
outputStream.write(1)
outputStream.write("hello".toByteArray())
val inputStream = FileInputStream("kotlin.txt")
println(inputStream.read())
val msg = String(inputStream.readBytes())
println(msg)
outputStream.close()
inputStream.close()
}
fun byteArrayStream() {
val outputStream = ByteArrayOutputStream()
outputStream.write(1)
outputStream.write("hello".toByteArray())
val readByteArray = outputStream.toByteArray()
val inputStream = ByteArrayInputStream(readByteArray)
println(inputStream.read())
val msg = String(inputStream.readBytes())
println(msg)
outputStream.close()
inputStream.close()
}
fun objectStream() {
val car = Car(name = "BMW")
val fileOutputStream = FileOutputStream("kotlin.txt")
val objOutputStream = ObjectOutputStream(fileOutputStream)
objOutputStream.writeObject(car)
val fileInputStream = FileInputStream("kotlin.txt")
val objInputStream = ObjectInputStream(fileInputStream)
val carObject = objInputStream.readObject() as Car
println(carObject.name)
fileOutputStream.close()
objOutputStream.close()
fileInputStream.close()
objInputStream.close()
}
fun bufferStream() {
val fileOutputStream = FileOutputStream("kotlin.txt")
val outputStream = BufferedOutputStream(fileOutputStream)
outputStream.write("hello".toByteArray())
outputStream.flush()
val fileInputStream = FileInputStream("kotlin.txt")
val inputStream = BufferedInputStream(fileInputStream)
val msg = String(inputStream.readBytes())
println(msg)
fileOutputStream.close()
fileInputStream.close()
}
}
Apart from the above streams, we also have
DataInputStream and
DataOutputStream . They do the same work as other threads. The difference is that
DataInput /
OutputStream is mainly used for reading/writing primitive types, while
ObjectInput /
OutputStream is mainly used for objects and so on.
Readers and Writers
In Java I/O, if we read/write data to streams, we must convert them to bytes first. Only then can we read or write them to streams.
InputStreamReader and
OutputStreamWriter do this automatically.
class ReaderWriter {
fun readerWriter() {
val outputStream = FileOutputStream("kotlin.txt")
val writer = OutputStreamWriter(outputStream)
writer.write("Hello Kotlin")
writer.flush()
val inputStream = FileInputStream("kotlin.txt")
val reader = InputStreamReader(inputStream)
println(reader.readText())
}
}
Parallel read and write
Sometimes we need multithreading support in Streams. Simply put, we want to read and write to streams from separate threads. For this we need to use
PipedInput /
OutputStream .
fun pipedStream() {
val inputStream = PipedInputStream()
val outputStream = PipedOutputStream()
inputStream.connect(outputStream)
val writeThread = object : Thread() {
override fun run() {
try {
for (i in 0..100) {
outputStream.write(i)
println("Write : $i")
sleep(100)
}
} catch (e: Exception) {
e.printStackTrace()
}
}
}
val readThread = object : Thread() {
override fun run() {
try {
for (i in 0..100) {
println("Read : ${inputStream.read()}")
}
} catch (e: Exception) {
e.printStackTrace()
}
}
}
writeThread.start()
readThread.start()
}
GO TO FULL VERSION