Java Tutorial

Welcome to the introductory lesson of the Java Tutorial, which is a part of the Java Certification Training Course. This lesson gives a brief introduction to Java, its benefits for professionals, and the topics it covers.

Let us begin by introducing Java.

What is Java?

Java is a programming language that was initially built for electronic devices, small and home user segment. Due to its ability of being portable in different platforms of the embedded system segment, it became popular in development of web applications.

Java is purely object-oriented language. It is portable because you can write it once and run it on different platforms. Java is used for developing various applications for the web, devices, enterprise servers, middlewares, etc.

Java EE platform is designed to help developers create large-scale, multi-tiered, scalable, reliable, and secure network applications.

In the next section, let us talk about the benefits of Java Tutorial to professionals.

Java Tutorial Objectives

By the end of this Java Tutorial, learners will be able to:

  • Discuss the Java technology

  • Discuss object-oriented programming (OOP)

  • Explain the fundamentals of Java language

  • Explore primitive data types and wrapper classes in Java

  • Set up Java and Eclipse on our systems

  • Write and run the first Java program

  • Have a complete understanding of the Core Java 8 concepts including the scope of variables, operators, arrays, loops, methods, and constructors

  • Explain servlet fundamentals such as J2EE, HTTP Protocol, and HTML in detail

  • Implement multi-threading, string handling, and exception handling techniques

  • Have a hands-on experience in JDBC and JUnit Framework

  • Learn the advanced Java topics such as Service Oriented Architecture (SOA), web services and Hibernate and Spring frameworks

  • Describe how to configure AOP in a Java application

Let us move ahead with the lessons covered in this Java tutorial.

History of Java

The search for “Java” like language started in 1990 when you actually required such an application development API that could provide the capability to write portable code that could run on any device.

So Java was developed by James Gosling in 1995 and was then apparently taken over by Oracle Corporation. It's now part of the Oracle Corp. Today it's almost used everywhere, whether you're looking at applications developed for the web, devices, enterprise servers, middleware, etc.

Why Java?

Some of the important features of Java language are discussed below.

Easy to read language

Firstly, Java is a simple and an easy-to-read language, it's flexible to change. Any developer who has written code, it becomes easy to maintain if that developer leaves the organization. You have rest of the team members that have to pick up and maintain the code. It becomes easy because it's quite simple to understand.

Purely object-oriented language

In terms of how the language is structured, it is purely object-oriented and it follows the object-oriented programming system.

In OOPS, you try to simulate the real world and model it into your applications so that maintaining the application is easier. It is because there is a direct relationship between the code that you write and to your entities that actually exist in the real world in part of your problem statement.

Distributed and interpreted

It is distributed as well as interpreted, which means you can run it on the servers, middlewares, web server, mobility devices, etc. You can distribute the processing load to a client-server kind of an environment.

It is interpreted which means it runs in a two-step compilation process, which is what makes it platform independent. So when you compile the Java program, rather than directly generating machine code, it converts into some intermediate bytecode.

Hence it is much quicker in terms of execution because it does not directly compile to machine code. It compiles to an intermediate language which then uses the runtime environment to compile to machine code which is targeted to the specific platform on which the runtime is installed.

Robust, platform-independent, and secure

Java is robust, platform-independent, and secure.

It provides a strong networking infrastructure for service side computing. For example, consider that you have a chat server where the code is installed on the remote system and you have multiple clients connecting to it. So you can use Java to actually write your applications that can be distributed and accessed by multiple users remotely.

It can be used in the top mobile OS, for example, Android studio. If you're developing apk applications installable on the Android platform, you can use the Android studio, Eclipse as an editor, and Java as a programming language of choice.

Has well-defined libraries

Java is an API. API is technically a set of functions. A group or functions together is called as a library which is created through modification from the existing C programming libraries.

So Java works at a level above the operating system. On top of the operating system, you have one more layer which is the Java runtime environment.

Your Java program does not directly run on top of the OS, it actually runs on top of the framework which is the runtime engine. Hence you do not have to do too much of management in terms of memory and in terms of optimizing the amount, of course, you have loaded into memory and executing.

All of that work is outsourced to the runtime engine or the framework so that you do not have to struggle like an embedded system or a raw language like C or C++ (where you directly target the OS and you have to manage a lot of things yourself in terms of memory management).

Java is much secure because it focuses on the business problem and leaves all the infrastructure issues for the framework to manage (which could be better effective memory management and ensuring that we do not illegally access memory that is already allocated).

Types of Java Applications

The various types of Java applications that you can create today are:

  • Standalone application

  • Web Application

  • Enterprise Application

  • Mobile Application

Standalone Application

