Editor's note:
This article is mainly written for beginners or beginners to Java introductory cognition and learning guide. The initial plan is to write three or four articles, so that students who are beginners in Java programming can better understand Java, master the core cheat list in Java programming, and the popular application frameworks that should be known in advanced learning. Experienced Java personnel can skip this article. New students are also welcome to leave a message for consultation.
Java is an Object-Oriented Programming Language (Object-Oriented Programming Language) based on the concept of Object-Oriented Programming Systems (OOPS).
Everything in Java is about objects. If you grasp the essence of objects, Java is as simple and flattering as eating your favorite food.
The question is, since it is like food, there are many programming languages, but why should you learn Java?
1. Why Java?
Simply put, because Java is like your favorite delicious (easy to code) and healthy (safe and robust) food!
Apart from the fact that Java is one of the top programming languages of 2021, and probably will remain there for at least another decade, Java has succeeded in just about every field you can think of!
Since Java is secure and multi-threaded, it is ideal for banking and transaction management services. The logic of the e-commerce store and billing software is written in a Core Java based framework. Mobile operating systems like Android also use Java APIs; stock market algorithms are based on Java; and all of the big data—the massive amounts of data—in recent times, is handled with ease in Java. In fact, Hadoop's MapReduce framework is written in Java. Java forms a powerful combination with other frameworks such as Spring for ordering implementation dependencies in the financial and IT domains and writing corresponding server-side applications.
2. What is Java programming?
Java is a "write once, run anywhere" programming language developed by Sun Microsystems. It's similar to C and C++, but much easier. You can combine Java with many technologies like Spring, node js, Android, Hadoop, J2EE, etc. to build robust, scalable, portable and distributed mature applications. Java also facilitates continuous integration and testing using tools like Selenium.
3. A Brief History of Java
Java was originally developed in the early 1990s by James Gosling and his colleagues at Sun Microsystems. Originally, it was called the "Oak" project, and its implementation was similar to C and C++. The name Java was chosen after a lot of brainstorming, and it comes from the name of a coffee bean. Java 1.0, the first version was released in 1995 with the tagline "write once, run anywhere". Later, Sun Microsystems was acquired by Oracle. Since then, there has been no turning back. The latest version of Java is Java 17 (a long-term support release) in September 2021.
4. Features of Java
Java offers many attractive features -
- Platform independent language.
- Rich standard library makes it easy to code. You can create a complete standalone application using Java.
- Java supports automatic memory allocation and release (called garbage collection).
- It provides excellent performance because Java supports multithreading and concurrency, making it a highly interactive and responsive language.
- Safe and simple.
- …
To learn
more about Java features, check out the article on the official website.
5. What is the Java platform?
You must have heard a lot about Java as a programming language. But, did you know it's also a "platform"? The Java platform is a software-only platform, distinct from traditional platforms such as Windows, Mac, Linux, or Solaris. The former runs on the hardware of the latter platform. Java programs go through the Java Virtual Machine, converting bytecode to native code, allowing the program to run on any device! This means you don't need a separate machine-specific compiler to run Java code. That's why Java is also called a platform. The Java programming language is different from the Java platform. The Java programming language helps you build applications. What you write in the Java programming language is developed and run with the help of an existing collection of programs and tools (collectively known as the Java platform). The Java platform consists of JDK, JVM and JRE.
Java programming language There are four Java platforms -
- Java SE (Java Platform, Standard Edition)
- Java EE (Java Platform, Enterprise Edition, now Jakarta EE)
- Java FX (can be considered more advanced Swing, but can develop mobile applications)
- Java ME (Java platform, micro version, terminal electronic equipment)
While it is possible to build stand-alone applications on the Java SE platform, most of the World Wide Web (Internet) relies on Java EE. Java ME is suitable for applications on small devices such as mobile phones.
Java has three main architectural components - JVM, JDK and JRE.
JDK (Java Development Kit) is the Java Development Kit, where developers write code and run it through JRE (Java Runtime Environment).
How is the code translated or translated? That is done through the Java Virtual Machine (JVM). Using the JVM, any code written in Java (or any other language - that supports bytecode) can be converted to Java bytecode. Any machine can implement this code based on the operating system. The JVM resides in the JRE along with Java packages (libraries) to serve Java programs.
in short:
- JDK: Contains JRE + development tools, such as interpreter (class loader), compiler (javac), jar files (packaging and archiving), and javadocs, etc.
- JVM: An abstract machine that executes java bytecode. Consists of a specification document describing the JVM implementation, the actual implementation program, and the JVM (runtime) instance in which the main program runs.
- JRE: The physical implementation (runtime instance) of the JVM. It contains library packages and support files that the JVM uses to run programs.
If you have a computer, there are a few things you can try as an exercise while reading this article: Install the JDK (Java Development Kit) and JRE (Java Runtime Environment) on your local system. To download the latest version, go to the official Java website.
You can then install an IDE on your system to handle the concepts we'll learn. Eclipse is a good IDE that I use, it's easy to set up and doesn't bother you. You can download Eclipse or Easy Eclipse. Easy Eclipse is a lightweight version of Eclipse with fewer features, suitable for beginners. There are other more IDEs, such as netbeans, JDeveloper, IntelliJ IDEA, BlueJ, etc. - starting from Java 9, you can start preliminary java programming learning in JShell, providing convenient learning support for beginners.
If you don't want to do any of that right now and just want to read about Java, great! Just keep reading, grasp the concepts, and start coding anytime!
6. Terminology and programming awareness
Before we start coding, let's get familiar with some terminology -
Every Java
program consists of a collection of objects of different types defined by a
class or interface. This is the basic structure –
class School {
// Consists of several other objects and instance variables
public String schoolName;
public int ID;
Teacher[] teachers;
Student[] students;
…
// and some other methods
public int getSchoolName(){
}
}
The logic is all inside the method, it can be as simple as a class's getter and setter methods, or as complex as fetching something from the database based on multiple conditions!
Let's write a simple program and we'll add extensions as we learn more Java concepts.
Note that every single program in Java should be executed by a main method, just like any other programming language.
Create a
Test class and add some simple code to it, as an example:
class Test{
public static void main(String args[]){
int rollNumber = 36;
String name = “Solo”;
System.out.println(“My name is ” + name + “ and my roll number is ” + rollNumber);
}
}
Each line of this code is learned one after the other, briefly described below:
- class – This keyword is used to create a java class. When you run the program, you use the command javac Test.java to compile the code and java Test.java to execute the program. If you're using an IDE, just right-click the class and select Run.
- public – public is an access modifier indicating visibility. The main method cannot make the access modifier private (access modifier). Private methods can only be called within the class, while public methods are visible to everyone.
- static – Variables and methods can be modified with the static keyword. Why is the main method static? For static methods, we don't have to create objects to use them. Therefore, we don't have to create a Test object to call the main method.
- void – If the method does not return any value, its type is set to void.
- int, String – These are two of the many data types used by Java. 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 System class. This field stores an instance of the PrintStream class. println() is a method of this class that prints the desired output to the console.
Let's
modify this program a bit to get the name and volume number entered by the
user. There are many ways to do this. For this code, let's use the most common
method - the Scanner class. To use this class, we need to import the class
first: import java.util.Scanner;
In the
previous code, before System.out.println(…), let's 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 running this program, you will be prompted to "Enter name:", then "Enter roll number:".
Another way is through BufferedReader, which is the traditional way, but it has too many wrappers that are hard to remember.
Let's find out more about the students - their names, registration numbers and subjects. The subjects will be in the array, for this program it is assumed that a student will take 3 subjects.
Define the array as :
String[] subjects = new String[3];
//Get all the subject information of the student
for(int j=0; j<subjects.length;j++){
subjects[j] = scanInput.next();
}
Here we use a for loop to get the subjects from the user and store it in a String array. The syntax of the for loop has changed in the latest java versions, but this syntax is easier to use. 'j' is a temporary counter starting from 0. Note the change in j.
subject.length gets the length of the array, in this case 3.
To view the contents of the array, use Arrays.toString(subjects) to view, or output to the console.
As we can see, we have three variables name, rollNumber and subject, which all belong to a public entity Student. So why not create a class and have all 3 variables as members of that class? Adding, modifying and deleting data is easier when we use them as objects! So, let's create a class Student.java as follows:
public class Student {
int rollNumber = 0;
String name = "";
String[] subjects = new String[3];
}
We will have to change the code to create objects of this class and access variables through getter and setter methods. An example of getter and setter methods is as follows:
public int getRollNumber() {
return rollNumber;
}
public void setRollNumber(int rollNumber) {
this.rollNumber = rollNumber;
}
IDEs can provide you with shortcuts for creating all of this when using an IDE, but for beginner exercises it's best to do it yourself.
Now, let's go back to our main program.
We already have all the data for one student, why not get more student details! We can create an array of Student objects and store each student's details in an object within the array.
Let's get the number of students from the user:
int numberOfStudents = scanInput.nextInt();
Now, let's start another for loop which will fetch details from all students –
for(int i=0;i<numberOfStudents;i++){
// get details
}
All we have to do now is set the data to the student object. To do this, create an array of Student objects of the same size as numberOfStudents. code show as below:
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);
// same as written before
for(int j=0; j<subjects.length;j++){
subjects[j] = scanInput.next();
}
student[i].setSubjects(subjects);
}
- When we create the Student[] array, the single Student object is still empty. That's why in the for loop, we are creating new Student objects. If you don't, trying to use student[i].. will throw a NullPointerException. We will discuss exceptions later in this article.
- We use next() for String instead of nextLine(). nextLine() will skip the current line and go to the next line. It is better to use next().
- Suppose the user sets numberOfStudents to 2. The outer for loop will execute twice. The size of the topics array is 3, so the inner for loop will execute 3 times for each outer loop, so 6 times in total.
- Note the naming conventions in Java. Variable and method names start with lowercase, but we capitalize the first letter of each word, and class names start with an uppercase letter.
Now, we have all the data in the Student array. We can improve the code by using Java constructors, which is a more efficient way of storing things in objects than setter methods. When you have a lot of data, you can set all the values in the constructor at once instead of using the set method 10 times. Let's create a constructor in the Student class. As follows:
public Student(String name, int rollNumber, String[] subjects){
this.name = name;
this.rollNumber = rollNumber;
this.subjects = subjects;
}
Now, let's
modify our Test class to use this constructor. Note that now the line:
student[i] = new Student();
This line won't work because we didn't create a parameterless constructor in our class. The java compiler creates no-arg constructor by default when no other constructor is defined, otherwise, we should use the constructor we created 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);
This saves us about 3-4 lines of code. Imagine how useful it can be when there are more objects and member variables. Note that the subjects array is empty because we're getting the subject's name and rollNumber before the subjects' value.
The next question is where do we store these student objects so that we can retrieve them later and make some modifications or display the contents of the list? The simple answer is ArrayList. Creating an ArrayList and adding objects to it is very simple.
Some important features of ArrayList to know:
- ArrayList is dynamic. We can extend ArrayList at any time, the size is not fixed, unlike arrays.
- ArrayList is an important part of the Java collection framework.
- We can randomly access any object in the list.
- We can only store objects in ArrayList. If we have to create an ArrayList of integers, we need to wrap the primitive int type into an Integer object.
Back to our code, to create the ArrayList as :
ArrayList studentList = new ArrayList();
To add an
object to the list, after getting all the details, just add the complete object
to the list. Add like this:
studentList.add(student[i]);
Instead of confusing array loops and addressing each object as student[0], student[1], etc... let's use an Iterator to get and display the data.
Think of an iterator as a cursor that iterates over the elements of a collection. You can use iterators to get or remove any element from a collection. Similar to the following:
Iterator itr = studentList.iterator();
System.out.println("The input information of all students is ---");
while(itr.hasNext()){
System.out.println(itr.next().toString());
}
- Instead of creating a new object of Iterator(), we use the iterator method of the list to point to itr.
- The while loop uses the hasNext() method to check if there are more objects in the list. The while loop will end when hasNext() returns false.
- itr.next() gets the next item in the list.
The output you want should be clean input. Isn't it right? Java gives something like the following -
Student@e7b241
Because we want to print the members of the object individually, we also need to override the toString() method in the 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;
}
- this keyword is a reference variable, pointing to the instance variable of the current class.
- To get a value from an array, we use the toString() method of the utility class Arrays. Note that Arrays contain static methods, so we don't need to create objects to use these methods. We use class and method names directly.
See, now you'll get the results you want!
However, there is a problem...
We didn't handle user input error scenarios! For example, what if someone enters a string for rollNumber ? We don't throw the entire stack trace of the exception to the user. Instead, we can send a good message to the user.
try to
enter a string for rollNumber you will get exception in thread "main"
java.util.InputMismatchException.
try{
rollNumber = scanInput.nextInt();
}catch(InputMismatchException ime){
System.out.println("Please enter a valid number");
}
To make sure this doesn't happen, we need to make sure the user enters the correct value. But how? Let's put a try/catch block to catch the exception and display a friendly message to the user when there is an error.
We can also apply the same method to numberOfStudents. The best practice is to put the entire code in a try block so any exceptions can be caught in a catch block.
This is called exception handling in Java. In a real application, classes can throw exceptions and eventually some class will catch and display an appropriate message to the user. There are many more runtime exceptions in Java, the most common are NullPointerException, ClassCastException, ArithmeticException, IllegalArgumentException, ArrayIndexOutOfBoundsException etc...
7. A quick review
In this article, I touched on the basics of Java, just to give you an idea of what a programming language is, and if you've used other languages before, you can start coding in Java in no time. Through this article, to understand the following basic concepts -
- Classes and objects
- Constructor
- input/output stream
- for and while loops
- Basic and non-basic data types
- toString() method
- Collection (ArrayList) and iterator
- Exception Handling Basics
Here is
just a simple procedure to recognize these. There are many more advanced
concepts that are beyond the scope of this article, but stay tuned for this
headline, where more articles on advanced concepts like threads, inner classes,
interfaces, garbage collection, etc. will be or have been introduced.
In the next
article, students who are learning Java programming will be provided with a
checklist of core basic knowledge for reading at any time. This article is
here, let's share it. goodbye!