Oops… Yeah, that’s what is Java! Object-Oriented Programming Language that is based on the concept of Object-Oriented Programming Systems (OOPS).
Everything in Java is about objects. If you get the essence of
objects, Java is as simple and likable as eating your favorite food.
Okay, but why should you learn Java? After all, there are so many programming languages just like food…
Why Java?
Java is like the variety of your favorite food that is tasty (easy to code) and healthy (secure and robust)!
Besides the fact that Java is among the top programming languages of 2019 and perhaps will remain so for at least a decade, Java has nailed it in almost every domain you can think of!
As Java is secure and multi-threaded, it is perfect for Banking and transaction management services. E-commerce shops and billing software have their logic written in frameworks based on Core Java. Mobile OS like Android uses Java APIs. Stock market algorithms are based out of Java. And most recently, all the big data
– the humongous data is dealt with like a breeze with Java. In fact,
the MapReduce framework of Hadoop is written in Java. Java along with
other frameworks like Spring make for a robust combination to sort
implementation dependencies and write server-side applications in Finance and IT domains.
What is Java?
Java is a write-once, run-anywhere programming language
developed by Sun Microsystems. It is similar to C and C++ but a lot
easier. You can combine Java with a lot of technologies like Spring,
node js, Android, Hadoop, J2EE, etc… to build robust, scalable, portable
and distributed full-fledged applications. Java also promotes
continuous integration and testing using tools like Selenium.
History of Java
Java was originally developed by James Gosling with his
colleagues at Sun Microsystems during the early 1990s. Initially, it was
called as project ‘Oak’ which had implementation similar to C and C++.
The name Java was later selected after enough brainstorming and is based
on the name of an espresso bean. Java 1.0, the first version was
released in 1995 with the tagline of ‘write once, run anywhere’. Later,
Sun Microsystems was acquired by Oracle. From there, there has been no
looking back. The latest version of Java is Java 12 released in March
2019.
Features of Java
Java offers plenty of attractive features –
- Platform independent language
- Rich standard library making it easy to code. You can create a whole stand-alone application using Java.
- Java supports automatic memory allocation and deallocation (called as garbage collection).
- Offers great performance as Java supports multithreading and concurrency, thus making it a highly interactive and responsive language.
- Secure and simple
What is Java platform?
You must have heard a lot about Java as a programming language.
But, do you know it is also a ‘platform’? Java platform is a
software-only platform quite different from the traditional platforms
like Windows, Mac, Linux or Solaris. The former runs on top of the
hardware of the latter platforms. Java programs go
through Java Virtual Machine, that converts the byte code into native
code, thus making the program run just any device! This means you don’t
need individual machine specific compilers for the Java code to run.
This is why Java is called as a platform too. Java programming language is different
from the Java platform. Java programming language helps you build
applications. What you write in Java programming language is developed
and run with the help of an existing collection of programs and tools
collectively called a Java platform. Java platform consists of the JDK,
JVM, and JRE.
There are four Java platforms of the Java programming language –
- Java SE (Java Platform, Standard Edition)
- Java EE (Java Platform, Enterprise Edition)
- Java FX
- Java ME (Java Platform, Micro Edition)
While stand-alone applications can be built on the Java SE
platform, most of the world wide web (internet) depends on Java EE. Java
ME is for applications on small devices (like mobile phones).
Components of Java
There are three main components of Java – JVM, JDK and JRE.
JDK or Java Development Kit is where the developers write their code and run it through the JRE or Java Runtime Environment.
How is the code translated? That’s through the Java Virtual
Machine (JVM). With JVM, any code is written in Java (or any other
language) can be translated to Java bytecode. Any machine can then
implement this code based on the Operating System. JVM resides inside
the JRE along with the java packages (libraries).
JDK | JVM | JRE |
JRE + development tools like interpreter(class loader), compiler (javac), jar files (package and archive) and javadocs. | The abstract machine where the java bytecodes are executed. Consists of specification document that describes JVM implementation, the actual implementation program and the instance of JVM (run-time) where you can run your main program. | Physical implementation (Runtime instance) of JVM. Contains the library packages and support files that JVM uses for running a program. |
If you have a system, you can try a few things as you read this article. To practice, you need to install JDK (Java Development Kit) and JRE (Java Runtime Environment) on your local system. To download the latest version, click here.
You can then set up an IDE on your system and work on the concepts that we will learn. Eclipse is a good IDE that I use, whenever I need to run a program on Java. It is easy to set up and does not bother you much. You can either download Eclipse or Easy Eclipse. Easy Eclipse is a lighter version of eclipse with fewer features. There are many more IDE’s,
Are you all setup?
Before we jump into coding, let us familiarize ourselves with a few terminologies –
Every java program is a collection of different types of objects that
are defined by a class or interface. This is the basic structure –
class College {
public String CollegeName;
public int ID;
Teacher[] teachers;
Student[] students;
…..
public int getCollegeName()
{
}
}
The logic is all inside the methods, that can be as
simple as getter and setter methods of a class or as complex as fetching
something from the database based on multiple conditions!
Note that, just like any other programming language, every stand-alone program in Java should have a main method to execute.
Create a Test class and add some simple code to it.
class Test{
public static void main(String args[]){
int rollNumber = 34;
String name = “Meoz”;
System.out.println(“My name is ” + name + “ and my roll number is ” + rollNumber);
}
}
There is learning in each line of this code.
- class – this keyword is used to
create a java class. When you run the program, you would give the
command javac Test.java to compile and java Test.java to execute. If you
are using IDE, you have to just right click on the class and select
Run. - public – public is an access
modifier that indicates the visibility. Main method cannot have access
modifier as private (access modifier). Private methods can be called
only within the class, whereas public methods are visible to all. - static – Variables and methods can use the static keyword. Why is
the main method static? For static methods, we don’t have to create an
object. Hence, we don’t have to create an object of Test to invoke the
main method. - void – if a method doesn’t return any value, its type is set as void.
- int, String – these are two of the
many data types that Java uses. Because it also uses primitive types,
Java is not considered a fully Object-Oriented language. - System.out.println – out is a
static field of the class System. This field stores the instance of
PrintStream class. println() is the method of this class, that prints
the required output to the console.
Let us slightly modify this program to get the name and roll number as inputs from the user. There are many ways to do this. For this code, let us use the most common method – Scanner class. To use this class, we need to import the class as import java.util.Scanner;
In the previous code, before the System.out.println (syso), let us add the following lines of code –
Scanner scanInput = new Scanner(System.in);
System.out.println("Enter name: ");
name = scanInput.nextLine();
System.out.println("Enter roll number: ");
rollNumber = scanInput.nextInt();
When you run this program, you will be prompted to enter a name and then a roll number.
The other ways to do this is through BufferedReader, which is the traditional method but it has too much wrapping which can be difficult
to remember.Let us get information about more students – their names, roll numbers and subjects. Subjects will be in array because for this program, let us assume, one student will take up 3 subjects.
Define an array as –
String[] subjects = new String[3];
for(int j=0; j<subjects.length;j++){
subjects[j] = scanInput.next();
}
- Here we are using a for loop to get subjects from
the user and storing it in the String array. The syntax of for loop has
changed in latest java versions, but this syntax is easier to use. ‘j’
is a temporary counter that starts from 0. Note that we do j - subjects.length gets the length of the array, which in this case is 3.
To view the contents of array, type Arrays.toString(subjects)
As we see, we have three variables name, rollNumber and subjects
which all belong to a common entity Student. So, why not create a class
and have all the 3 variables as members of the class? It will be easier
to add, modify and delete data when we use them as objects!
Let’s create a class Student.java –
public class Student {
int rollNumber = 0;
String name = "";
String[] subjects = new String[3];
}
We will have to change our code to create an object of this class and
access the variables through getter and setter methods. An example of
getter and setter method is –
public int getRollNumber() {
return rollNumber;
}
public void setRollNumber(int rollNumber) {
this.rollNumber = rollNumber;
}
The IDE will create all these for you, but for your practice, it will be good to do it yourself.
Now, let us get back to our main program.
We already have all the data for one student, why not fetch details
of more students! We can create an array of Student objects and store
each student’s detail in one object from the array.
Let us get the number of students from the user as
int numberOfStudents = scanInput.nextInt();
Now, let us start another for loop, which will get details from all the students –
for(int i=0;i<numberOfStudents;i++){
}
All we have to do now is set the data into student objects. For this,
create an array of Student objects of size same as numberOfStudents.
Student[] student = new Student[numberOfStudents];
for(int i=0;i<numberOfStudents;i++){
student[i] = new Student();
name = scanInput.next();
student[i].setName(name);
rollNumber = scanInput.nextInt();
student[i].setRollNumber(rollNumber);
for(int j=0; j<subjects.length;j++){
subjects[j] = scanInput.next();
}
student[i].setSubjects(subjects);
}
Few things in the code –
- When we create the Student[] array, the individual Student objects
are still null. That’s why inside the for loop, we are creating new
Student object. Not doing this will throw a NullPointerException, when
we try to use student[i].. We will touch upon exceptions later in this
article. - We are using next() for String instead of nextLine(). nextLine()
will skip the current line and go to the next one. It is always better
to use next(). - Let us say, user gives numberOfStudents as 2. The outer for loop
will execute twice. The size of subject array is 3, so the inner for
loop will execute 3 times for each outer loop, hence a total of 6 times. - Note the naming convention in Java. The variable
names and method names start with small case but we capitalize the first
letter of every word, while the class names start with a capital
letter.
Now, we have all the data in the Student array. We can improve the code using a Java Constructor, which is a more efficient way of storing things in objects than a setter method. When you have a lot of data, instead of using set method 10 times, you can set all the values in the constructor at once. Let us create a constructor in our Student class.
public Student(String name, int rollNumber, String[] subjects){
this.name = name;
this.rollNumber = rollNumber;
this.subjects = subjects;
}
Now, let us modify our Test class to use this constructor. Note that, now the line
student[i] = new Student()
will not work, as we have not created a no-arg constructor in our
class. When no other constructor is defined, java compiler creates the
no-arg constructor by default, otherwise, we should use the ones we
create in the code.
Our code will now become –
System.out.println(“Enter name and roll number: “);
student[i] = new Student(scanInput.next(), scanInput.nextInt(), subjects);
which reduces about 3-4 lines of code for us. Imagine, how useful it
can be when there are many more objects and member variables. Note that
the subjects array will be empty, as we are getting the values of
subjects after name and rollNumber.
The next question is where do we store these student objects so that
we can retrieve them later and do some modifications or display the
contents of the list? The simple answer is ArrayList. It is very simple to create an ArrayList and add objects to it.
Some important features of ArrayList –
- ArrayList is dynamic. We can expand ArrayList at any time, the size is not fixed, unlike arrays.
- ArrayList is an important part of the Java Collection Framework.
- We can access any object in the list randomly.
- We can store only objects in ArrayList. If we have to create an ArrayList of integers, we need to wrap the primitive int types into Integer object.
Getting back to our code, let us create the ArrayList as –
ArrayList studentList = new ArrayList();
To add objects to the list, after fetching all the details, just add the complete object to the list.
studentList.add(student[i]);
Rather than confusing ourselves with looping over an array and
addressing each object as student[0], student[1], etc… let us use an Iterator to fetch and display the data.
Think of Iterator as a cursor, that traverses through the elements of
a collection. You can fetch or remove any element from a collection
using an iterator.
Iterator itr = studentList.iterator();
System.out.println("The entered details of all the students are---");
while(itr.hasNext())
{
System.out.println(itr.next().toString());
}
- We don’t create a new object of Iterator(), rather use the list’s iterator method to point to itr.
- The while loop checks, if there are any more
objects in the list using, hasNext() method. The while loop will end
when hasNext() returns false. - itr.next() gets the next item on the list.
You would expect the output to be the neat details that you had entered. Right? But Java will give us something like this –
The entered details of all the students are—
Student@e7b241
Why?
Because to print the members of the object individually, we need to override the toString() method in our Student class.
public String toString(){
String studentDetails = null;
studentDetails = "Student name: " + this.name + ", Student roll number: " + this.rollNumber + " , Chosen subjects: " + Arrays.toString(this.subjects) + "n";
return studentDetails;
}
- The this keyword is a reference variable that points to the instance variable of the current class.
- To get values from an array, we use the toString() method of the utility class Arrays. Note that Arrays contain static methods and hence we need not create an object to use the methods. We are directly using the class name and method name.
Voila! You will now get the result you want!
But, there is one problem…
We haven’t taken care of the scenarios where user gives wrong inputs!
For example, what if someone enters a String for rollNumber? We
wouldn’t throw the entire stack trace of the exception to the user. We
can instead, put a nice message to the user.
Try to enter a string for rollNumber, you will get Exception in thread “main” java.util.InputMismatchException
To ensure this doesn’t happen, we need to make sure the user enters correct values. But, how? Let’s put a try/catch block to catch the exception and display a friendly message to user when there is an error.
try{
rollNumber = scanInput.nextInt();
}catch (InputMismatchException ime){
System.out.println("Please enter a valid number");
}
We can apply the same for numberOfStudents too. The best practice is
to put the entire code in the try block, so that any exception can be
caught in the catch block.
This is called exception handling in Java. In a real-world application, classes can throw
the exception and the last one will catch and display the appropriate
message to the user. There are many more runtime exceptions in Java, the
most common being NullPointerException, ClassCastException,
ArithmeticException, IllegalArgumentException,
ArrayIndexOutOfBoundsException, etc…
A quick recap
In this article, I have touched the basics of Java, with which you
can start coding in Java as long as you know what a programming language
is and have worked with some other language before. We have understood
the basic concept of –
- Class and objects
- Constructors
- I/O streams
- For and while loop
- Primitive and non-primitive data types
- toString() method
- Collection (ArrayList) and Iterator
- Basics of Exception handling
through a simple program. There are many advanced concepts which are
not in the scope of this article, however, stay tuned as we are coming
up with more articles for advanced concepts like Threads, inner classes,
interface, garbage collection and many more.