Learning Casting in Java

One of the most renowned programming languages at present is Java. Furthermore, Java application development continues to be a lucrative source of income for many people who are into the tech industry. The language is used to create web platforms and web apps, designed for flexibility, which enables developers to write code that runs on any machine, whatever the platform or architecture may be. Billions of computers and mobile phones throughout the world run Java.

What is Java Casting?

Casting, a process of creating a variable as a variable to another type. Software and app developers are aware of the rapid pace of industry requirements. Nonetheless, some instruments continue to remain significant even in times of regularly fluctuating trends. Undoubtedly, Java is the best choice nowadays for software programmers and developers for many reasons.
With Java casting, if a class shares an IS-A or an inheritance relationship with another interface or class, the variables could be cast to the type of each other. There are times that the cast is permitted and at times not allowed. This is because some of the cast won’t show any error at compilation time but would fail during runtime.

Basic Rules When Casting Variables

  • Casting an object from a superclass to a subclass needs an explicit cast
  • Casting an object from a subclass to a superclass
  • The compiler does not allow casts to unrelated types

Understanding Java Casting

The popularity of Java application development has been responsible for the surge in the demand for Java tutorials. Amid the many topics, Java casting remains one of the most puzzling concepts in the language, even if it’s one of the easiest to comprehend.

Basic Java Casting Rules

First and foremost there should be a definition of the term. The process of casting is to take an object of a particular kind and transform it into another. This is just one of the vital reasons that casting and conversion is an analogous process of Java. It’s important to note that casting is not Java-specific since most other languages support it as well. Nevertheless, the language has specific variables casting restrictions to not cast any variable to a random kind. It, therefore, needs Java casting rules to focus to comprehend the best ways. The Java SE 11 release also has come up with several new features “regarding casting”.

Casting Primitives

One of the main issues related to casting directly points to the two groups in Java, the primitive and reference. Primitives refer to double, int, long, float and other types of data. References on the other hand, includes type classes, interfaces or arrays. Nonetheless, one of the critical points related to casting refers to explicit and implicit changes. In some instances, the system could change the type of expression itself, based on specific requirements. Check out this example:


Int num1 = 5;
Double num2;
Double a = num1/num2;

In the last code line, automatic typecasting of num1 turns to ‘double’ automatically. The next major concern comes with explicit casting or Java typecasting. Developers should specify what type an object should be cast, in case changes don’t happen automatically. The following is the basic syntax for type casting:

Identifer2= (type) identifer1;

For instance,

num1=(int) num2;

Combined widening and narrowing primitive conversion

Developing an overall understanding of Java casting becomes easier. The widening or upscale of primitive types inclusion is converting from a smaller primitive into a bigger one. In primitives widening, the smaller value assumes a bigger container, which leaves plenty of space. So, the space located on the left is filled with zeros. Moreover, one cannot move towards a floating-point from the integer group. Check this out:

Int myint = 12; 
long myLong = myint; 
float myFloat = myLong; 
double myDouble = myLong;

Another form of casting is narrowing primitives wherein you fit a larger value than the specified type in a variable declaration, thus information loss is imperative because of discarding some bytes. Furthermore, narrowing primitives demand explicit expression regarding cast usage and provide a basic idea about Java downcasting. Understand it better with the following example:

Int myint = (int) myDouble;
byte myByte = (byte) myint;

Upcasting,Downcasting

Upcasting includes supertype casting. Downscaling, on the other hand, means casting to a subtype. Both help provide advantages, including a facility for grouping of different objects or polymorphism. Upcasting means widening or generalization through casting to a parent type.

Object Casting

  • Objects of the same class could be assigned with one another.
  • Subclass object may be assigned to a super class object. This is done implicitly and known as upcasting, which means upwards in the hierarchy, from subclass to superclass.
  • Java doesn't allow assigning a superclass object to a subclass one. To do so would require explicit casting, or known as downcasting. This required explicit conversion.

