Tag Archive | "Java"

How to create an array in Java

How to use arrays in Java

An array in Java is a type of variable that can store multiple values. It stores these values based on a key that can be used to subsequently look up that information.

Arrays can be useful for developers to store, arrange, and retrieve large data sets. Whether you are keeping track of high scores in a computer game, or storing information about clients in a database, an array is often the best choice.

Also read: How to use arrays in Python

So, how do you create an array in Java? That all depends on the type of array you want to use!

How to create an array in Java

The word “array” is defined as a data structure, consisting of a collection of elements. These elements must be identified by at least one “index” or “key.”

There are multiple data objects in Java that we could describe as arrays, therefore. We refer to the first as the “Java array.” Though making matters a little more confusing, this is actually most similar to what we would call a “list” in many other programming languages!

This is the easiest way to think about a Java array: as a list of sequential values. Here, a key is automatically assigned to each value in the sequence based on its relative position. The first index is always “0” and from there, the number will increase incrementally with each new item.

Unlike a list in say Python, however, Java arrays are of a fixed size. There is no way to remove elements or to add to the array at run time. This restriction is great for optimized code but of course does have some limitations.

To create this type of array in Java, simply create a new variable of your chosen data type with square brackets to indicate that it is indeed an array. We then enter each value inside curly brackets, separated by commas. Values are subsequently accessed by using the index based on the order of this list.

String listOfFruit[] = {"apple", "orange", "lemon", "pear", "grape"}; System.out.println(listOfFruit[2]);

While it’s not possible to change the size of a Java array, we can change specific values:

listOfFruit[3] = “melon”;


If you need to use arrays in Java that can be resized, then you might opt for the ArrayList. An ArrayList is not as fast, but it will give you more flexibility at runtime.

To build an array list, you need to initialize it using our chosen data type, and then we can add each element individually using the add method. We also need to import ArrayList from the Java.util package.

import java.util.ArrayList;  class Main {    public static void main(String[] args) {      ArrayList<String> arrayListOfFruit = new ArrayList<String>();     arrayListOfFruit.add("Apple");     arrayListOfFruit.add("Orange");     arrayListOfFruit.add("Mango");     arrayListOfFruit.add("Banana");     System.out.println(arrayListOfFruit);    }  }

Now, at any point in our code, we will be able to add and remove elements. But keep in mind that doing so will alter the positions of all the other values and their respective keys. Thus, were I to do this:

System.out.println(arrayListOfFruit.get(3)); arrayListOfFruit.add(2, "Lemon"); System.out.println(arrayListOfFruit.get(3));

I would get a different output each time I printed. Note that we use “get” in order to return values at specific indexes, and that I can add values at different positions by passing my index as the first argument.

How to create an array in Java using maps

Another type of array in Java is the map. A map is an associative array that uses key/value pairs that do not change.

This is a perfect way to store phone numbers, for example. Here, you might use the numbers as the values and the names of the contacts as the index. So “197701289321” could be given the key “Jeff.” This makes it much easier for us to quickly find the data we need, even as we add and remove data from our list!

We do this like so:

import java.util.HashMap; import java.util.Map;      Map<String, String> phoneBook = new HashMap<String, String>();     phoneBook.put("Adam", "229901239");     phoneBook.put("Fred", "981231999");     phoneBook.put("Dave", "123879122");     System.out.println("Adam's Number: " + phoneBook.get("Adam"));

As you can see then, a Java Array is always an array, but an array is not always a Java Array!

How to use the multidimensional array in Java

Head not spinning enough yet? Then take a look at the multidimensional array in Java!

This is a type of Java Array that has two “columns.”

Imagine that your typical Java array is an Excel spreadsheet. Were that the case, you’d have created a table with just a single column. We might consider it a “one dimensional” database, in that the data only changes from top to bottom. We have as many rows as we like (1st dimension) but only one column (the hypothetical 2nd dimension).