It is an application that needs to be installed on every machine, such as a set-top box, antivirus, and media player.

An example of a standalone application is Microsoft Word which typically runs on your desktop and you need a physical installation of it.

Web Application

It is an application that runs on the server side and creates a dynamic page.

The web application runs in a browser. An example of this would be Facebook where we do not need to physically install anything.

Enterprise Application

It is a business application that has a high level of security, load balancing, and clustering, such as a banking application. It is developed using Enterprise Java Bean (EJB).

An enterprise application is an end to end application that makes the entire business paperless and takes it online. An example of this could be the banking system. The customers of the bank would have a web application to connect to their subsystem and use it.

Let's take HDFC bank as an example. So we could have a web-based application for the bank which could be used:

  • for customers

  • for employees within the organization to manage user accounts

  • to create fixed deposits

  • to transfer funds

We could also have a mobile-based application for users who are in transit. We could also have a desktop-based application which is a physical installation of a standalone app.

So different user interfaces could be given to the application so that various regional offices would connect to a central server on which we would have a block of code running.

Having a central server means that the moment we have a new update to our code, rather than going to all the branches of the bank, we just push it to the central server and all the branches would get the current code updates to the current changes that would be made.

So an enterprise application caters to the entire business. It takes the entire business online and looks at providing an end to end online IT-based solution to cater to the end users, the customers, and the bank employees.

It could also give meaningful reports to the management so that they can take better decisions in terms of how to run the business.

Mobile Applications

It is an application for mobile devices. It is currently developed using Android and Java Micro Edition (Java ME).

Mobile applications are now a mandate and not a luxury any longer because the industry is moving towards that.

Java Editions

There are multiple Java editions that are available today. They are discussed below.

Java Standard Edition (SE)

The Java standard edition called as SE is the standard SDK that is used to develop applications for the desktop.

Java Enterprise Edition (EE)

The enterprise edition is typically what is used to take the entire business online. So it needs to cater to the web aspect, the data storage aspect, the mobility aspect, and to develop a standalone application.

So it's an all in one solution which has multiple tiers. There are different APIs available within the Java development kit which allows you to develop applications for these different tiers which could be database, middleware, front end, or mobility.

Java Micro Edition (ME)

It is specific to mobile devices.

Java SE

In terms of the second edition of Java, if you look at some of the core concepts around it, it's a standard edition core Java programming platform.

A Java standard edition contains multiple Java libraries. It allows development and deployment of Java applications on either a desktop, a server, or various embedded environments. Embedded environments would be any kind of device on which you have an application that is running and built on Java.

And it is used to build standalone applications like Microsoft Word, Excel, etc.

The latest version available for Java is Java 8, which is the stable release. We also have a Java 9 or JDK 9. JDK stands for Java development kit, and it is the software that you need to download to get started with building applications for Java.

The JDK application is available in version 9 as well but that is still in beta. The 8th version is preferred because it's a stable release.

A stable release ensures that the application you are building has a higher probability of running without any errors, issues or crashing.

Java EE

An enterprise edition of Java lets you develop large-scale, multi-tiered, scalable, reliable, and secure network applications. So multi-tiered and scalable indicates that multiple users can connect to it.

It has a set of functions, technically called an API, to develop distributed apps. Distributed apps would be part of the application running on your client and part of it running on the server.

For example, when we have a mobile app:

  • part of it is processing on our local mobile phone using the processing speed of the mobile phone.

  • for the data, it is connecting to the server to get the updates.

So distributed applications are applications that run on multiple systems.

The enterprise edition allows an application to be hosted at one place and accessed across the world over the internet.

In terms of the enterprise edition, the version in the market today is Java EE 7.

Java ME

The micro edition helps you develop programs for mobile application devices. It consists of programming specifications and a special virtual machine that allows a Java ME encoded program to run on mobile devices.

The latest version in the market, that is stable release, is Java ME 8.3

Differences between Editions

The differences between the three different editions have been listed below.

SE API Package

EE API Package

ME API Package

java.applet

javax.annotation

Device Access API

java.awt

javax.ejb

System Configuration API

java.lang

javax.jms

OAuth2 API

java.rmi

javax.persistence

JSON API

java.sql

javax.servlet.http

HTTP Client API

java.util

javax.servlet.jsp

Security API

The above listed packages have been described below.

Standard Edition

The packages under this edition are as follows.

java.applet

If you look at the standard edition, you have Java applet. Applets are typically phased out. If you see the flash applications that run inside the browser, applets are similar to that.

It allows you to run small flash applications within the browser. They're phased out because browsers today do not allow you to have plug-ins installed.

We would prefer to use HTML5 to create small games, apps, or something which would run in the browser.

java.awt

