Ramya Shankar | 28 Jul, 2023

Best Way to Learn Java

 

Learning Java is easy and fun, no matter what background you have. With this comprehensive guide, you will have all the resources that will help you start your Java journey and master the essential concepts.

Java is –

  • Object-oriented programming language
  • Platform independent
  • capable of automatic garbage collection
  • multi-threaded and concurrent

Java code runs on the Java Virtual Machine, which translates Java code into a language that the OS understands. All these features and more make Java one of the top programming languages of 2024.

Best way to learn Java

Well, there is no shortcut to learning anything, and the same is valid for Java. If you want to master the language (believe me, it is worth it), you have to set it up on your system and get practicing. Download and install JDK (Java Development Kit) and JRE (Java Runtime Environment) and also any IDE that you are comfortable with. Easy Eclipse works just fine for writing programs and building stand-alone applications.

Okay, before we get into the core concepts, here are a few things you should remember always –

  • Never start with the mindset of “How hard is it to learn Java.” Still think it must be secure, that is why so many people are doing it.
  • If you are a non-programmer, have some extra patience – you will undoubtedly get there.
  • Think about a real-world scenario and list down how you would implement it. For example, if you want to buy groceries from Big Basket, what is the checkout process? Same way, how would you do it? If you think of a design/flow, you will surely find a way to implement it and get results. It is possible to build full-fledged web applications using Java and J2EE.
  • There are plenty of resources available to learn Java. If you are stuck, the Java community is significant and active and will help you.
  • The IDE takes care of all your syntax errors. So, focus on the core functionality but know the syntax well too.
  • Read this article and follow the approach of starting with a simple program and then adding functionality over it to make it more complicated and interactive.

Now that we have a positive mindset and zing to learn let us look at all the concepts we need to learn to write efficient code in Java –

Variables and data types

On a day to day basis, we come across different types of data. For example, the telephone number of your car driver is an integer, but his name is a string (array of characters). Same way, the price of petrol that he puts in your vehicle is a floating-point (decimal). Java handles a lot of data types –

String driverName;
int telephoneNo;
float petrolPrice;
boolean isRegular;

One of the best practices in Java is to follow the right naming conventions. Variables (driverName, telephone. etc…) like the above and methods should start with a small case, and the following word begins with a capital letter – driverName. Same way, since a boolean data type returns true or false, it is a good practice to name the variables starting with is, are, has, etc.…

The advantage of storing data in variables is that we can use the variable anywhere in the code. The limit of using a variable is defined by its scope, which can be local, static, or global.

The data types char, int, float, boolean and double are called primitive types, and Java has corresponding objects for each of these. For example, int has Integer; boolean has Boolean, and so on. A string is an object.

So, what do we do with the data? We perform some operations on it!

Operations

For example, based on whether the driver is regular or not, we can give him some incentives or, based on the amount of petrol he fills, we can know how many kilometers he drives.

if (isRegular)
{ 
salary += 200;
}

The result of expression inside of the condition can be a boolean only. If we compare two strings, for example, if(driverName == “Chand”), we use the comparison operator ‘==’ which is different from the assignment operator ‘=.’ Same way, there are <, <=, >, >= and so on.

Conditions

Just like we saw above, the ‘if’ is a condition that tests for something to be accurate and returns results accordingly. It is usually combined with else if and else statements that can handle multiple situations.

if(marks < 23)
grade = ‘F’;
else if(marks > 23 && marks < 60)
grade = ‘D’;
else 
grade = ‘B’;

Note that && means both the expressions have to be true for the if to be successful.

Functions

A lot of code that we write can be segregated into blocks of code so that many parts of the application can reuse it. Such blocks of the system are called as functions. For example, applying the grade can be a function based on the marks. The system, when divided into smaller functions, looks neat and is easy to understand. It is modular and reusable.

Function names in Java start with the small case, with the following words having the first letter as capital. For example, get grades(float marks) that return a char, isRegular(String driverName) that returns a boolean, and so on.

Okay, now comes the real power of Java.

Suggested Course

Java Programming for Complete Beginners

Object-oriented programming