It's possible here to pass an instance of any class for ‘object’ argument, which includes all Java classes in the ‘object’ subclasses. In the case of ‘component’ argument, it’s possible to pass it in subclasses such as label, button and container in ‘java.awt’. Object casting is applicable also anywhere in a program, not just for method calls. Variables with a class ‘component’ definition allows assigning objects of the class or subclasses to object without the need for casting. The contrast is also applicable since a superclass could be used in places wherein a subclass is expected. Because subclasses have more behavior than superclasses, a significant precision loss is clear with the process of casting.

Reference Casting

Casting and conversion of reference types also is a prominent topic for casting evaluation. References involve a range of interface and type class. There are two specific methods for casting, namely, assignment conversion and method invocation. Conversion assignment has the inclusion of assigning reference type to a value of different kinds. Object reference conversion follows certain rules that apply to Java casting. The interface type conversion is only possible to an object or interface type. In casting to a new type of interface, the new interface should be superior compared to the old one.

Makefile Template for a Shared Library in C (with Explanations)

tl;dr: Save the following file as Makefile and change the source files to the ones that you intend.

# Makefile template for a shared library in C
# https://www.topbug.net/blog/2019/10/28/makefile-template-for-a-shared-library-in-c-with-explanations/

CC = gcc  # C compiler
CFLAGS = -fPIC -Wall -Wextra -O2 -g  # C flags
LDFLAGS = -shared   # linking flags
RM = rm -f   # rm command
TARGET_LIB = libtarget.so  # target lib

SRCS = main.c src1.c src2.c  # source files
OBJS = $(SRCS:.c=.o)

.PHONY: all
all: ${TARGET_LIB}

$(TARGET_LIB): $(OBJS)
	$(CC) ${LDFLAGS} -o $@ $^

$(SRCS:.c=.d):%.d:%.c
	$(CC) $(CFLAGS) -MM $< >$@

include $(SRCS:.c=.d)

.PHONY: clean
clean:
	-${RM} ${TARGET_LIB} ${OBJS} $(SRCS:.c=.d)

The above code snippet is also available on GitHub gist.

Continue reading

Pitfalls in Using a Standard “Global” C++ Function: Its C Counterpart May Be Camouflaging

A large number of C++ functions in the standard library are extended from standard C functions, such as qsort(), memcpy(), etc. Among these functions, many have overloaded their C counterparts. For example, abs() in C++ is overloaded for both integral and floating-point types, while it is only defined for int in C. These functions, however, are often unwittingly misused as global functions and produce unexpected results.

Continue reading

Pros and Cons of Automated Machine Learning

Last updated on January 14, 2020

Machine Learning is nothing but one of the subdomains of science that deals with computers or applications that are not explicitly coded to perform the task. The combination of machine learning, cognitive technology, and AI will make a lot more smooth the processing of big chunks of data and information.

Machine Learning is an application of AI (Artificial Intelligence) which ables the machines or software to adapt, learn from itself, provided the data is resourceful and sensible. Simply saying the efforts are implying to develop expert systems.

Mainly we have three categories of machine learning: Supervised Learning, unsupervised learrning, reinforcement Learning.

Since it delivers at a faster rate with better and more accurate results, machine learning is brought into practice. The engineers work day and night to predict, classify, cluster the data. The player Machine Learning is sent on the pitch of data, and Big Data to handle the problems.

Continue reading

Automatically Conceal Sender’s IP Address in Email Clients via SSH Tunneling

Last updated on November 22, 2018

Desktop email clients, such as Thunderbird and Claws Mail, are preferred over their web counterparts by many professionals and power users due to their additional convenience and security. However, one big downside is that they often expose the sender's IP address to the receivers, since many SMTP servers record the sender's IP address and put it in the header, something similar to Received: from [xxx.xxx.xxx.xxx] (my.example.com. [xxx.xxx.xxx.xxx]). This, unfortunately, puts the sender's privacy in great jeopardy, as an IP address can reveal so much information including location, ISP, and institution names.

To address this issue, one simple solution is to let the email client connect via a proxy. While a system-widely available proxy works for many users, some of us just want our email clients, but not other programs, to go through a specific proxy. In this post, I'll demonstrate how to use an email client automatically via SSH tunneling. The instructions are specifically tailored for GNU/Linux and MacOS users, as it involves some uses of UNIX commands and bash scripts; if you are on Windows, you can still follow the instructions with the help of Cygwin.

Continue reading