To add more columns, we simply add a second set of square brackets. We then populate the rows and columns. The resulting data structure can be thought of as an “array of arrays,” wherein each element is an entire array itself!

In this example, we are using integers (whole numbers):

int[][] twoDimensions = {       {1, 2, 3, 4},       {5, 6, 7, 8},       {9, 10, 11, 12}, };

But we can actually take this idea even further by creating a three dimensional array! This would be an array of 2D arrays. You would build it like this:

int[][][] threeDimensions = {         {           {1, 2, 3},           {4, 5, 6}         },         {           {-1, -2, -3},           {-4, -5. -61},         } };

Although this idea is tricky to conceptualize, try to imagine a database that has three axes, with cells that move in each direction.

So that is how you create an array in Java! While many people reading this will never need to concern themselves with three-dimensional arrays, it just goes to show how powerful and adaptable Java really is.

In fact, the list of things you can accomplish with Java is limitless. As is the Array List. Why not continue your education with one of the best resources to learn Java?

Android Authority

Posted in Android NewsComments (0)

How to call a method in Java

How to call a method in Java

In this post, we will learn how to call a method in Java. This is a useful “chunk” of code that you can call from anywhere else in your program, thus preventing you from needing to write out the same lines of code over and over.

By designing code this way, developers can create far more modular and portable programs and save significant time typing out code.

How to call a method in Java – the basics

To call a method in Java, you type the method’s name, followed by brackets.

For example, the following will call a method called “helloMethod()”:


In order for this to work though, we first need to create our helloMethod() method. We can see what helloMethod might look like, here:

public static void helloMethod() {      System.out.println("Hello world!");  }

This code simply prints “Hello world!” to the screen. Therefore, any time we write helloMethod(); in our code, it will show that message to the screen.

If you ever want to change the message being displayed, you will only have to change it once – rather than every single time you used it in the code.

How to create methods in Java

Let’s rewind a moment and take a closer look at the method we created. Why does it look the way it does?

To build a method, we use a number of statements to define that method. In the previous example:

  • Public – Means that the method is accessible to other classes outside of this one
  • Static – Means that the method belongs to the class and not the instance of the class
  • Void – Means that the method does not return a value

If none of that makes any sense to you, don’t worry! Most new developers will be able to use “public static void” for the majority of their methods and won’t have to worry. That said, we’ll address two of these phrases in the coming sections.

It is considered good practice to name Java methods using “camel case.” As we aren’t allowed spaces, camel case gets around this by capitalizing every word except the first one. Methods should generally be verbs (though I have bent that rule here!).

See also: An introduction to Java syntax for Android development

After we’ve named our method, we use brackets in order to add any arguments. An argument is a variable that we wish to pass from one method to another. Variables are values represented by words. Again, if that’s confusing, then just adding two closed brackets is fine.

