Archive for the ‘Java’ Category:

How to Use ForEach in JavaScript

JavaScript is one of the most popular development tools or languages in use for creating websites and client-side applications today. Its capabilities and power are demonstrated through JavaScript’s presence in social media sites such as Facebook and Twitter, as well as adoption by powerful search engines that include Google.


As a JavaScript developer, you’re always on the lookout for tips, tools, and methodologies that can make your software engineering life easier, more productive, and more efficient.


Among these techniques is the appropriate use of JavaScript’s “foreach” method of handling arrays and controlling program flow. You probably are quite accustomed to using the “for” loop in your programming, but there are several nuances and scenarios where the foreach method may contribute to a more efficient way of coding for your application.

What is the ForEach Method?

Foreach is a coding method that controls the flow of logic when handling an array or some collection of sequential elements.

As with the for logic method, foreach in JavaScript is utilized to perform a certain set of logic or an operation on the input elements. Unlike a for loop, foreach utilizes no counter or iteration value to control the execution of the loop. Foreach essentially tells the program to perform the specified logic on every entry in the collection of elements.

By comparison, JavaScript’s for loop includes a combination of three parameters or statements, defining the execution of the logic to be executed through the loop code. For example:

  • For (i = 0; i < 20; i++) {  }
  • i = 0 initializes the iteration to 0
  • the loop will execute as long as the iteration index remains less than 20
  • i++ will increment the iterator by 1

Logic coded between the brackets will be executed for each iteration of the loop. This basic functionality of loop processing is a powerful and useful cornerstone of JavaScript. It has been utilized for its versatility in creating iterative code by practically any developer who was to put fingers to a keyboard.

The trick when coding a for loop is knowing where to set the iteration value – setting it too low could result in fewer than all elements in the input array being successfully processed through the intended logic of the function.

ForEach operates in a different manner, giving you a method that can perform a function on every element in an array, map, or set.

The most common use of foreach method is to loop through a sequence of elements and perform the same logic for every element in the array or collection. There is no explicit counter for the number of items to be processed through the foreach loop – every element is processed.

Here is a simple illustration of JavaScript code utilizing a for loop vs. a foreach method:

var sample_array = ['a', 'b', 'c'];

        for (var i=0; i<sample_array.length; i++) {


            //a b c


        sample_array.forEach(function(current_value) {


            //a b c


ForEach Syntax in JavaScript

Foreach processing is supported in many languages besides JavaScript, although the details of the syntax vary from one language to another.

In JavaScript, the syntax for the foreach array method takes on the following syntax:

Array.forEach(function (currentValue, index, arr), thisValue)

Parameters include:

  • Function – the function that will be executed for each array element – this is referred to in JavaScript as the callback function
  • currentValue – this is the value of the current element
  • index – (optional) array index of the current element
  • arr – (optional) the array object the current element is part of
  • thisValue – (optional) a value that you want to pass to the called function as its “this” value provides you with some very basic examples of coding foreach loops, which will give you a good foundation for the syntax and construction of this method.

How to Use ForEach in JavaScript

Now that you know what foreach does, how do you use it effectively?

You need to be aware of certain factors that apply to using foreach methods on arrays:

  • forEach() sets the range of elements to be processed in the array before execution starts with the first element. This means that any elements that get added to the array after execution begins will not be processed by the foreach loop.
  • If the content or values of array elements change after execution begins, the value recognized by the called function will be the value at the time that element is executed.
  • If elements in an array have no values, the function is not executed.
  • Also, elements that are deleted from the array before they are processed through the function will not be processed.
  • Another caution – if elements that have already been processed are deleted, the process of shifting elements in an array will cause elements later in the array to be omitted from processing. To illustrate this effect, imagine an array that contains values of 10, 20, 30, and 40, and logic that is to summarize the values. If the second entry is deleted, while processing the array in a foreach loop, 30 and 40 will be shifted up. With the element containing 30 now in the second position, it will be skipped.

Foreach does not make a copy of the array before executing the loop, which could subsequently impact your results. This may not be an important factor in your application, but you must be aware of the condition.

Foreach method will not alter the content of the original array, although the function called may do so.

Each of these attributes of foreach processing is important to your programming design, especially when working with arrays that may be highly volatile in nature.

ForEach Browser Support

Nearly every popular browser supports the forEach JavaScript method, depending on the version in use:

  • Google
  • Internet Explorer (Ver. 9.0 and higher)
  • Firefox (Ver. 1.5 and higher)
  • Safari
  • Opera

Browser compatibility makes use of the method nearly universally acceptable for your web page or other application development use.

Reasons to Use ForEach in JavaScript 

There are reasons you may want to elect to use foreach methods in your code over other options including for loops:

  • Readability – many developers view foreach loops as more comprehensive when reading code
  • Lines of code may actually be reduced, with no need to define extra variables for controlling iteration
  • Speaking of iteration, foreach reduces the likelihood of making mistakes with index handling, such as setting an index to 1 instead of 0, also known as “off-by-one” errors. The result can be a loop that includes one too few iterations, or one too many.

On the other side of the coin, there are instances where you may want to break out of a loop early, before processing all entries in an array. This could be where you’re searching for a certain name, and want to break out once you encounter it, rather than stepping through every element in the array. For loop has an easy method of breaking out of the iteration.

Breaking out of a ForEach Method in JavaScript

Can you break out of a foreach loop? Yes, there are methods available to break out of a foreach loop, such as forcing an exception based on detecting some condition.

Like many developers, you may view this as contrary to why you would utilize the foreach method over a standard for loop, since throwing an exception is not a “clean” programming methodology or best practice. This is stated very plainly in an MDN Documents page:

“There is no way to stop or break a forEach() loop other than by throwing an exception. If you need such behavior, the forEach() method is the wrong tool, use a plain loop instead. If you are testing the array elements for a predicate and need a boolean return value, you can use every() or some() instead.”

A full discussion on breaking out of foreach methods and alternatives is available online, as well.

Learning More About ForEach in JavaScript

There are other variations of foreach methods available to you, if processing an object other than an array:

NodeList.forEach() performs the same function as the array foreach method, but utilizes a NodeList as opposed to an array.

There are many examples and tutorials online for developing your skills in the use of foreach in JavaScript, and YouTube offers many videos with examples and discussions on the use of the method.

What Does the JavaScript Split Do?

JavaScript is perhaps the most popular scripting language in use for client-side web page development, world-wide. It continues to evolve and add features that enable new functionality and performance improvements, providing developers with enhanced toolsets for building robust, efficient applications.


One of the areas where JavaScript shines is in the management and manipulation of arrays.

One method available to you is the split() method. This method has been included in the JavaScript library of methods ever since the ECMAScript 1 standard. ECMA (European Computer Manufacturers Association) sets the standards for scripting languages, with a special focus on JavaScript standards.


JavaScript is the most well-known, popular technology that forms the basis for the ECMAScript Language Specification. The ECMA Standard is continuously evolving, now in its 9th edition, formalized in June of 2018, with contributions from many members of the development community.

JavaScript Split Method – What it Does 

JavaScript provides the split() method to split a string into an array comprised of substrings, returning the new array to you.

Split syntax is very simple on the surface:

string1.split(separator, limit)

  • string1 – the name of the original string to apply the method to
  • separator – the character to be used for executing the split of the string. If this parameter is not provided, the result will be an array with one item, which contains the entire original string. The separator is not limited to a single character. If you specify a separator with more than one character, the exact and entire string of the separator must be found before the split point will be recognized.
  • limit – this optional value specifies the maximum number of splits to be generated. The split method stops when the limit is reached. If the split execution reaches this limit, no additional items will be included in the resulting array, so all data from the original string will not be represented.

Results – after the split is performed, the result will be an array containing the values that have been split.

Programming notes:

  • Split() method does not alter the original string in any way
  • Split() can only be used with strings, not arrays
  • If you provide an empty string for the separator value (“”), the result is that the string is split between each character.

A simple example:

var string = "Hello reader how are you?";

var result = string.split(" ");

Your array result:

Let’s try another example, omitting the second parameter this time:

var string = "Hello reader how are you?";

var result = string.split();

Now the result will appear in your array as:
Hello reader how are you? – as you can see, the entire string has been “split” to the new array
This time let’s try the same string, with a blank separator, and take a look at the result:

var string = "Hello reader how are you?";

var result = string.split("");

Your resulting array:
H,e,l,l,o, ,r,e,a,d,e,r, ,h,o,w, ,a,r,e, ,y,o,u,?
Each character in the string has been split, including the spaces between words.
Notice that since a space was not used as a separator, the spaces are retained in the resulting array.
Adding in the parameter to limit the split to 3 values:

var string = "Hello reader how are you?";

var res = string.split(" ", 3);



Now let’s use a split value such as the letter “e”:

var string = "Hello reader how are you?";

var result = string.split("e");

Here is the resulting array:

H,llo r,ad,r how ar, you?

Putting the JavaScript Split Method to Use 

Now that you know the basics of what the JavaScript split does, you need to know how to use it in your application.  The split method is sometimes confused with JavaScript’s slice and splice methods, so it’s important to understand specifically what the JavaScript split does.

JavaScript slice() and splice() perform their functions on arrays, where split() works with strings, dividing a string into substrings, then returning the results in the form of an array.

programming code


Split method coding is very simple, with only minimal parameters needed to perform its function. Putting the method into practical use can be a little more complicated, once you apply a separator and begin to evaluate the results returned in the array.

One of the most common uses for using split is using the method with empty parameters:


This returns a comma-separated array for each character from the original string, which you can subsequently access by index for easily working with the array.

Determining the number of elements in the array is an effective tool for evaluating how many fields were returned in a keyed entry in your web application. A good example would be finding the first and last names entered in a web page string.

You may also find this method very useful in splitting the contents of a hyphen-entered phone number:

var inp_phone = “ 614-555-1212”;

var phone_split  = inp_phone.split(“-“);

Your new array will contain the numeric portion of the phone number, with the hyphens split out

Another common use would be to split an email address, to drop the “@” element from your resulting array:

var inp_email = “”;

var email_split = inp_email.split(“@“);

the resulting array will omit the “@” value, containing: President,

Browser Support for JavaScript Split

You can utilize the split method in JavaScript freely, as all popular browsers support the function:

  • Chrome
  • Internet Explorer
  • Firefox
  • Safari
  • Opera

When to Use the JavaScript Split Method

String objects are usable by many functions in JavaScript, but others are only useful in handling and manipulating information in arrays. String methods include:

  • match
  • search
  • repeat
  • substr

There are, of course, many other methods that function with string content. While some do not have an impact on the original string, others can transform string data, such as toLowerCase() and toUpperCase().

But there are many instances when you need to work with information in an array. Split() method is the tool that can transform string data to an array, even providing powerful selection as it performs the string-to-array transformation.

Arrays are a basic element of JavaScript, and contain variables of multiple types. Presenting information in arrays offers all the flexibility you need for building complex web applications

Knowing your data content is key to the most efficient context of your split method. Special characters contained in your string could potentially alter the results of your array if they duplicate the character you specify as the separator.

Unique Ways to Use the JavaScript Split

If the separator you provide is a regular expression that includes capturing parentheses, each time the separator matches, the results of the capturing parentheses will be spliced into your output array.

An array may be used as a separator in the split to extract string content that contains the array elements.

Split can also be utilized to reverse a string, although this may not be the most effective way to accomplish such reversal.

It’s important to select your separator carefully, due to the nature of how split process the string and the results that appear in your array when the value or separator array are encountered in the data.

Are There Times When You Should Not Use Split?

Certainly, if your data is in a string, and standard JavaScript string methods will suffice for your application, the split function is unnecessary. Performing the function will utilize cycles and add memory requirements for the new array, both of which can be avoided.

When your data is unknown or contains unpredictable characters, use caution with the split method, since separator values could encounter data that produces results that negatively impact your application.

Becoming Proficient with JavaScript and Split

Examples and discussions of how some developers have addressed challenging or unexpected exception conditions are available on JavaScript community websites and online video tutorials.

If you need more details, you can always invest in a JavaScript course at a local community college, pick up a good JavaScript book, or even take online courses.

Each of these educational options can open doors to a rewarding and lucrative career as a JavaScript developer, one of the most in-demand technical positions in the industry today. alone lists openings for over 40,000 JavaScript developers nation-wide, in full-time, part-time, and contract positions.

Developing your JavaScript skills with a working knowledge of split() and other methods may get you on your way to a promising development career.

Java Tips: How to Convert String to Int

Java gives you all the tools you need to create robust, high-performing websites and applications for a variety of devices, from enterprise mainframes, to tablets, to smartphones and other mobile devices.


Building such applications, of course, includes accepting data from users in the form of keyed or uploaded data to be validated and processed by your programs. Data comes in many forms that include characters, numbers, and symbols.

Java supports multiple forms of data, among them are string and integer objects. One of the data objects most commonly utilized for accepting and working with data is the basic form – a string object.


But to utilize string data for specific purposes such as performing calculations or storing in database fields that have numeric properties, the string content must be transformed to an integer object. Attempting to perform an arithmetic function on a string object will get you in trouble with an error occurring immediately. You must first transform the numeric value in the string to an acceptable data type.


That being the requirement, the question is – how to convert string to int object content.


Java Has Options to Convert String to Int

Regardless of how new you are to Java programming, it’s quite likely that your first experience will require the function of performing numeric operations on data that is initiated in a string object form. Knowing how to make the conversion to fields you can treat as numbers will be critical to writing a successful application.

Java provides multiple ways to transform string content into integer objects. There are multiple types of integer objects, to make the subject more confusing. Java provides four primitive integer types that store whole numbers of varying sizes:

  • Byte – 1-byte integer that can contain a range of values from -128 to 127
  • Short – 2-byte integer with a range between -32,768 to 32,767
  • Int – 4-byte integer with range between -2 billion and 2 billion
  • Long – 8-byte integer with range between -4,000 trillion to 4,000 trillion

The most common selection for an integer object is int, due to its range for most numeric values

When you know a small value will be used for a particular function, byte or short can provide an efficient use of memory. Long is an exception, but may be applicable for some applications.

These data types indicate to your program not only that the field is a numerical variable, but also the range of values it can contain, and the operations the variable can be have performed on it.

The issue is that it’s often the case that you begin with a string data type, which must be transformed to an integer type to perform numeric functions. Two options are available to you in Java:

Option 1 – Integer.parseInt()

A simple example:

string number = “50”;

int result = Integer.parseInt(number);

the result will be a primitive integer with a value of 50

The parseInt syntax is:

parseInt(string s, int radix)

s = the string to be converted to an integer – the sign needed for the integer may also be specified

radix – the radix to be used during string parsing

You can also perform a simple conversion from string to an integer with this function:

parseLong() – parses the string to Long integer data type

Option 2 – Integer.valueOf()

String number = “50”;

Integer result = Integer.valueOf(number);

The result is a new integer object with a value of 50

Integer.valueOf syntax is:

Integer valueOf(int a)

This results in a new integer representing the parameter a

The same syntax applies to variations of the valueOf and parse functions for other data types:

  • Short.valueOf
  • Long.valueOf
  • parseShort
  • parseLong

The primary difference between parseInt and valueOf functions is that parseInt returns a primitive int, but valueOf returns a new integer object. In fact, valueOf actually uses the parseInt function behind the scenes.

With either of the options, if the string contains a value that cannot be parsed to a valid integer, the code will throw a NumberFormatException error.

  • String1 = “Hello world 12345”; would result in an exception
  • String1 = “12345”; will be parsed without and exception being thrown

Due to the potential for any string containing a value that cannot legitimately be parsed, your code should always either:

  • Validate the string content prior to attempting to convert a string to int.
  • Handle the NumberFormatException within your program.
  • Strip any invalid characters from the string before parsing (possible logging a warning that data has been omitted).

Selecting the Right Type of Java Int Object

With the multiple options available to you for numeric variables, you need to be cautious in the object type selected for individual functions.

Values that you know will be small such as counting entries on a web page screen may easily be contained within a byte or short data type. Int type will handle most typical application values, but if you may encounter large values, long data type can be your best option.

If you opt for a smaller capacity data type but encounter larger values, you could conceivably overflow the capacity of your integer object.

Examples of How to Convert String to Int?

You have the basics now for functions that allow you to convert strings to numeric variables using integers of different types, so let’s look at some additional examples to illustrate the coding.

Additional example1 using Integer.parseInt()

String strTest1 = "500";

    int iTest = Integer.parseInt(strTest1);

    System.out.println("Original String:"+ strTest1);

    System.out.println("Converted to Int:" + iTest);

This routine will result in the original string of “500” converting to the integer object iTest, displaying both the original string and new integer

Additional example2 using Integer.parseInt()

String ostr="123";

                int inum = 456;

                /* convert the string to int value

                 * ,making the value of inum2 123 after

                 * conversion


                int inum2 = Integer.parseInt(ostr);

                int sum = inum+inum2;

                System.out.println("Result is: "+sum);

Additional example1 using Integer.valueOf()

String strTest1 = "1000";

    int iTest = Integer.valueOf(strTest1);

    System.out.println("Original String:"+ strTest1);

    System.out.println("Converted to Int:" + iTest)

Additional example2 using Integer.valueOf()

String istr="-234";

                //int variable

                int inum1 = 110;

                /* Converting String to int in

                 * the value of variable inum2 negative after

                 * conversion


                int inum2 = Integer.valueOf(istr);

                //Adding up inum1 and inum2

                int sumo = inum1+inum2;

                //displaying results of sumo

                System.out.println("Result is: "+sumo);

Final results of the valueOf and parseInt methods of converting string data to int objects are the same, aside from the type of the object returned.

In Summary

In order to perform any numeric functions such as arithmetic on an object in Java, the information must be in contained in a valid numeric object type. Even if a string contains all numeric data, an error will occur if you try and use it for any type of calculation.

programmer working on codes


You can perform this conversion from string to int with two Java coding methods:

  • Integer.valueOf(string)
  • Integer.parseInt(string)

The difference between the two:

  • parseInt returns a primitive int value
  • valueOf returns an Integer class object with the converted value
  • valueOf may optionally contain a negative value, provided by a minus sign

Regardless of the method you choose in your Java development efforts, the primary considerations to keep in mind are:

  • Be sure the int object you define from the string conversion has the capacity you can conceivably extract from the string – if in doubt, use a larger data type.
  • Select an integer type that will allow all functions and values you anticipate, such as negative values or floating point operations.
  • Verify the string contains valid data that can be parsed successfully, or at least include code to detect any exceptions thrown from a conversion error.

More Details for Java Conversion String to Int

There are many great resources available to you as a Java developer, to gain additional knowledge of how to convert string to int values.

Each of these options will provide an amazing array of how-to instructions on Java programming topics, with a variety of examples, drawing from the experience of seasoned Java developers.

How Does HashMap Work in Java?

Java is one of the most commonly used programming languages worldwide.

With the Java Virtual Machine (JVM) incorporated on an impressive array of platforms from enterprise mainframes to smartphones, compiled Java applications can run on nearly any device imaginable.

Java developers remain in high demand. Although estimates vary among sources, there is a population of between 9 and 10 million Java developers in the global application development community.

To fellow Java developers, this means there is essentially an unlimited resource of forums, technical expertise, and experience available to answer questions, share code examples, and discuss challenges and solutions related to coding Java applications.

One subject that generates considerable mention among developers is – how does HashMap work in Java?

What Is HashMap?

hashmap in java

First, you need a good understanding of what HashMap is in Java.

HashMap is a data structure that allows programs to store and retrieve an object in constant time, assuming you have the key available.

Hash functions come into play in linking the value to th associated key in HashMap. Java’s implementation of HashMap stores data with keys such that each object is stored utilizing a pair that includes the key and value.

How Does HashMap Work in Java?

Java Logo

Utilizing HashMap in Java is a fairly simple concept, at least at a high level:

Objects are stored utilizing a HashMap method call: put (key,value). The object can subsequently be retrieved with another method call: get(key)

Calling the put hashcode() method of a key object generates the hash function so that the hash map can assign a location in the hash table for the object, which will then store that value with a corresponding key.

Internally, HashMap retains the mapping in a Map.Entry form, as an object that contains both the key and the accompanying value of the object. Using a hashing algorithm, the key/value combination is assigned a “bucket” location in the hash table, which is actually an internal array with the bucket location being an index into the array.

By calling the get() method with the key, HashMap is then able to return the value stored in that location of the table, again using hashing process to locate the key’s location in the array.

HashMap internally calls hashcode() with the key object to determine the actual hash value that is used to locate a bucket for the object. The hash value will also be utilized to locate the bucket for that key when it is retrieved through a get() method.

Effective Java

Effective Java
  • Java has changed dramatically since the previous edition of Effective Java was published shortly after the release of Java 6. This Jolt award-winning classic has now been thoroughly updated to take full advantage of the latest language and library features. The support in modern Java for multiple paradigms increases the need for specific best-practices advice, and this book delivers.
  • As in previous editions, each chapter of Effective Java, Third Edition, consists of several "items," each presented in the form of a short, stand-alone essay that provides specific advice, insight into Java platform subtleties, and updated code examples. The comprehensive descriptions and explanations for each item illuminate what to do, what not to do, and why.
  • Joshua Bloch
  • Publisher: Addison-Wesley Professional
  • Edition no. 3 (01/06/2018)

Head First Java

Head First Java, 2nd Edition
  • O Reilly Media
  • Kathy Sierra, Bert Bates
  • Publisher: O'Reilly Media
  • Edition no. 2 (02/19/2005)
  • Paperback: 688 pages





HashMap Storage and Collisions

The issue with the HashMap array is that its size is fixed, so there are only so many buckets available in the table. This makes it conceivable that two objects (pairs of key,value) could have the same hashcode value. This is known as a collision. When this occurs, HashMap will generate a linked list, retaining the original bucket location and creating a “next” node for storing the new entry.

HashMap keys are immutable, so updating the bucket assignment is not an option, which is why linked lists are the solution to collisions.

When a get is used that equates to a bucket that includes a linked list, the method can include the equal() operand, which instructs the method to return the object where the key is equal to the requested key. HashMap will follow the linked list and return the correct value (the object in the list where the key matches).

Coding to allow for a linked list is relatively simple, when you’re aware of this phenomenon:

call keys.equals() method will return the correct node using the linked list to find the key that matches the request.

Since linked lists may result in performance issues due to proceeding through the list, Java 8 included an enhancement that replaces linked lists with a balanced tree structure, once the linked list exceeds a certain defined threshold. This improves worst-case performance problems related to HashMap collisions.

HashMap Variations

HashMap in Java includes a number of methods and subclasses that may be useful in certain applications:

ConcurrentHashMap differs from HashMap in several ways:

  • ConcurrentHashMap is thread-safe, where HashMap is not
  • HashMap is a better performer, partly because it is not thread-safe, allowing multiple uses simultaneously. ConcurrentHashMap can require threads to wait, slowing performance
  • ConcurrentHashMap does not allow nulls for key and values, where HashMap does

LinkedHashMap is a subclass of HashMap that provides a method of maintaining insertion-order. This technique utilizes a doubly-linked list to retain sequence of the objects in the data structure.

When to Use HashMap in Java

There are many good reasons to utilize HashMap in Java applications:

  • It is fast – hash methods for put and gets results in high performance
  • Storage and retrieval by key is required
  • Entry sequence is not an issue – this is not retained with a HashMap data structure
  • Reference by index is not needed

When key reference is needed for your application, HashMap is a great solution.

Reasons Not to Use HashMap

There are a variety of storage or application reasons not to utilize HashMap in Java:

  • When keys are not required or present in a data structure, such as sequential data objects that will not incorporate random (key) retrieval, arrays or linked lists would be more appropriate for your application.
  • If values can change after saving, HashMap is not a reasonable choice, since hash values are immutable.
  • Hash table storage can be costly strictly from a size viewpoint.
  • If you’re only storing a list of objects, an ArrayList or array would be a better choice.
  • Where order is critical, HashMap will simply not meet your requirements.
  • Since HashMap is not synchronous, it is not a good choice when there will be multiple concurrent threads reading and writing to the same map.

As a rule, HashMap in Java is not a good choice when sequence is important or keys are not needed.

Java: A Beginner's Guide

Java: A Beginner's Guide, Eighth Edition
  • Herbert Schildt
  • Publisher: McGraw-Hill Education
  • Edition no. 8 (11/02/2018)
  • Paperback: 720 pages

The Insiders' Guide

Elements of Programming Interviews in Java: The Insiders' Guide
  • Adnan Aziz, Tsung-Hsien Lee, Amit Prakash
  • Publisher: CreateSpace Independent Publishing Platform
  • Edition no. 2 (10/06/2015)
  • Paperback: 482 pages





Continuing Enhancements for HashMap in Java

Developers can benefit from the continuous improvements in how HashMap works in Java, including updates made in Java Development Kit (JDK) versions 1.7 and 1.8:

Reduction in memory allocation requirements – empty maps formerly consumed memory that was not needed, so improvements have been implemented to limit the unnecessary demands for memory.

Collision handling – to avoid excessive linked lists caused by poor hashing that previously resulted in a performance impact, Java replaced that functionality with a true binary balanced tree that can be interpreted much more efficiently.

Overall performance of HashMap functions has improved on average by 20% in Java 8 as compared with Java 7. Even with poorly-derived hash map keys, HashMap returns the objects for the key specified much more quickly with the most current versions of Java, largely due to the elimination of the adoption of lengthy linked lists (again, where a threshold has been reached for use of a linked list).

Putting Your Knowledge of How HashMap Works in Java to Use

Java Logo

From a practical viewpoint, knowledge of how HashMap works, when to use it in applications, and when it makes more sense to avoid this data structure can play a contributing role in landing a career position as a Java developer. In fact, some of the most frequently asked questions are covered in the preceding material, so use this information to your advantage in responding to interview questions such as:

Q: How does the put() method work with HashMap in Java?

A: Hashcode() is called to generate a location/bucket to store the object, which is a paired value that includes the key and data

Q: What happens when you attempt to store (put) a key that already exists in HashMap?

A: The old value is overridden with the new value – no exception is returned for this condition.

Q: What happens when HashMap creates a second entry in the same bucket?

A: This is a HashMap collision. When it is encountered, HashMap will create a linked list for the duplicate entries, so that subsequent gets with equals() specified will follow the link to return the correct object from the linked list, that matches the key requested. When the linked list exceeds a set threshold, the linked list is converted to a binary balanced tree structure, for better performance.

Q: Does HashMap support duplicate keys?

A: No – duplicate keys are not allowed. If the same key is put() to the table, the value will be replaced.

Hardcore Java 1st Edition

Hardcore Java
  • Used Book in Good Condition
  • Robert Simmons
  • Publisher: O'Reilly Media
  • Edition no. 1 (01/01/2004)
  • Paperback: 400 pages

Java for Beginners 2018

Java for Beginners 2018
  • Mr Kotiyana
  • Publisher: CreateSpace Independent Publishing Platform
  • Paperback: 369 pages





With a good grasp of how HashMap works in Java, you’re equipped to make an informed decision on the use of this data structure for your Java application development.

What Is An Insertion Sort Algorithm – Its Basic Definition

If you need to get a good understanding of what an insertion sort algorithm is, the best way to start is with a basic definition of what an algorithm is.

An algorithm in its purest sense is just a formula or method for solving a problem. Even a simple task may include an algorithm by utilizing a standard process for arriving at a solution. This could include a variety of types of problems, and their associated resolutions:

  • Manual tasks such as how to select the best grocery products

  • Solutions to mathematic problems

  • Computer system processes that solve business problems

Modern computer applications are where insertion sort algorithms enter the picture. In computer science and mathematics, an algorithm is a defined specification that eases the burden of solving even complex problems.

By formalizing a process or function as a proven algorithm, programmers and scientists can reuse code and formulas to solve business and mathematical problems more efficiently.

Computer algorithms are essentially program logic that receives input values and produces consistent, reliable results as output. Algorithms can be applied for automated and consistent reasoning, performing calculations, and yes – sorting.

Types of Sorting


There are multiple methodologies and algorithms for conducting computer sorting:

Select Columns Layout
  • Insertion sort

  • Bucket sort

  • Bubble sort

  • Selection sort

  • QuickSort

  • Counting sort

  • Merge sort

  • Radix sort

  • and others

Even within those variations in processing, and the applicable uses for each, there are additional classifications such as recursive insertion sort, binary insertion sort, recursive merge sort, and so on.

Insertion Sort Explained

So just what is an insertion sort algorithm?

Insertion sort algorithms work much in the same way as you would in sorting a deck of cards. Assume someone gives you stack of playing cards, already in order (or even a single card). Then they give you another card, asking you to place it in the proper sequence in the deck. You will scan through the deck you have, then insert the new card in its place.

Next, you’re given another card, with the same request – put in the deck – in sequence. With many iterations of cards passed to you, the process is repeated. This is essentially the process in working with an insertion sort algorithm.

For each iteration, processing is required to shift the array to insert the new entry, which can be an important factor in utilizing an insertion sort when large arrays or data sets are anticipated. In effect, the insertion sort algorithm proceeds in this manner:

  • Select the first element (since it is the first one, it is already in place, and no shifting is necessary)

  • Pick the next entry from the input array

  • Compare the value against the sorted list

  • Shift all elements higher than the new entry to the right

  • Insert the new entry

  • Repeat the process until the entire input set is complete, resulting in a sorted output set

This provides a reasonably straight-forward process, yet also reveals how the algorithm can result in considerable processing, when the input set is composed of extremely large arrays.

Variations of an Insertion Sort


Within the realm of insertion sort processing, there are additional variations:

Binary insertion sort - binary insertion sort can be used to reduce the actual number of comparisons over a normal insertion sort. By utilizing a binary search function to insert an element in the proper position of the output set, less processing is required. Normal insertion sort will require multiple iterations for comparison, depending on the size of the input array. In a worst case of large arrays, the binary insertion sort can have significant performance advantages.

Recursive insertion sort–insertion sort algorithms can also be written recursively, although this could have a negative impact on performance. Recursion can simplify coding of the algorithm, but can increase processing requirements.

Insertion sort methodology is more commonly implemented in a non-recursive manner.

Insertion Sort Algorithm Characteristics/Caveats

One factor of sorting algorithms is the attribute of being termed stable or unstable. This refers to the occurrence of equal values in array elements, and whether the sequence of those elements will be retained in the same order as originally encountered in the output set. Insertion sort algorithms are stable by their very nature.

Divide and conquer – algorithms that implement a divide and conquer methodology process data elements utilizing a somewhat more complex approach:

  • Divide – separate the data to be processed into multiple smaller sets of data

  • Conquer – recursively process the subsets of data to execute the algorithm separately

  • Combine – generate the resulting output set through combining the subsets

As divide and conquer algorithms require multiple steps, they are recursive in their processing methodology. Where large sets of data are involved, this type of algorithm can provide an advantage in run times (time complexity).

Insertion sort is not a divide and conquer algorithm, processing elements in a single pass.

Why Would You Use (or Not Use) an Insertion Sort Algorithm?

With the many variations of sort algorithms, why would you decide you use the insertion sort algorithm for any particular problem?

When to Use Insertion Sort

Utilizing an insertion sort algorithm can be an effective solution under certain conditions:

  • Input sets are relatively limited in size

  • Input sets are partially sorted, which increases the efficiency of the algorithm, through the requirement for fewer iterations

  • Space is a consideration – insertion sort requires only a single new memory space, reducing space complexity

  • Stability is an important factor – insertion sort is a stable algorithm, making it an effective choice when that is important for your output set

  • For managing online content, where your application receives one element at a time, insertion sort is a great choice due to its performance in handling such small volumes

Benefits of the insertion sort algorithm include its low overhead and simplicity. When a pre-sorted or partially-sorted input set is expected or known, performance of the insertion sort algorithm can be significantly better than many alternatives, including divide and conquer algorithms such as merge sort, heap sort, even QuickSort.

When Not to Use an Insertion Sort Algorithm


In many instances, the size of the input set to your sort algorithm is unpredictable, or you may even be aware that the volume of data will be large. In such use cases, insertion sort will not be a good choice to solve your sort requirements.

With average and worst-case scenarios (refer to Big O Notation later in this article), alternatives such as merge sort and heap sort will provide better performance.

Insertion sort is not your best choice when concerned with:

  • Large data volumes – insertion sort performance suffers with large input sets

  • Space is not an issue – divide and conquer algorithms will have a higher space complexity, but if that is not an issue, there are better options than insertion sort

  • Stability is not required – for many implementations, stability in the output is not a requirement, allowing the use of non-stable algorithmsthat offer better performance

  • If the input array is unsorted or reverse-sorted, insertion sort will not result in good performance

  • Optimizing processor use – larger data volumes will result in more CPU cycles when implementing an insertion sort algorithm over a divide and conquer solution

Making the Best Choice for Your Sorting Algorithms

Mathematicians and computer scientists have developed a set of guidelines termed Big O Notation, which provides guidelines for the efficiency of different sorting algorithms based on critical factors:

  • Efficiency in run times (time complexity)

  • Space requirements (space complexity)

Binary insertion sort

These algorithm variations have even been compiled into a “cheat sheet” that provides a quick reference to these factors, including performance in best, average, and worst case scenarios.For an insertion sort algorithm, worst case conditions occur when the input set is in reverse order, with best case being where the input set is already sorted.

Additional information, including tutorials on Big O Notation can be found on YouTube and on multiple websites.

It pays to do a little research before making your final choice of sort algorithm solutions. There are divide and conquer algorithms that determine the size of the input set first, and automatically switch to another alternative such as selection sort or insertion sort to process small arrays more efficiently.

Sorting algorithms that are right for your application will depend on the volume of data to be sorted, the condition of the data itself (duplicate values, pre-sorting, etc.), space requirements, and even the programming language in use (not all sorting techniques are supported by every language).

What Is A Merge Sort Algorithm And How It Is Used

A primary function of every computer system is to organize data for effective use in analysis, reporting, or presentation purposes. You certainly cannot expect to logically make sense of data that is presented in a random sequence, and make judgements or decisions based on the information.

To solve that problem, computer programmers and mathematicians have created a variety of sorting algorithms that transform non-sequenced data into elements that are sorted into sets of records that provide information in a meaningful manner for business or scientific use.

In today’s sophisticated computer systems that commonly utilize extremely high data volumes for intelligent analysis – referred to as “big data”, efficient sorting techniques are more critical than ever before.

A merge sort algorithm is one of the more commonly-used and powerful solutions for sorting data structures and data content quickly and efficiently.

Sorting Efficiently with a Merge Sort Algorithm

colorful drinks

There are many options available to computer application developers for sorting sets of data to generate organized output.

Selection of the algorithm to be utilized is to some extent dependent on the language being utilized (ex: C++ “sort()” function can select a different algorithm depending on the array presented for sorting. Its native algorithm is the Introsort function, a blend of heapsort, insertion sort, and quicksort methodology. Depending on the depth of recursion of the array, quicksort or heap sort may be performed. For extremely small arrays, the high performance of insertion sort algorithm will be selected.

When executing a sort function in Python, a combination of insertion sort and merge sort will be used, known as Timsort.

A merge sort algorithm will sort an array into the desired sequence quickly and efficiently, utilizing a divide and conquer methodology. As with many sort algorithms, with a merge sort algorithm the array test will detect the size of the array, and if the size is 0 or 1, consider the data sorted with no processing required.

What is a Divide and Conquer Algorithm?

But what is a merge sort algorithm, and what makes it different from other sorting techniques?

Merge sort is just one of several divide and conquer algorithms that accomplishes its functions in a multi-step process:

  • Divide the array intotwo equal smaller arrays for processing efficiently

This is a simple process of dividing the array size by 2 to determine the midpoint, and creating the two subsets

  • Solve the sequencing of each subarray individually – conquer the problem

This is also a straight-forward process involving recursive calls for each subarray to execute the sort process

  • Combine the sorted subarrays back into the complete original array, now in sequence – this is the merge function that gives the algorithm its name, and requires heavy comparison processing to create the final result set

This divide, conquer, combine process can be performed much more efficiently than other methods such as insertion sort algorithm, which can take a considerable amount of processing time when arrays exceed more than minimal depth.

Array depth is one of the most important elements in determining the sort algorithm that will perform most efficiently when implemented in your solution. Other considerations include space requirements, memory available, and overall performance.

Since a merge sort algorithm will generate additional arrays in memory while processing the input set (divide), space is an important consideration in using merge sort for large arrays. Your trade-off is in performance – time complexity is a major advantage in using a divide and conquer algorithm like merge sort. Since these algorithms create subarrays as part of their basic functions, they are recursive in execution.

Factors for consideration in sort algorithm selection are available on websites for your comparison and decision-making purposes.

Merge Sort Variations


There are multiple variations or implementations of merge sort algorithms, providing options and flexibility in your choice of sorting methodology:

3-way merge sort

In a 3-way merge sort, instead of sub-setting the input array into two subarrays, three equally-sized separate arrays are created, sorted, then merged. Although the time complexity would seem to be reduced due to the smaller arrays being sorted, the increased number of comparisons required in the merge operation will raise the time complexity during that phase.

Bottom-up Implementation

Bottom-up processing utilizes indices and two buffers to iteratively merge sub-lists between the buffers to sort elements into the sorted array. The result is a non-recursive merge sort, contrary to the typical recursive nature of other merge sort variations.

Polyphase Merge Sort

This variation of a bottom-up merge sort is geared for external data sources where multiple files are being sorted, often including data stored on a hard drive or even a tape device. This includes data sets that will be uneven or unknown in their array sizes, being external input to the algorithm. Due to that criteria, polyphase merge sorts are not stable in nature.

Natural Merge

Similar to the processing of a bottom-up merge, natural merge further examines any existing sorted elements (naturally-occurring sequenced data), and takes advantage to move these elements in a single pass to the result set. In a perfect case, the array will be found to be in sequence, resulting in a single pass to create the solution. Even in a partially-sequenced array, the impact can be improved performance though fewer passes to solve the problem.

Oscillating Merge

Do you ever deal with data from tape drives, especially those that can read backwards? Oscillating merge sort algorithm was designed with that technology in mind. This variation of merge sort intersperses the input data with the merge process, rather than reading the entire set of data before merging can begin.

Pros and Cons of a Merge Sort Algorithm

Not all sort algorithms are created equal – in fact, there are significant differences that will impact your decision on the best sort algorithm for solving your problem.


  • Merge sort utilizes additional space over the original array to create its subsets of data to solve the problem and create sorted output.

  • A merge sort algorithm will process large arrays with reduced time complexity over many other options, notably an insertion sort algorithm.

  • Where stability is an important factor for your application, merge sort is a viable choice, since it is a stable algorithm. Stability means that where values being sorted are equal in multiple elements, the resulting output will retain the original sequence of those elements.


  • Space restrictions –since additional space is required to create the subsets of data for divide and conquer algorithms, you need to have space available to utilize this sort method.

  • Small arrays – where very small arrays will be sorted, other non-recursive, single-pass algorithms such as insertion sort may be more efficient.

Since the merge step makes an additional copy of the array to accomplish its work, extra space is required. While some algorithms such as insertion sort and selection sort do their work “in place” and are therefore preferred where space is at a premium, merge sort is not an in-place algorithm.

There is an exception to the requirement for a merge sort algorithm’s need for additional space to process – use of a linked list. Due to the nature of how linked lists reside in memory, no additional space is required for a merge sort with linked lists.

Factors for Choosing the Best Sort Algorithm


Now that you’re comfortable with the concept of what a merge sort algorithm is, your dilemma may be what sort algorithm to utilize in your application. Big O Notation is a representation of how algorithms will perform, based on primary factors:

  • Time Complexity

  • Space Complexity

  • Array Size

Considering those factors plus any special requirements you have in your problem (such as stability issues mentioned earlier), you can make the decision on the algorithm that will perform best for your data and meet your application performance goals.

Where space is not a major consideration, there are additional sort algorithms to be explored for potentially improving your application performance and efficiency:

  • QuickSort

  • Heap Sort

  • Bucket Sort

  • Bubble Sort

There are additional sort algorithms available for your applications, each with their own pros and cons. Some are more useful when used with certain programming languages or may be more useful for website applications (such as insertion sort algorithms).

Utilizing sort selection tools and Big O Notation guidelines can help you determine the best sort algorithm for your implementation.

Keywords:What is a merge sort algorithm, merge sort

Java Interview Questions

The Top 21 Most Common Java Interview Questions

It pays to know of the one most popular programming languages.

In 2016, Oracle noted Java was used by approximately 9 million developers and running on 7 billion devices worldwide. That’s an exponential growth curve, considering it’s only been public for less than 25 years.

Java was born in Santa Clara, California as part of the Silicon Valley boom in the early 1990s. Java was developed at Sun Microsystems to boost the abilities and effectiveness of C++ language.

It was released to the public in 1995 and quickly gained popularity. Java was designed to run independent of platform. Any device that has Java Runtime Environment (JRE), a lightweight application, can run a Java program. This provided developers a “write once, run anywhere” programming language. It significantly reduced the coding and resources necessary to write a program for multiple platforms.

Java was eventually acquired by Oracle as part of its larger purchase of Sun in January 2010.

Of all the programming languages available, how did Java surpass them and become such a hot commodity in today’s job market?

Why Java is One of the Top Programming Languages

Java is undeniably popular. It consistently leads the TIOBE index – a measure of the popularity of programming languages created by the TIOBE Company in the Netherlands – with the most recent rating of 17.8%. That’s up 5.4% from last year.

Below are just a few of the reasons why Java has become so popular:

  • The Five Principles: Sun Microsystems wanted to build on the C++ language and create something that more people could use. They explained this goal as Five Principles which guided the initial design and subsequent iterations of the language.
  • Open Source: Anyone can create Java applications at no cost. A massive community of users has grown around Java, providing additional resources and expertise for developers. Message boards and forums provide free publicity and ongoing training for users. With a growing library of functions and classes, Java is an easy choice when looking to deliver results quickly.
  • Concurrent: Programmers can process data in parallel, meaning multiple programs can run at the same time. This increases the efficiency and power of programs written in Java.
  • Wide Range of Uses: Java is used in banking and financial services, IT, and stock market trades. It provides a solid foundation for websites. Java is critical for applications in a wide range of industries.
  • Big-Name Users: Companies and programs that use Java include Minecraft, Adobe Creative, Google, and more.

Thanks to the high demand for this skill set, average salary range has been reported at $93,570 for a Java programmer. It’s no wonder Java developers and programmers are in such demand.

Knowing Java is only part of what you need to earn a position with one of the top companies in the world. Let’s look closely at the interview process and the questions you can expect.

Interview Questions

The interview is designed to give the business a better understanding of who you will be as an employee and how you will work as part of a team. The questions will also cover specific technical skills you’ll need.

Problem-Solving Questions

Managers want problem solvers in every layer of employment – from entry level to top management. The hiring manager will test your personal skills by asking about missed deadlines, office conflicts, loss of data, and overlapping deadlines. They are not only looking to see that you know how to fix a problem but want to know how you can deliver solutions when problems occur. Below are a few of the questions you should prepare to answer:

  • What is a challenge you’ve faced in the past and how did you handle it?
  • Have you ever had a project that was behind schedule? How did you manage the work and meet the deadline?
  • Tell me about a time where you faced a problem you couldn’t solve. How did you handle it?
  • Describe a creative solution you used to handle a work-related problem?
  • What kind of troubleshooting process do you use in your work?

Leadership-Based Questions

Do you wait for a solution or do you lead by proactively finding the answer? Everyone has their comfort zone with leadership. Hiring managers want to know where you will fit within the company. They may ask questions about your proudest accomplishment, what do you want to gain from this job, or if would you speak up if you knew something in the process was wrong.

  • In your opinion, what makes a great leader?
  • What experience do you have that will help you in this position?
  • What work-related responsibilities have you had in the past?
  • If you knew a manager was wrong, how would you handle it?
  • What is your greatest strength and greatest weakness?

Java Interview Questions

Java is considered one of the easier programming languages, especially when compared to languages like C, C++, Fortran, and Pascal. Even so, there are core skills and expertise every developer and programmer working in Java should have mastered.

The technical questions in the interview will be designed to not only determine your comfort and competence in Java programming, but also check that you have the core skills for the position. Before the interview, make sure to review the job listing to identify what those skills are. Take time to brush up on those skills and have answers ready for any specific technical questions the interviewer might ask.

Let’s look at a few other common Java interview questions:

  • Can you explain what a “platform independent programming language” means, and why Java fits this description?
  • Can you explain the difference between StringBuffer and String?
  • Tell me what you know about the finalize() method?
  • Can you explain the difference in Set and List interface?
  • Why doesn’t Java support multiple inheritances?
  • Tell me what you know about Java Exception Handling? Is there a difference between “throw” and “throws”?
  • What is the Final keyword in Java? How is a super keyword used?
  • Can you explain the abstract class in Java? How is it different from an abstract class in C++?
  • How does static variable work in Java?
  • How does Java store objects in memory?
  • What are the differences between HashTable and HashMap in Java?

Keep in mind, these are common Java interview questions. Many jobs will require specialized technical knowledge and Java programming that isn’t covered by these questions. Understand the position you are interviewing for and the expectations for the job.

Next, we’ll go over a few other things you can do to ace your interview.

Appearances Mean Everything

Beyond knowing the answers to the top interview questions, landing the job is all about first impressions and professionalism. Employers are looking for Java programmers that fit within the corporate culture and take pride in themselves. Confidence in your abilities translates to confidence in your appearance and mannerisms.

Below are some guidelines to acing the first impression:

Prepare for the Interview

You are an expert in your field, Java programming, but companies also expect you to know about them and how they are using Java. Go beyond the simple Google search and see what the company says about itself. Look at what others are saying about the company and who are their competitors. Review their business pain points and prepare responses on how you can solve them.

Dress Appropriately

Sometimes a recruiter or the hiring manager will provide guidelines on what to wear. If they don’t, do your research and learn what is expected in the corporate culture. Not every company will expect a suit, but some won’t give you a second glance if you wear jeans. In general, interviews tend to be more formal than your daily wear once you land the job.

  • Here are recommendations for women, including what to wear and suggestions on where to buy layers, blazers, dresses, and pants. You don’t have to buy the exact item in the article; use it as a guideline and tailor it to your style and budget.
  • Likewise, there are also suggestions for men for ties, shirts, and trousers. Again, make the style your own, but make sure it fits the expectations.

Print your Resume

Some companies and human resource departments still prefer paper. Print and bring a copy of your resume. It’s better to have it and not need it, then to not be prepared for someone to review your resume.


Store your printed resume, laptop and any samples in a portfolio or briefcase, so they are crisp when you arrive. You will lose credibility if your work looks sloppy.

Follow Up

Gather business cards or contact information during the interview. Email a thank-you note within 24 hours (the sooner the better) of the interview. Express not only your thanks, but also your excitement and recap what you can bring to the company.

A Final Word on Java Interview Questions 

Learning Java is only the first step in a career. Even as the demand for quality employees and the sheer number of companies using Java continues to rise, competition for jobs is still fierce.

Preparing for Java interview questions and doing your research before you meet with a recruiter is critical to landing the job you want. You may be the best Java programmer for a position, but if you can’t ace the interview and show what an asset you will be for the company, you may never get a chance to show what you can do.

Meta Information

Focus Keyword(s): Java Interview Questions

Meta Keywords: Java programming, Java programmer

Meta Title: The Top 21 Most Common Java Interview Questions

Meta Description: Competition is fierce for Java programmer jobs. Stay ahead of the competition with these top Java interview questions.

WordPress Tags: Java, Java interview questions, Java programming

How System.out.println() works

In Java, how does System.out.println() work?

This question is an excellent example of how just some very basic knowledge of Java can lead you to the correct answer. Most interviewers would not expect you to know the answer to do this right away – but would like to see how you think and arrive at an answer.

Marcus Aurelius (a Roman emperor) once said: "Of each particular thing ask: what is it in itself? What is its nature?". This problem is an excellent example of how that sort of thinking can help one arrive at an answer with only some basic Java knowledge.

With that in mind, let’s break this down, starting with the dot operator. In Java, the dot operator can only be used to call methods and variables so we know that ‘out’ must be either a method or a variable. Now, how do we categorize ‘out’? Well, ‘out’ could not possibly be a method because of the fact that there are no parentheses – the ‘( )’ – after ‘out’, which means that out is clearly not a method that is being invoked. And, ‘out’ does not accept any arguments because only methods accept arguments – you will never see something like “System.out(2,3).println”. This means ‘out’ must be a variable.

What is “out” in System.out.println()?

We now know that ‘out’ is a variable, so we must now ask ourselves what kind of variable is it? There are two possibilities – it could be a static or an instance variable. Because ‘out’ is being called with the ‘System’ class name itself, and not an instance of a class (an object), then we know that ‘out’ must be a static variable, since only static variables can be called with just the class name itself. So now we know that ‘out’ is a static member variable belonging to the System class.

Is “out” in System.out.println() an instance variable?

Noticing the fact that ‘println()’ is clearly a method, we can further classify the ‘out’ in System.out.println(). We have already reasoned that ‘out’ is a static variable belonging to the class System. But now we can see that ‘out’ must be an instance of a class, because it is invoking the method ‘println()’.

The thought process that one should use to arrive at an answer is purposely illustrated above. Without knowing the exact answer beforehand, you can arrive at an approximate one by applying some basic knowledge of Java. Most interviewers wouldn’t expect you to know how System.out.println() works off the top of your head, but would rather see you use your basic Java knowledge to arrive at an answer that’s close to exact.

When and where is the “out” instantiated in System.out.println?

When the JVM is initialized, the method initializeSystemClass() is called that does exactly what it’s name says – it initializes the System class and sets the out variable. The initializeSystemClass() method actually calls another method to set the out variable – this method is called setOut().

The final answer to how system.out.println() works

The more exact answer to the original question is this: inside the System class is the declaration of ‘out’ that looks like: ‘public static final PrintStream out’, and inside the Prinstream class is a declaration of ‘println()’ that has a method signature that looks like: ‘public void println()’.

Here is what the different pieces of System.out.println() actually look like:

//the System class belongs to java.lang package
class System {
  public static final PrintStream out;

//the Prinstream class belongs to package
class PrintStream{
public void println();