Then we have java.awt which stands for abstract windows toolkit. It is an API to develop GUI or windows based applications in Java, very similar to the MS Office product which is a stand-alone product.

java.lang

Then we have java.lang which contains classes that are fundamental to the design of the Java programming language. So this is the core API or the core package.

When we say package, it is technically a grouping of functions or classes. So if we need to call some ready set of functions, for example, to draw a circle, we can call the java.lang.graphics.circle function, in terms of pseudo code.

Similarly, there are different packages that perform different actions and they have a set of classes or functions inside it that allow us to perform that action.

If we need to do file I/O or write to a file, we would have a java.io package. If we want to send a message, we would need a package which would give email capability.

Similarly, these packages group together functions which perform a certain action and we can use them. So java.lang is the route package that we generally need and has most of the standard codes that we would write in our Java program.

java.rmi

RMI stands for Remote Method Invocation and it is a set of functions that give a mechanism to create distributed applications. You can have your code hosted on the server and you could access it by sending a request from the client.

java.sql

Then we have java.sql which is used to perform java database operations while connecting to a database and firing SQL queries.

java.util

As part of the standard edition, we finally have java.util package which has collections and various other utility classes. The utility classes are used for storing temporary data and memory, iterating over the data, processing that data before it is sent to the database, accessing time and date etc.

You can also look at how you can internationalize your application. If you're building it with one language, how do you ensure that if somebody opens up the web application in another country with a different language, does that application automatically transition to that language?

Most of these utility classes are a part of java.util package.

Enterprise Edition

The packages under this edition are as follows.

javax.annotation

The first package is javax.annotation. So the annotation is typically a tag that represents the metadata that is attached with our Java code. It indicates additional information which is used by the Java compiler when compiling or processing our program.

The purpose of Java annotation is simply to associate information with our program element. So rather than writing too much code, annotation brings down the requirement to write code where you just identify your code with a small identifier at the top indicating that this is what this particular code should be doing.

javax.ejb

Then we have the Enterprise JavaBeans package i.e. javax.ejb. We discussed that EJB is used for developing enterprise based applications containing reusable code, which can be deployed on a remote server and multiple users can connect to it and use it.

javax.jms

Next, we have javax.jms package. JMS stands for Java Messaging Service, and it is a messaging standard that allows applications (on the Java platform) to create, send, receive, and read messages between each other.

So if we want one Java application to communicate with another Java application, we can use the JMS API so that messages and information can be sent.

For example, today if Vodafone, which is a telecom service provider, purchases Airtel as a service provider, we need both systems now to cross communicate.

So customers doing billing in one system needs to communicate with the other system. So we can send messages from one system to the other so that both the systems can communicate with each other using the JMS.

We do not wish to rewrite both the systems so we can get the integration of the Vodafone and Airtel billing systems.

javax.persistence

The next package is javax.persistence. This is an application programming interface or an API specification that describes the management of relational data in applications using Java platform.

So persistence means data storage. It's a lightweight Java class and the state of this is typically persisted to a table in a database. So this is more of an object-relational mapper or an ORM. We define an object inside your Java program.

An object is nothing but a real life entity. If we are looking at a banking system, our customer would be an object that exists in the banking system. So we would model a customer inside our java code.

The customer details need to be saved into the database, so for that, we will use the persistence API. It'll take that customer information and persist it to the database.

javax.servlet.http

Then we have the javax.servlet.http package. It supports the development of the servlet. Servlets are small Java programs that run on the web server and you can access them using the HTTP protocol.

They provide features that we can send a request to the Java program. The Java program will give us a response, which is in HTML and can be viewed inside the browser.

javax.servlet.jsp

Then we have the javax.servlet.jsp package. Now, this is a scripting language to create dynamic content for web applications. So the servlets are Java programs that are already compiled, which create dynamic contents. JSPs typically run slower as compared to servlets as it takes time to convert and compile these JSPs to Java servlet.

So Java servlets typically run faster compared to JSPs. JSPs allow you to create dynamic content by writing scripts on the service side. JSP is a server-side scripting language.

So you write programs on the web server depending on the user id that the user is logged in.

So if we are logging in to a banking application, depending on the user id used to log in, we would get account information or account details that are specific to us.

Micro Edition

The packages under this edition are as follows.

Device Access API

The first API here is a Device Access API. This Device Access API gives you a set of functions that allow you to access the device or its sensors so that you can write effective programs for that.

System Configuration API

Then there is a System Configuration API that allows you to access various system level configurations on the Android or the specific OS that is being run on that device.

OAuth2 API

OAuth2 API is an authorization framework that allows you to obtain limited access to user accounts such as facebook, twitter, etc. so that you can use the login credentials using claims-based authentication.