You then open the code block using “{“. All the code that follows should be indented, and will be part of the method and will run when you call that method.

How to use arguments when calling a method in Java

As mentioned, we can place arguments inside of the brackets when defining our methods. This allows us to pass variables, and therefore values, between methods.

For example, a “String” is a type of variable that holds alphanumeric characters. We create a string by using the word “String” followed by the name.

Now, whenever we call that method, we need to add the value we want to use in the brackets.

helloClass.helloMethod("Hello there!");   public static void helloMethod(String helloMessage) {      System.out.println(helloMessage);    }

How to call a method from outside the class

A public method is a method that can be called from outside your class. To do this, you use the following syntax:


For example:

class Main {    public static void main(String[] args) {      helloClass.helloMethod();    }  }     class helloClass {    public static void helloMethod() {      System.out.println("Hello world!");    }  }

However, if we wanted to prevent this from working, we would simply replace the word “public” with the word “private”.

How to return values

Finally, we can return specific values from our methods. Let’s see how this might be used.

Let’s say we decide we want the method to provide our greeting but not display it onto the screen. Thus, we might make the method return a string. To do this, we change the word “void” for the type of variable we want to return, and we add “return value” at the end of the method.

This changes how we call a method in Java, because we can simply insert the name of the method in-line in our code, as though it were a variable:

class Main {    public static void main(String[] args) {      System.out.println(helloMethod());    }     public static String helloMethod() {        return "Hello there!";    }   }

If you’re still wondering what all that “static” stuff is about, then we recommend reading up on classes and objects over at the official Java Documentation from Oracle.

Alternatively, why not check out our list of the best places to learn Java. There you will learn about objects, classes, and much more besides!

Android Authority

Posted in Android NewsComments (0)

Best resources to learn Java – free and paid

Online Java courses

Want to make Android apps? Become a professional developer? Finding the best resources to learn Java online is one of the smartest ways to start.

Java is one of the most useful programming languages for any new developer to learn. Not only is it highly in-demand among employers and larger organizations, but it’s also one of just two official programming languages used for Android development.

Unfortunately, Java is also one of the harder programming languages to pick up. Especially if it’s your first one! Java does a few things that makes it one of the tricker langauges; encouraging an unintuitive object-oriented structure, featuring many rigid syntax requirements, and generally being home to numerous quirks.

Also read: The best free and paid Android app development courses

Don’t let that put you off! Learning Java is a masterclass in programming in itself, and many of those issues end up being useful organizational “features” down the line. The best resources to learn Java are designed to walk even the most green-horned learner through these challenges, and to help turn this mammoth task into a fun, easy project.

With that in mind, you’ll find the best resources to learn Java listed below!

The best resources to learn Java online for free

Android Authority

Android Authority is much more than a website about phones! This site covers every aspect of technology, which includes coding tutorials! Here, you’ll find a wide range of excellent Java tutorials to get you started, as well as specific lessons. Stay tuned too, because lots more is on the way. So you’re already on one of the best resources to learn Java… who knew!

Start here:


The clue is very much in the name! LearnJavaOnline.org is the selection of tutorials put together by Oracle: the company that owns Java. That means you can rest assured it will be accurate and up-to-date.

The sequences of courses is also rather comprehensive and well structured. These tutorials cover all of the basics and offer an excellent foundation. That said, the lessons are rather dry and text-heavy, so you may find this a somewhat dense introduction to the language. As the official option, this is definitely one of the best resources to learn Java online for free.

Best resources to learn Java


Never underestimate what you can learn from YouTube. The juggernaut video-upload site has endless tutorials focussing on Java, ranging from general overviews to highly specific tips and tricks. For those looking for a quick introduction, “Learn Java in 14 Minutes” from Alex Lee is an excellent option that touches on the basics.

For something a little more intensive “Java in 9 hours” from freeCodeCamp.org is ever-so-slightly more comprehensive. There’s something for everyone, though of course, the quality varies from one creator to the next!


TutorialsPoint is a site that’s filled with comprehensive tutorials, including an in-depth guide to Java. The course is a little bare-bones in terms of presentation, but once again walks you through all of the basics that you might need to know.


Codecademy has a paid “Pro” membership option, but offers a lot of hands-on tutorials completely free. That includes a four hour Java tutorial that should help you learn the basics.

The best-paid resources to learn Java

Introduction to Android app development

Introduction to Android app development from DGiT Academy is a course led by our very own Gary Sims. As you might have guessed, this course is geared primarily toward Android development. If that’s what you’re learning Java for, then this is a big advantage!

Java resources

But what makes this a great option for anyone, is that the bundle actually includes an in-depth introduction to Java as well. You’ll get two in-depth courses for the price of one, delivered in a way that’s easy and fun to follow along with. Whether you’re learning for fun, or to advance your career, this is definitely one of the best resources to learn Java online.

The Complete Java Bundle

The Complete Java Bundle is a comprehensive, 58-hour, 360-lesson Java course aimed at beginners. This course covers everything from the most basic fundamentals, all the way up to expert tips and techniques. While some of the individual classes are getting a little long-in-the-tooth, the concepts you’ll learn here are timeless and it’s still a fantastic starting point for new learners.

The course represents a truly “complete” education in Java and costs just $ 39 for Android Authority readers. That’s a saving of 96% on the usual $ 989 price tag, so don’t miss this opportunity!

The 2020 Java Bootcamp Bundle

The 2020 Java Bootcamp Bundle is a modern and up-to-date selection of Java courses, covering all the major topics you need to know. You’ll learn basic structure and syntax, Java objects, flow control, arrays, and more. By the end, you’ll have a firm grasp on the language and feel confident to begin working on your projects.

Once again, Android Authority readers can get a huge 96% discount if they act now, netting the entire bundle for just $ 35.99.

All-Level Java Programming Bundle

For just $ 19 (for Android Authority readers), this all-level Java programming bundle represents not only one of the best resources to learn Java, but also one of the most affordable. The bundle is designed to appeal to both beginners and advanced-level programmers and can, therefore, provide a complete education, all in one place.


Skillshare is a fantastic resource for learning anything. This is a platform where teachers can upload their lessons for users to watch. Those teachers create the videos themselves for the community, meaning that there is a mixed bag of quality. But what’s also true, is that there is some very good stuff here. And as you’ll only pay a fixed yearly fee for membership, it’s actually very good value!

Many of these classes even contain extra materials and community discussion to help you take your learning further.


While the web is packed with many of the best resources for learning Java, you shouldn’t forget about the old-fashioned option: books!

Learn Java

Learning Java from books is a brilliant strategy, as it gives you a reference you can refer to while coding and lets your eyes take a break from staring at screens! I learned the basics of Java from the now-outdated Beginning Programming With Java for Dummies but there are many modern equivalents to sink your teeth into. Depending on your preferred learning style, you might just find that a book is the best resource to learn Java for you!

My advice is not to attempt to read an entire book on Java and then expect to “know” Java. Instead, read the first few chapters to try and understand the basics, then start building something simple. You’ll find you need to refer back to the book as you forget syntax and statements, or as you try and do things you haven’t learned yet. This is the best way to learn, as it structures the process and gives you an end goal to strive toward.

You can learn more top tips for learning to code here.

Android Authority

Posted in Android NewsComments (0)

Android N doing away with Oracle’s Java APIs, OpenJDK to be the new standard

Android robot

Google has announced a move away from Oracle’s proprietary Java APIs. Beginning with the next version of their mobile operating system (Android N), the new standard will be OpenJDK, an open source alternative.

Suspicions of this move have been emerging for a while, as bits of code have shown up here and there. Today Google confirms all the speculations with the following statement, which was sent to the guys over at Venture Beat.

maxresdefaultSee also: Android Nankathai? What if Android fans got to name Android N?34

“As an open-source platform, Android is built upon the collaboration of the open-source community. In our upcoming release of Android, we plan to move Android’s Java language libraries to an OpenJDK-based approach, creating a common code base for developers to build apps and services. Google has long worked with and contributed to the OpenJDK community, and we look forward to making even more contributions to the OpenJDK project in the future.” – Google spokesperson

What is the difference? From a user standpoint, there will likely be little to no noticeable changes. It is developers who will likely have to adapt to the new standard in a more significant manner. So why the switch?

oracle logo mwc 2015

There is really no major reason we can think of… other than the legal issues Google has been having with Oracle. Google lost the case last year, causing quite the havoc and putting Google in a tight spot (which is very hard to get out of). Neither parties have commented on this, though, and we doubt they will.

Regardless, it is likely a good strategic move for the future of the company. We will have to wait until more details on Android N show up. Until then, let’s just stay put and keep it tuned to the Android Authority homepage.

Android Authority

Posted in Android NewsComments (0)

Related Sites

Powered by WP Robot