If you want to get into details of OOPS concepts, go through with the above-given video, which I have embedded in this article previously. Still, for this article, all you need to know is that in OOPS, everything is considered as an object. A pencil is an object, a car, plant, animal, and even a Driver is an object.

Continuing our driver example, let us say, the following attributes identify driverdriverName, joiningDate, isRegular, dateOfBirth, and avgCustomerRating.

Let us say a service provider like Uber, will have many such drivers. Each driver has all these attributes that will be differentiated with their unique values. That means, we can create a class ‘Driver’ with these attributes as the members of the course. Whenever we need to get or set a particular driver’s details, we will create an ‘object’ of the Driver class using the new operator.

Driver driver = new Driver();

When we create the class, we also create the ‘getter and setter’ methods for the members through which we can get individual values of the members. If we have to set the whole object, we can do using a constructor that we should define in the class.

public Driver(String driverName, String joiningDate, boolean isRegular, String dateOfBirth, float avgCustomerRating){
this.driverName = driverName;
this.joiningDate = joiningDate;
this.isRegular = isRegular;
this.dateOfBirth = dateOfBirth;
this.avgCustomerRating = avgCustomerRating;
}

Now, when we want to create an object, we can do so by just calling the new operator and this constructor as –

Driver driver1 = new Driver(“John”, “21/12/2018”, true, “12-01-1983”, 4.5);

If you are practicing the code simultaneously, after fixing compilation errors, if any, build and run the program and expand your project. You will see the .class file corresponding to every .java file.

Data structures and looping

There are many data structures in Java-like arrays, lists, maps, trees, and so on. All these come under the Collection framework except Array, which is part of the java.util package. Learning about Collection will give you immense satisfaction about storing and retrieving data – which means half the battle won for you. Let us do a quick example with arrays. In my article, What is Java, I have used ArrayList to do similar kind of operations, do check that too.

Driver[] drivers = new Driver[5];

//Set driver details for each driver or fetch it from database or user input

Let us say there are five drivers, and we want to set the salary based on some conditions for each of the drivers. We use a ‘for’ loop for this.

for(int i=0; i<5; i++)
{
if(driver[i].isRegular && driver[i].salary < 4000)
driver[i].salary += 200;
}

Note that we get each driver’s detail and then do some checks for each of the drivers. After that, we set a value. Here we have hardcoded the cost of Driver to 5, but in a real application, we will fetch that from a database or the console.

How?

User inputs

Consider fetching the driver details from the user. For each driver, let us bring the further information using the for loop we just learned. First, let’s create the array. This time we will not fix the length. Let’s ask the user for it.

If you haven’t created our favorite Driver class, do that now using your IDE. These things are best learned when practiced. To create this class, let us first create a project on the IDE. Create a project of any name, for example, SampleProject. Then create a package named src (which means source code). Inside the package, create the class Driver with the members. With the click of a few buttons, generate getters and setters on the IDE.

User Inputs

Now write or create the constructor as we discussed earlier.

Now, let us create our Test Class, which will have the public static void primary (String args[]) method.

To get input from the user, the best way is to use the ‘Scanner’ method.

Scanner scanInput = new Scanner(System.in);

There are other ways to do the same thing.

After this, we can get the inputs one by one using the next() method of the scanner. The first thing we get is the number of drivers for which information needs to be stored. Then, we create an array of the same length, loop through it, instantiate each object inside the loop, and set the values using constructor or setter methods.

Connecting to the database

For our java code to connect to the database, we need a JDBC driver (which is different from our car Driver). Different databases have different drivers; for example, for MySQL, the driver will be com.mysql.jdbc.Driver. Next, we need to connect to the URL (location) where the database is located. For accessing the database, we need a username and password too. After getting the connection, we can execute queries via code to get or set the necessary details.

For any simple or complex web application, you must know JDBC (Java Database Connectivity). Take up this nice tutorial explaining about JDBC connectivity. You will enjoy learning it all by yourself.

Handling files

File handling in Java is done using two classes FileWriter and FileReader. Java documentation describes all the methods and constructors that are provided with these classes, and they are pretty much straightforward. Earlier, FileInputStream and FileOutputStream were used, but the former two are preferable because they write stream of characters while the latter two are byte stream classes. Remember that with file handling, it is essential to catch exceptions like FileNotFoundException.