Here instead of you creating a username and password, the user will log in using his Facebook credentials. You will get the user authorized at facebook and then the user will come into your system.

JSON API

Then we have the JSON API. JSON stands for Javascript Object Notation. This API is used to send and receive data in the Javascript object format between the client and the server.

We use Javascript because Javascript is a platform independent language, runs on any OS and platform. Hence, once your data is in JSON, irrespective of which technology or which app is trying to consume this data, we would be able to consume it effectively.

HTTP Client API

Then we have  HTTP Client API. This is used to write code for the HTTP protocol so that you can communicate along with your mobile app using the micro edition.

Security API

Then we have the Security API which does not need too much of explanation. It obviously gives us a way to access sensitive resources when we are building applications for the Java micro framework.

Java 8 Features

Java 8, as we discussed, is the latest stable version of Java. It was released in March 2014. It allows developers to develop applications across a wide range of scenarios, from standalone to enterprise apps, also allowing you to build applications for the Internet of Things (IoT).

Internet of Things is where you could have a device, which is connected to the WiFi. It could even be a light bulb which is smart enough to understand data that this processed from the internet, right up to business based servers or enterprise servers that are deployed on the cloud.

So it includes upgrades to Java programming, Java Virtual Machine (JVM), tools, and library. So when you install Java, you get the Java development toolkit, which includes the JVM. JVM is the runtime environment that is specific to different platforms that actually gives you the portability feature of Java.

Some of the features of Java 8 are listed below:

  • Java 8 Date/Time API

  • Lambda Expressions

  • Method References

  • Functional Interfaces

  • Stream API

  • Base64 Encode Decode

  • Default Methods

  • forEach method

  • Collectors

  • StringJoiner

  • Optional class

  • Nashorn JavaScript

  • Parallel Array Sorting

  • Type Inference

  • Method Parameter Reflection

  • Type annotations and repeating annotations

  • Java Database Connectivity (JDBC) improvements

Let us discuss these features in detail.

Java 8 Date/Time API

There are some of the functions available in the Java framework which allow you to work around with the date and time.

For example, if we want a statement to be printed in the banking system, we would need access to the end of the month so that when it is the end of the month, the statement needs to be printed.

Lambda Expressions

Lambda expressions are typically expressions that allow us to pass an entire expression to a function. So it is a shortcut way where it's more about functional programming. It is where you can write an expression as a function, and that function really does not need to belong to any class.

So it's a shortcut way of writing everything in a single line. Below is an expression which shows the lambda operator.

Maths multiply = (int a, int b) ⎯˃ { return a+b};

This has a lot of benefits in terms of how you can write code in a simplistic way and also how you can pass the entire expression as a value to a function.

Method References

It is another feature where we can actually create references to object. It can be done either by creating new objects or by using an existing object.

List list = new ArrayList( );

store(new ArrayList( ));

Here we have created an object of the List class which holds temporary data. ArrayList is an inbuilt Java class. To use method reference, we create an object named store which takes ArrayList as the parameter. This is one of the things that we can do with method reference.

Functional Interfaces

Functional interfaces have a single functionality to exhibit. For example, if we want to compare two values, we can actually do it with a compareTo( ) method, which is used for comparison purpose.