Exception handling

Java permits a lot of flexibility. But as a developer, we need to know what are the scenarios where our code can give incorrect results. One such case is the user not entering correct values. For example, if you have set driverName as a String, and the user introduces some numbers or random characters, we should be able to handle such cases and inform the user. These are generally done on the client-side using JavaScript, but JavaScript can be disabled. As developers, we need this validation done from our side too. Some standard exceptions are-: NullPointerException: when we are trying to do some operation on a null object.

NumberFormatException: when we try to convert a string into a number, and it is not valid.

ArrayIndexOutOfBoundsException: when we try to access an element more than the size of the list

There are many such checked and unchecked exceptions in Java that you need to be aware of for robust code.

Garbage collection

While we always loathe when we think of garbage, Java GC is something that you will love to know about it. As a programmer, you don’t have to worry about how the garbage collector thread works. It just does its job quietly. However, if you are interested, it makes for a good read and is asked about in some core java interviews too. Read about Java garbage collection here.

Multithreading

To handle concurrency, Java supports multithreading and has efficient built-in methods. While many people find Threads to be a dreadful topic, it is not so in the case of Java. Threads do behave differently at times, but we all have mood swings at some point, don’t we? If handled delicately, threads are always in their best mood just like us.

For example, you are trying to book a cab. While you check out multiple options, a couple of more users try to seek the same cab from the same starting point.

Who gets the booking?

The first person to confirm and get the handle! If you make your booking fast, the ride is locked for you — the other riders than don’t see this particular cab. However, if you cancel the cab for some reason, the lock is released, and the cab is available for others. The same concept is with the threads. If one thread is changing a part of the code which others want to access, the others have to wait for their turn so that all the threads don’t work on the same data at the same time and corrupt it. Multithreading has made our life easy – think of online ticketing, banking transactions, and all secure transactions – if everyone had access to the same data at the same time, the world would be full of chaos!

I learned threads through this excellent brain friendly guide by Kathy Sierra. I don’t know if it's their familiar way of explaining or the head first approach, the concept was planted so permanently in my mind that I could write a whole 2-page program within minutes during an interview. The interviewer (who was eventually my manager) was stunned and talked about it even days after I joined the company!

Creating web applications

Okay, so now we have come to the real thing! The whole point of learning Java is to create robust web applications that are interactive and fast. If you already have the IDE setup, all you need to do is install J2EE components into your IDE. Read this blog to understand how J2EE helps build scalable and robust web applications.

To build web applications, you will need to know the basics of servlets and JSP (Java Server Pages), which are easy to learn. There are many other frameworks like Spring, Struts, which give powerful web applications when combined with Java. Here is an excellent tutorial that covers all of them in a single course and with a practical (hands-on) approach.

Creating web services

Java web services are used to interact with the different layers of an MVC architecture. There are two ways for Java Web Service (JWS) application to communicate – SOAP and RESTful services. The communication is done through WSDL (Web Services Description Language). Read this extensive tutorial that covers all about SOAP and REST to get you started on Java web services.

Conclusion

In this blog, I have given you a lot of resources and links to various subtopics that you need to know to master Java. There are a lot of other OOPS concepts that Java uses – like boxing, unboxing, design patterns, generics, and so on that help you with better coding practices, but these are the concepts that will help you build a functional application. While you are at it, you should also make sure your understanding is correct by checking out if you can answer these Java Interview Questions! Here is also a nice paid tutorial that you can take up once you are done playing with the basics. Do check out our comprehensive list of Java books that will make learning Java, an enjoyable and thorough experience for you.

People are also reading:

 

By Ramya Shankar

A cheerful, full of life and vibrant person, I hold a lot of dreams that I want to fulfill on my own. My passion for writing started with small diary entries and travel blogs, after which I have moved on to writing well-researched technical content. I find it fascinating to blend thoughts and research and shape them into something beautiful through my writing.

View all post by the author

Subscribe to our Newsletter for Articles, News, & Jobs.

I accept the Terms and Conditions.

Disclosure: Hackr.io is supported by its audience. When you purchase through links on our site, we may earn an affiliate commission.

In this article

Learn More

Please login to leave comments