There are a lot of readymade methods available which do not belong to any class (so you don't have to create an object of a class to access them). You can directly access these methods to do a comparison or to do quick validations and check. So it is simplistic from a syntax perspective.

Stream API

This is a new layer or an abstract layer introduced in Java version 8. So, you can actually process data in a declarative way, very similar to SQL statements. Now, this is very similar to what is available in .Net as the link or language neutral query system.

Let’s say we have a list of users. Now we need to iterate over this and find out what is the list of users inside. We can do this by using the stream feature i.e. using SQL like query as shown.

UserList;

select max(salary) from UserList

Base64 Encode Decode

To do encoding and decoding, we have the encode or decode methods.

Default Methods

We have default methods, which allow you to store default values into variables.

forEach method

This is used to iterate over each element present inside your stream. So once the stream returns a set of values from your list of users, you use the forEach method to quickly pick up values from the stream and print them.

Collectors

Collectors is actually a class that extends the object class, or object is the base of the route class in the Java framework. Most of the APIs available or the classes available, go and inherit from the object class, and this provides reduction operations.

For example, you have multiple lists of users and want to summarize them based on the salary. You want to look at the trend in terms of which is the person having the highest salary, which is the person who is having the highest balance in the account, or which is the person who has done a maximum number of banking transactions.

Then the collector feature allows you to get that done easily.

StringJoiner

If you want to construct a sequence of characters separated by a delimiter, (for example S, A, T) like we have a string and we want to break it up and tokenize it, then we have the StringJoiner class available.

Optional Class

It is used to contain not-null objects, so optional object is used to represent a null with absent value. For example, in a database, we have users or employees. Some employees may not be eligible for increments and hence salary incremented would show a zero.

Some employees would have resigned and hence their salary should not show a zero. It may give the wrong impression that the person has not got an increment. It should show us null.

Nashorn JavaScript

It is an improved javascript engine that replaces Rhino. Rhino was the original javascript engine. If you need to write javascript code along with your server-side jsp etc. you have much better performance (2-10 times) in terms of the compilation speed.

It directly goes ahead and compiles the code in memory and passes the bytecode to your Java virtual machine. So the first compilation of your Java code is going to be much quicker using this capability that is there as a part of the Java development kit.

Parallel Array Sorting

So there is a new feature in the array class available which allows you to use parallelism. It means we can run parallel processing threads. So if we have two user lists, we can run one mini-program that can access one list of users, and a second mini-program that can access the second list of users.

It will iterate over these list of users and get us our data.

Type Inference

It tells the data type of any expression. This is very similar to reflection. So if we really need to find which particular data type this particular variable or object belongs to, we can very easily get it.

Method Parameter Reflection

It is an extension to the reflection API and allows us to get the list of parameters passed to a method.

Type Annotations and repeating annotations

It is where you can apply annotations to your code and use it before any code block is required.

Java Database Connectivity (JDBC) Improvements

Some improvements have been done to the Java JDBC, which is the databases connectivity option available.

Java Object-Oriented Programming

OOP is a programming language organized around “objects” rather than “actions” and “data” rather than “logic.” So you focus on the real-life problem and the business problem rather than just focusing on writing too much of code.

Some of the important concepts of object-oriented programming are:

  • Class

  • Object

  • Inheritance

  • Encapsulation

  • Polymorphism

  • Abstraction

So let us go ahead and understand what these concepts are all about. Let us begin with Class and Object.

Now, the first thing that you do when somebody gives you a requirement, is you start with doing an object identification exercise. You start identifying what or which is the object in the system. Now, let's, understand how this is done.

Okay, so the first thing that we're going to look at is the object. So an object is something that is defined as a real-life entity. It comes with three things, which are state, behavior, and identity.

Why not enroll for a course in Java? Check out our Course Preview now!

Java OOP - Use Case Example

Okay, so let's, take an example of a student management system. So let us say that we're going to build a student management system. And now we need to identify all the objects that are part of the student management system.

As we know that an object is a real-life entity, so we'll start making a list of all the real-life entities that we actually see in our student management system.

A student management system is going to automate what the student does in class every day (attending sessions, creating assessments, creating reports, attending lectures, getting grades, etc.).

So when we sit in a classroom, we are going to identify what are the real-life things that we actually see around us. So we see:

  • Whiteboards

  • LCD projectors

  • Students

  • Faculty who are going to teach the students

  • Courses which the student is attending

  • Attendance that the student is going to take

  • Chairs

  • Tables  

The table shown below lists the state, behavior, and identity of the objects that we have found in a classroom.

We can see that there are only three objects are definitely meeting the definition and all these three objects need to be considered and modeled in your system. Now when you understand that you need multiple students to be tracked, you start building something called as a class.

So if an object is something that has state, identity, and behavior, a class is a template or a blueprint of that object.

For example, take a car as an object. The car should have desired features like color, kind of engine, kind of tires, automatic gears, etc. Then the class will be the factory that you're going to set up to start building the cars as per the specifications.

The class is nothing but a blueprint that will identify what are the types of objects that you're going to create.

Java Class

A class is a blueprint or prototype for creating objects, providing initial values for the variable state, and implementing behavior.

The syntax of creating a class is shown below:

access_specifier class ClassName

{

/*

class consists of

a)class level or global variables

b)objects

c) static and   methods

d) constructors

e) inner classes

*/

}

Inside the class, we may have a set of variables, a set of functions that operate on them, constructors, inner classes, etc. Once you create a class, you can create multiple objects or products from that blueprint.

Object

An object is a software bundle of related state and behavior. Software objects are often

used to model the real-world objects. An object is an entity that has “variable” and “method.”

An object has three characteristics:

  • State: Data (value) of an object

  • Behavior: The behavior (functionality) of an object, such as deposit, withdraw

  • Identity (ID): Typically implemented via a unique ID

The value of the ID is not visible to the external user. But, it is used internally by the JVM to identify each object uniquely.

Features of Java OOP

Inheritance

Inheritance provides a powerful and natural mechanism for reusing code. For example, we already have a class as a blueprint which means we have a factory that makes a car. Now we wish to have an amphibious vehicle (it should run on land as well as water).

Now the base class for the car that can run on land is already created. So we just create another class that extends from the base class and provide the capability of the car that can also go on the water.

The above concept is helpful because you do not need to touch the base class and make changes to it (because you'll have to retest it and there'll be effort and cost there). So rather than modifying the existing class, you just extend to the class by using inheritance.

So the top level class is called superclass or a base class and the class which inherits is called the child class. So this promotes reusability of the code.

So rather than writing the entire code again, you simply reuse code from the base class, bring it into your inherited class, and add only the extended features that you want into the new class. Hence, you save on testing the entire class, you just test the new class that you added.

And you also reduce your risk of breaking code that already works, by avoiding modifications to it.

The inheritance can be of three types:

  1. Single level

  2. Multilevel

  3. Hierarchical

The image clearly depicts what the above terms mean.

Below is a simple example of inheritance.

We have a Shape class, which is the base class and it draws shapes. Now we want a specialized class that only draws lines. So we can create a Line class, which inherits from the shape, and then has the capability of drawing lines.

The “extends” keyword is what is used to implement inheritance in Java.

Encapsulation

Encapsulation is grouping together of variables and methods inside your class so that the methods can operate on the variables that are all part of the same class. The entire thing works as one unit which is a black box. So it's easy for you to process any data if the data and the processing code is in the same class. So encapsulation wraps together the variables and the methods together in a single unit.

Polymorphism

The word ‘Polymorphism’ means ‘one from many actions’ or ‘one word multiple actions.’

There are two types of Polymorphism:

  • Compile time Polymorphism

  • Runtime Polymorphism

So here we have a base class called Shape. We have multiple inherited classes called Line, Triangle, and Rectangle. Now if we want to draw a shape, we have a method named draw( ).

So if we want to draw a shape, we can either decide whether we want to call the draw method of the base class or the draw method of the inherited classes.

Now, if we create an object of Line class, it will call the draw method of the Line class. So the runtime polymorphism overwrites the draw method of the base class with the one that we have in the inherited class. So this is what we call us runtime polymorphism or method Overriding.

If we have multiple functions called draw( ) in the same class with different parameters passed to it, that is what we would call as compile-time polymorphism or method overloading.

Abstraction

Abstraction allows us to abstract out common functionality into a base class.

Consider the image shown below:

So when we are building the system for employee management, in this case, we know that there is an employee and we know he should have an id and name. But we do not know anything beyond that because, later on, the organization may decide they want a permanent or temporary employee.

So we start with modeling the Employee class. Once we have clarity that the employee is going to be permanent or temporary, we go ahead and create a child class from the Employee class. So whatever common functionality (like mobile number, salary, address, etc.) that we can capture when we initially build our system, we capture that into the base Employee class.

So abstraction is typically nothing but hiding internal details and showing functionality which is called as encapsulation.

Consider an example of an ATM machine.

When we go to any ATM to withdraw money, we see a nice interface in front. Now if the entire interface was hidden to us, we wouldn't know which are the buttons to click on to actually get the money out.

So the ATM does not show us how the money is dispensed. That is hidden. It only shows us what the ATM has the capability to do.

So these are the internal details the bank needs for processing the cash transaction, which is not shown to the end user and that's hidden out. So the bank has a flexibility of modifying that process so that they do not have to expose that information to the end user.

Core Elements of Java Language

The core elements of the Java language are discussed below.

Classes and objects

The class has two components:

  • Class declaration—It contains the class name and the access modifier. The access modifier defines the accessibility of the class.

  • Class body—It comes after the declaration, and it contains functions and variables.

An object is an instance of a class. When a program is run, objects are created to do the task.

Methods

A method is a subprogram that contains the logic of the application. It acts on data and often returns a value.

It is referred to by name and can be called by its name.

Each method contains the following:

  • Declaration—includes the method name, return type, parameter, and accessibility

  • Body—contains information that determines the behavior of the object

The general syntax of a method is as shown:

public static void main (String[] args)

{

statement;

method1();

statement;

method2();

statement;

}

Variables

Variable is a reserved memory that temporarily stores a data value and thus has a data type. It can be either declared or inferred. It adheres to type constraints.

There are four types of variables in Java:

  • Instance/non-static variables—a variable that belongs to an object

  • Static variables—a variable that belongs to a class

  • Local variables—a variable declared inside methods, constructors, or blocks

  • Parameters—a variable that is passed to a method when the method is called

Example of a non-static variable:

public class MyClass

{

public static void main(String[] args) {

int number = 5;

number = number + 10;

}

}

Components of Java

The components of Java are discussed below:

Java Development Kit (JDK)

JDK contains JRE and development tools necessary to compile, document, and package Java programs.

The JDK typically contains the java compiler which is a file called ‘JavaC’ and a file called ‘java’ that allows you to execute the code that you write.

Java Runtime Environment (JRE)

Java Runtime Environment has a virtual machine that allows you to execute your code and convert it to machine specific code. The runtime environment also has support files and libraries that allow you to execute your java program on the destination system or the production environment.

So the Java Runtime Environment actually takes your Java bytecode. The bytecode is the code that gets generated when you first compile your project on the development machine.

The JRE contains all the class libraries and other files that are required for the JVM to execute that bytecode and convert it to machine specific code that is targeted at that specific OS or environment.

Java Virtual machine (JVM)

The Java virtual machines is an abstract machine which sits on top of the OS. Unlike other languages like C or C++ program, Java programs are executed on a CPU that does not exist. It means they execute on the virtual machine, not directly on the OS and hence are portable because they do not directly target the processor, hardware, or operating system.

They work on the virtualized machine and the virtual machine ensures that the machine code is generated just in time. And hence this gives you the portable feature of Java where you write once and run on any machine.

So you write your code in a .java file, compile it on the development machine into a .class file. You then use the runtime environment which is specific to that OS or platform.

You have different flavors and downloads available of the runtime environment specific to an OS or platform.

Hence, when you execute your bytecode, it would look at the OS executed on the virtual machine and generate a specific file that targets only that particular processor and OS and that is what we refer to as machine code.

Java Architecture

The Java Architecture is shown in the image below:

We write our Java source code in a .java file. We compile it using the javac compiler. All these components are part of the Java development kit.

This process executes on the Development system. Once you compile the program, it gets converted into a .class file, which is bytecode. You then move that to the production system. The production system would have its own hardware and operating system.

On top of it, the Java runtime environment would sit, which has the virtual machine as part of it. The runtime environment comprises of inbuilt components like the class loader.

The class loader is required so that it breaks down your code and loads the various classes that you have in your code. The bytecode verifier verifies whether the code that you've written is in the valid format.

So we write our code in a java file and compile it to form a .class file. The .class file is moved to the production machine. Then we search for a runtime environment that suits the OS and platform, install it.

That's all we need for our java program to be platform independent and run on any OS.

Primitive Data Types and Wrapper Classes in Java

A variable is a temporary memory storage area which is held in the RAM of our computer. We can use different data types to define what is the format of the data we're going to store.

Primitive data types are basic data types in Java language.

There are 8 primitive data types:

  • int 4 bytes

  • Short 2 bytes

  • Long 8 bytes

  • Byte 1 byte

  • Float 4 bytes

  • Double 8 bytes

  • Char Unicode encoding (2  bytes)

  • Boolean {true, false}   

We always ensure that we have a coding convention while writing code so that other developers looking at a code can ensure better maintainability of the code.

The convention defines that primitive types always begin with a lowercase letter giving a message to developers that this is a primitive data type that you are dealing with.

Wrapper Classes

To make life easy for developers, we also have wrapper classes in java. Wrapper classes have a set of additional functions available which give us added capability on top of the base data type.

The eight classes of the java.lang package are known as wrapper classes in Java.

  • Boolean

  • Character

  • Byte

  • Short

  • Integer

  • Long

  • Float

  • Double

So this is the same set of variables or data types that we saw as primitive which are also defined as custom wrapper classes in java with added functionality.

The types of data types can be explained with the help of the following image:

How to set up and execute a Java Program

First, let us set up our Eclipse IDE. Eclipse is an open source IDE that you can download. An IDE is an Integrated Development Environment. It's an editor that we use to create a java program.

Once we download it, we set up our Java environment.

To set up the Java environment variables:

  • Right-click My Computer

  • Select Properties > Advanced system settings > Environmental Variables

  • Under User Variables, click New. A popup window will appear.

  • In the popup window, define the variable name and its value. Value is the complete path to where you have saved your JDK. For example:

C:\Program Files\Java\jdk1.8.0_16\bin;.; path

  • Test the variable by opening the command prompt window and type “javac” to launch the compiler with the command.

The command prompt window should show the list of things supported by Java.

  • Restart your machine.

  • Start Eclipse and do the following:

  • Update the Installed JREs

  • Install the Maven Eclipse Plugin

  • Configure the Maven Plugin

  • Set up a DOS Shell in Eclipse

Setting up Java and executing Java Program

To set up JDK on a Windows machine:

  • Download and install JDK and JRE by running the downloaded installer.

  • Include JDK’s “bin” Directory in the PATH.

  • Verify the JDK Installation.

  • Write a “Hello-World Java” Program as shown below:

class Hello

{

public static void main(String[] args){

System.out.println(“Hello World !!!”);

}

}

C:\javac Hello.java (compilation creates Hello.class )

C:\java Hello (Execution on the local JVM)

  • Compile and Run the Hello World Java Program.

Benefits of Java Tutorial to Professionals

Being the most popular programming language, Java is widely used to develop web and mobile applications. There is rising demand for skilled Java developers. Hence this tutorial is ideally suited for:

  • Students and professionals who wish to become Java developers

  • Software developers

  • Web designers

  • Programming enthusiasts

  • Engineering graduates

Let us focus on the prerequisites for Java in the next section.

Prerequisites for Java Tutorial

There are no prerequisites for studying this Java Tutorial. Even with no previous coding experience, a keen interest in programming is just what is required for this tutorial.

In the next section, let us look at the objectives of this Java tutorial.

What are you waiting for? Willing to take up a course in Java? Check out our Course Preview here!

Lessons covered in the Java Tutorial

This Java Tutorial is aimed to give you a full understanding of the Java concepts right from beginning to advanced level. The complete tutorial is divided into 11 chapters and the topics discussed in each chapter are listed in the table below:

Lesson No

Chapter Name

What You’ll Learn

Lesson 1

Introduction to Java EE

This chapter covers the following topics:

  • Introduction to Java Enterprise Edition with various job additions

  • Distributed applications

  • Clients of a model and important terms related to it

Lesson 2

Java Servlet I

This chapter covers the following topics:

  • Servlets API, Interfaces, and Methods

  • Servlet Lifecycle

  • Configure and Deploy Servlet

  • ServletRequest, ServletResponse

  • ServletConfig, ServletContext

  • Servlet Scopes, Attributes, and Collaboration

Lesson 3

Java Servlet II

This chapter covers the following topics:

  • Session Management

  • Listeners in Java EE

  • Filters in Java EE

Lesson 4

Java Server Pages

This chapter covers the following topics:

  • JSP Architecture and Lifecycle

  • Creating and Working With JSP Elements

  • Working With JSP Standard Action

  • JSTL and Custom Tag Libraries

Lesson 5

Introduction to Hibernate

This chapter covers the following topics:

  • Introduction to Hibernate

  • Hibernate CRUD operation

Lesson 6

Hibernate Queries and Relationship

This chapter covers the following topics:

  • Hibernate queries and relationships

  • Mapping relationship with Hibernate

Lesson 7

Introduction to Spring

This chapter covers the following topics:

  • Introduction to Spring and its architecture

  • Inversion of control

  • Dependency Injection, SpringBean Lifecycle, Wiring, and Scope

Lesson 8

Spring AOP

This chapter covers the following topics:

  • Introduction to Spring AOP (Aspect-Oriented Programming)

  • Configuring AOP in Java Application using AspectJ Approach

Lesson 9

Spring JDBC and Spring Hibernate

This chapter covers the following topics:

  • Spring JDBC Implementation in an Application

  • Spring Hibernate Template

  • Spring JDBC Transaction Management

Lesson 10

Spring MVC

This chapter covers the following topics:

  • Spring MVC Architecture, Components, and Framework

  • Spring MVC Program

Lesson 11

SOA and Web Services

This chapter covers the following topics:

  • Basics of SOA Architecture and Web Services

  • Creating SOAP-based and RESTful Web Services

Summary

Look at the key takeaways of this lesson.

  • Java is both a programming language and computing platform for developing application software that can run on any device.

  • Java is platform independent—Write Once and Run Anywhere (WORA).

  • Java programming can be used to develop standalone, web, enterprise, and mobile applications.

  • Java is an Object-Oriented Programming language.

  • Classes and objects, methods, and variables are some of the core elements of Java.

  • JVM, JRE, and JDK are components of Java.

  • Primitive data types are basic data types in Java language.

  • Wrapper class in Java provides the mechanism to convert primitive into object and object into primitive.

Conclusion

With this, we have come to an end of this introductory lesson on Java tutorial. The next lesson focuses on Introduction to Java EE.

Find our Java Certification Training Online Classroom training classes in top cities:


Name Date Place
Java Certification Training 6 Oct -17 Nov 2018, Weekend batch Your City View Details
  • Disclaimer
  • PMP, PMI, PMBOK, CAPM, PgMP, PfMP, ACP, PBA, RMP, SP, and OPM3 are registered marks of the Project Management Institute, Inc.

Request more information

For individuals
For business
Name*
Email*
Phone Number*
Your Message (Optional)
We are looking into your query.
Our consultants will get in touch with you soon.

A Simplilearn representative will get back to you in one business day.

First Name*
Last Name*
Email*
Phone Number*
Company*
Job Title*