X-51nBc ZqYiRfoi6b EU-yLfUnMoDvnKMsAlF77FxQhGeTJiPb2nA
X-51nBc ZqYiRfoi6b EU-yLfUnMoDvnKMsAlF77FxQhGeTJiPb2nA
Why Java?
Java is a programming language and a platform. Java is a high level, robust, object-
oriented and secure programming language.
Java was developed by Sun Microsystems (which is now the subsidiary of Oracle) in
the year 1995. James Gosling is known as the father of Java. Before Java, its name
was Oak. Since Oak was already a registered company, so James Gosling and his team
changed the name from Oak to Java.
Platform: Any hardware or software environment in which a program runs, is known
as a platform. Since Java has a runtime environment (JRE) and API, it is called a
platform.
Application
According to Sun, 3 billion devices run Java. There are many devices where Java is
currently used. Some of them are as follows:
Desktop Applications such as acrobat reader, media player, antivirus, etc.
Web Applications such as irctc.co.in, javatpoint.com, etc.
Enterprise Applications such as banking applications.
1. Mobile
2. Embedded System
3. Smart Card
4. Robotics
5. Games, etc.
Types of Java Applications
There are mainly 4 types of applications that can be created using Java programming:
1) Destop Application
Standalone applications are also known as desktop applications or window-based
applications. These are traditional software that we need to install on every machine.
Examples of standalone application are Media player, antivirus, etc. AWT and Swing
are used in Java for creating standalone applications.
2) Web Application
An application that runs on the server side and creates a dynamic page is called a web
application. Currently, Servlet, JSP, Struts, Spring, Hibernate, JSF, etc. technologies
are used for creating web applications in Java.
3) Enterprise Application
An application that is distributed in nature, such as banking applications, etc. is called
an enterprise application. It has advantages like high-level security, load balancing,
and clustering. In Java, EJB is used for creating enterprise applications.
4) Mobile Application
An application which is created for mobile devices is called a mobile application.
Currently, Android and Java ME are used for creating mobile applications.
Flavors of Java:
1. J2SE(Java Platform, Standard Edition)
Also known as Core Java, this is the most basic and standard version of Java.It’s the
purest form of Java, a basic foundation for all other editions.
It consists of a wide variety of general purpose API’s (like java.lang, java.util) as well
as many special purpose APIs
J2SE is mainly used to create applications for Desktop environment.
It consist all the basics of Java the language, variables, primitive data types, Arrays,
Streams, Strings Java Database Connectivity(JDBC) and much more. This is the
standard, from which all other editions came out, according to the needs of the time.
The famous JVM of Java, the heart of Java development, was also given by this
edition only.It’s because of this feature, that Java has such a wide usage.
2. J2ME(Java Platform, Micro Edition)
This version of Java is mainly concentrated for the applications running on embedded
systems, mobiles and small devices.(which was a constraint before it’s development)
Portability and security was its main features.
JavaFX is another such edition of Java technology, which is now merged with J2SE
8.It is mainly used, to create rich GUI (Graphical User Interface) in Java apps.
It replaces Swings (in J2SE), with itself as the standard GUI library.
It is supported by both Desktop environment as well as web browsers.
PersonalJava was another edition, which was not deployed much, as its function was
fulfilled by further versions of J2ME. Made to support World Wide Web (and Java
applets) and consumer electronics.
PersonalJava was also used for embedded systems and mobile. But, it was
discontinued in its earlier stages.
Constraints included limited processing power, battery limitation, small display etc.
Also, the J2ME apps help in using web compression technologies, which in turn,
reduce network usage, and hence cheap internet accessibility.
J2ME uses many libraries and API’s of J2SE, as well as, many of it’s own.
The basic aim of this edition was to work on mobiles, wireless devices, set top boxes
etc.
Old Nokia phones, which used Symbian OS, used this technology.
Most of the apps, developed for the phones(prior to smartphones era), were built on
J2ME platform only(the .jar apps on Nokia app store).
J2EE(Java Platform, Enterprise Edition)
The Enterprise version of Java has a much larger usage of Java, like development of
web services, networking, server side scripting and other various web based
applications.
J2EE is a community driven edition, i.e. there is a lot of continuous contributions from
industry experts, Java developers and other open source organizations.
J2EE uses many components of J2SE, as well as, has many new features of it’s own
like Servlets, JavaBeans, Java Message Services, adding a whole new functionalities
to the language.
J2EE uses HTML, CSS, JavaScript etc., so as to create web pages and web services.
It’s also one of the most widely accepted web development standard.
There are also many languages like .net and php, which can do that work, but what
distinguishes it from other languages is the versatility, compatibility and security
features, which are not that much prominent in other languages.
Nowadays, developers are going more towards this edition, as it more versatile and
web friendly that it’s other counterparts.
Apart from these three versions, there was another Java version, released Java Card.
This edition was targeted, to run applets smoothly and securely on smart cards and
similar technology.
Features of Java Language
The prime reason behind creation of Java was to bring portability and security feature
into a computer language. Beside these two major features, there were many other
features that played an important role in moulding out the final form of this
outstanding language. Those features are :
1) Simple
Java is easy to learn and its syntax is quite simple, clean and easy to understand.The
confusing and ambiguous concepts of C++ are either left out in Java or they have been
re-implemented in a cleaner way.
Eg : Pointers and Operator Overloading are not there in java but were an important
part of C++.
2) Object Oriented
In java, everything is an object which has some data and behaviour. Java can be easily
extended as it is based on Object Model. Following are some basic concept of OOP's.
Object
Class
Inheritance
Polymorphism
Abstraction
Encapsulation
3) Robust
Java makes an effort to eliminate error prone codes by emphasizing mainly on
compile time error checking and runtime checking. But the main areas which Java
improved were Memory Management and mishandled Exceptions by introducing
automatic Garbage Collector and Exception Handling.
4) Platform Independent
Unlike other programming languages such as C, C++ etc which are compiled into
platform specific machines. Java is guaranteed to be write-once, run-anywhere
language.
On compilation Java program is compiled into bytecode. This bytecode is platform
independent and can be run on any machine, plus this bytecode format also provide
security. Any machine with Java Runtime Environment can run Java Programs.
5) Secure
When it comes to security, Java is always the first choice. With java secure features it
enable us to develop virus free, temper free system. Java program always runs in Java
runtime environment with almost null interaction with system OS, hence it is more
secure.
6) Multi Threading
Java multithreading feature makes it possible to write program that can do many tasks
simultaneously. Benefit of multithreading is that it utilizes same memory and other
resources to execute multiple threads at the same time, like While typing, grammatical
errors are checked along.
7) Architectural Neutral
Compiler generates bytecodes, which have nothing to do with a particular computer
architecture, hence a Java program is easy to intrepret on any machine.
8) Portable
Java Byte code can be carried to any platform. No implementation dependent features.
Everything related to storage is predefined, example: size of primitive data types
9) High Performance
Java is an interpreted language, so it will never be as fast as a compiled language like
C or C++. But, Java enables high performance with the use of just-in-time compiler.
10) Distributed
Java is also a distributed language. Programs can be designed to run on computer
networks. Java has a special class library for communicating using TCP/IP protocols.
Creating network connections is very much easy in Java as compared to C/C++.
JVM–The heart of Java
Java virtual Machine(JVM) is a virtual Machine that provides runtime environment to
execute java byte code. The JVM doesn't understand Java typo, that's why you
compile your *.java files to obtain *.class files that contain the bytecodes
understandable by the JVM.
JVM control execution of every Java program. It enables features such as automated
exception handling, Garbage-collected heap.
JVM Architecture
JDK : The JDK also called Java Development Kit is a superset of the JRE, and
contains everything that is in the JRE, plus tools such as the compilers and debuggers
necessary for developing applets and applications.
Java’s Magic Byte code
Byte Code can be defined as an intermediate code generated by the compiler after the
compilation of source code(JAVA Program). This intermediate code makes Java a
platform-independent language.
How is Byte Code generated?
Compiler converts the source code or the Java program into the Byte Code(or machine
code), and secondly, the Interpreter executes the byte code on the system. The
Interpreter can also be called JVM(Java Virtual Machine). The byte code is the
common piece between the compiler(which creates it) and the Interpreter (which runs
it).
class demo {
public static void main (String[] args) {
System.out.println("Hello");
}
}
The above-written code is called JAVA source code.
The compiler compiles the source code.
Finally, Interpreter executes the compiled source code.
Whenever we write any program, it is not written in machine code. We write it in a
high-level language like JAVA, C++, Python, etc. But the computer understands only
the machine code. So when we execute our program, it is first converted into machine
code or Byte code by the compiler and then executed by the Interpreter.
Installing Java:
Step 1: Verify that it is already installed or not
Check whether Java is already installed on the system or not. In my case, it is not
installed therefore I need to install JDK 1.8 on my computer.
There are available releases for Linux and mac operating systems. You can visit the
official link for JDK distributions.
Step 3: Install JDK
Open the executable file which you have just downloaded and follow the steps.
Click Next to continue.
We have successfully installed Java SE development kit 8. Close the installation set
up.
Object Oriented Programming Class Fundamentals
Class:-
1. Class is a set of object which shares common characteristics/ behavior and common
properties/ attributes.
2. Class is not a real world entity. It is just a template or blueprint or prototype from
which objects are created.
3. Class does not occupy memory.
4. Class is a group of variables of different data types and group of methods.
Constructor:
Java constructors or constructors in Java is a terminology used to construct something
in our programs. A constructor in Java is a special method that is used to initialize
objects. The constructor is called when an object of a class is created. It can be used to
set initial values for object attributes.
In Java, a constructor is a block of codes similar to the method. It is called when an
instance of the class is created. At the time of calling the constructor, memory for the
object is allocated in the memory. It is a special type of method which is used to
initialize the object. Every time an object is created using the new() keyword, at least
one constructor is called.
How Constructors are Different From Methods in Java?
Constructors must have the same name as the class within which it is defined it
is not necessary for the method in Java.
Constructors do not return any type while method(s) have the return type
or void if does not return any value.
Constructors are called only once at the time of Object creation while method(s)
can be called any number of times.
Now let us come up with the syntax for the constructor being invoked at the time of
object or instance creation.
class fruit
{
.......
// A Constructor
fruit() {
}
.......
}
// We can create an object of the above class
// using the below statement. This statement
// calls above constructor.
fruit obj = new fruit();
The first line of a constructor is a call to super() or this(), (a call to a constructor of a
super-class or an overloaded constructor), if you don’t type in the call to super in your
constructor the compiler will provide you with a non-argument call to super at the first
line of your code, the super constructor must be called to create an object:
class Fruit {
Fruit() {
}
public static void main(String[] args)
{
Fruit f1 = new Fruit();
}
}
When Constructor is called?
Each time an object is created using a new() keyword, at least one constructor (it
could be the default constructor) is invoked to assign initial values to the data
members of the same class.
Rules for writing constructors are as follows:
The constructor(s) of a class must have the same name as the class name in
which it resides.
A constructor in Java cannot be abstract, final, static, or Synchronized.
Access modifiers can be used in constructor declaration to control its access i.e
which other class can call the constructor.
So by far, we have learned constructors are used to initialize the object’s state.
Like methods, a constructor also contains a collection of statements(i.e. instructions)
that are executed at the time of Object creation.
Types of Constructors in Java
Now is the correct time to discuss the types of the constructor, so primarily there are
two types of constructors in java:
1. No-argument constructor
2. Parameterized Constructor
1. No-argument constructor
A constructor that has no parameter is known as the No-argument or Zero argument
constructor. If we don’t define a constructor in a class, then the compiler creates
a constructor(with no arguments) for the class. And if we write a constructor with
arguments or no arguments then the compiler does not create a default constructor.
// Java Program to illustrate calling a
// no-argument constructor
class Fruit {
int num;
String name;
// this would be invoked while an object
// of that class is created.
Fruit() { System.out.println("Constructor called"); }
}
class Demo {
public static void main(String[] args)
{
// this would invoke default constructor.
Fruit f1 = new Fruit();
// Default constructor provides the default
// values to the object like 0, null
System.out.println(f1.name);
System.out.println(f1.num);
}
}
Output:
Constructor called
null
0
2. Parameterized Constructor
A constructor that has parameters is known as parameterized constructor. If we want
to initialize fields of the class with our own values, then use a parameterized
constructor.
Example:
class student {
// data members of the class.
String name;
int id;
student(String name, int id)
{
this.name = name;
this.id = id;
}
}
class Demo1 {
public static void main(String[] args)
{
// This would invoke the parameterized constructor.
student s1 = new student("avinash", 68);
System.out.println("Student Name :" + s1.name + " and Student Id :" + s1.id);
}
}
Output:
Student Name :avinash and Student Id :68
JustLike methods, we can overload constructors for creating objects in different ways.
The compiler differentiates constructors on the basis of the number of parameters,
types of parameters, and order of the parameters.
Example:
// Java Program to illustrate constructor overloading
// using same task (addition operation ) for different
// types of arguments.
import java.io.*;
class student {
// constructor with one argument
student(String name)
{
System.out.println("Constructor with one " + "argument - String : " + name);
}
Access Modifiers
What are Access Modifiers?
In Java, access modifiers are used to set the accessibility (visibility) of classes,
interfaces, variables, methods, constructors, data members, and the setter methods.
For example,
class Animal {
public void method1() {...}
In the above example, we have declared 2 methods: method1() and method2(). Here,
method1 is public - This means it can be accessed by other classes.
method2 is private - This means it can not be accessed by other classes.
Types of Access Modifier
There are four access modifiers keywords in Java and they are:
Default Access Modifier
If we do not explicitly specify any access modifier for classes, methods, variables, etc, then by default
the default access modifier is considered. For example,
package defaultPackage;
class Logger {
void message(){
System.out.println("This is a message");
Here, the Logger class has the default access modifier. And the class is visible to all
the classes that belong to the defaultPackage package. However, if we try to use
the Logger class in another class outside of defaultPackage, we will get a compilation
error.
Private Access Modifier
When variables and methods are declared private, they cannot be accessed outside of
the class. For example,
class Data {
// private variable
private String name;
}
public class Main {
public static void main(String[] main){
// create an object of Data
Data d = new Data();
// access private variable and field from another class
d.name = "Hello World";
}
}
Output:
In the above example, we have declared a private variable named name. When we run
the program, we will get the following error:
Main.java:18: error:
name has
The error is generated because we are trying to access the private variable of
the Data class from the Main class.
You might be wondering what if we need to access those private variables. In this case,
we can use the getters and setters method.
For example,
class Data {
private String name;
// getter method
public String getName() {
return this.name;
}
// setter method
public void setName(String name) {
this.name= name;
}
}
public class Main {
public static void main(String[] main){
Data d = new Data();
// access the private variable using the getter and setter
d.setName("James Gosling");
System.out.println(d.getName());
}
}
Output:
The name is James Gosling
In the above example, we have a private variable named name. In order to access the
variable from the outer class, we have used methods: getName() and setName(). These
methods are called getter and setter in Java.
Here, we have used the setter method (setName()) to assign value to the variable and
the getter method (getName()) to access the variable.
We have used this keyword inside the setName() to refer to the variable of the class.
Protected Access Modifier
When methods and data members are declared protected, we can access them within
the same package as well as from subclasses. For example,
class Animal {
// protected method
protected void display() {
System.out.println("I am an animal");
}
}
class Dog extends Animal {
public static void main(String[] args) {
// create an object of Dog class
Dog dog = new Dog();
// access protected method
dog.display();
}
}
Output:
I am an animal
In the above example, we have a protected method named display() inside
the Animal class. The Animal class is inherited by the Dog class. To learn more about
inheritance, visit Java Inheritance.
We then created an object dog of the Dog class. Using the object we tried to access the
protected method of the parent class.
Since protected methods can be accessed from the child classes, we are able to access
the method of Animal class from the Dog class.
Output:
I am an animal.
I have 4 legs.
Here,
The public class Animal is accessed from the Main class.
The public variable legCount is accessed from the Main class.
The public method display() is accessed from the Main class.
Access Modifiers Summarized in one figure
Interface
An Interface in Java programming language is defined as an abstract type used to
specify the behavior of a class. An interface in Java is a blueprint of a behaviour. A
Java interface contains static constants and abstract methods.
Interfaces specify what a class must do and not how. It is the blueprint of the
behaviour.
Interface do not have constructor.
Represent behaviour as interface unless every sub-type of the class is guarantee
to have that behaviour.
An Interface is about capabilities like a Player may be an interface and any
class implementing Player must be able to (or must implement) move(). So it
specifies a set of methods that the class has to implement.
If a class implements an interface and does not provide method bodies for all
functions specified in the interface, then the class must be declared abstract.
A Java library example is Comparator Interface. If a class implements this
interface, then it can be used to sort a collection.
Syntax:
interface {
// declare constant fields
// declare methods that abstract
// by default.
}
To declare an interface, use the interface keyword. It is used to provide total
abstraction. That means all the methods in an interface are declared with an empty
body and are public and all fields are public, static, and final by default. A class that
implements an interface must implement all the methods declared in the interface. To
implement interface use implements keyword.
Why do we use an Interface?
It is used to achieve total abstraction.
Since java does not support multiple inheritances in the case of class, by using
an interface it can achieve multiple inheritances.
Any class can extend only 1 class but can any class implement infinite number
of interface.
It is also used to achieve loose coupling.
Interfaces are used to implement abstraction. So the question arises why use
interfaces when we have abstract classes?
The reason is, abstract classes may contain non-final variables, whereas variables in
the interface are final, public and static.
interface Language {
public void getType();
public void getVersion();
}
Here,
Language is an interface.
It includes abstract methods: getType() and getVersion().
Implementing an Interface
Like abstract classes, we cannot create objects of interfaces.
To use an interface, other classes must implement it. We use the implements keyword
to implement an interface.
interface Polygon {
void getArea(int length, int breadth);
}
// implement the Polygon interface
class Rectangle implements Polygon {
// implementation of abstract method
public void getArea(int length, int breadth) {
System.out.println("The area of the rectangle is " + (length * breadth));
}
}
class Main {
public static void main(String[] args) {
Rectangle r1 = new Rectangle();
r1.getArea(5, 6);
}
}
Output:
The area of the rectangle is 30
In the above example, we have created an interface named Polygon. The interface
contains an abstract method getArea().
Here, the Rectangle class implements Polygon. And, provides the implementation of
the getArea() method.
Implementing Multiple Interfaces
In Java, a class can also implement multiple interfaces. For example,
interface A {
// members of A
}
interface B {
// members of B
}
class C implements A, B {
// abstract members of A
// abstract members of B
}
Extending an Interface
Similar to classes, interfaces can extend other interfaces. The extends keyword is used
for extending interfaces. For example,
interface Line {
// members of Line interface
}
// extending interface
interface Polygon extends Line {
// members of Polygon interface
// members of Line interface
}
Here, the Polygon interface extends the Line interface. Now, if any class
implements Polygon, it should provide implementations for all the abstract methods of
both Line and Polygon.
Extending Multiple Interfaces
An interface can extend multiple interfaces. For example,
interface A {
...
}
interface B {
...
}
interface C extends A, B {
...
}
default methods in Java Interfaces
With the release of Java 8, we can now add methods with implementation inside an
interface. These methods are called default methods.
To declare default methods inside interfaces, we use the default keyword.
Why default methods?
Let's take a scenario to understand why default methods are introduced in Java.
Suppose, we need to add a new method in an interface.
We can add the method in our interface easily without implementation. However,
that's not the end of the story. All our classes that implement that interface must
provide an implementation for the method.
If a large number of classes were implementing this interface, we need to track all
these classes and make changes to them. This is not only tedious but error-prone as
well.
To resolve this, Java introduced default methods. Default methods are inherited like
ordinary methods.
Let's take an example to have a better understanding of default methods.
Example: Default Method in Java Interface
interface Polygon {
void getArea();
// default method
default void getSides() {
System.out.println("I can get sides of a polygon.");
}
}
// implements the interface
class Rectangle implements Polygon {
public void getArea() {
int length = 6;
int breadth = 5;
int area = length * breadth;
System.out.println("The area of the rectangle is " + area);
}
// overrides the getSides()
public void getSides() {
System.out.println("I have 4 sides.");
}
}
// implements the interface
class Square implements Polygon {
public void getArea() {
int length = 5;
int area = length * length;
System.out.println("The area of the square is " + area);
}
}
class Main {
public static void main(String[] args) {
// create an object of Rectangle
Rectangle r1 = new Rectangle();
r1.getArea();
r1.getSides();
// create an object of Square
Square s1 = new Square();
s1.getArea();
s1.getSides();
}
}
Output
The area of the rectangle is 30
I have 4 sides.
The area of the square is 25
I can get sides of a polygon.
In the above example, we have created an interface named Polygon. It has a default
method getSides() and an abstract method getArea().
Here, we have created two classes Rectangle and Square that implement Polygon.
The Rectangle class provides the implementation of the getArea() method and
overrides the getSides() method. However, the Square class only provides the
implementation of the getArea() method.
Now, while calling the getSides() method using the Rectangle object, the overridden
method is called. However, in the case of the Square object, the default method is
called.
Call by reference:
In case of call by reference original value is changed if we made changes in the called
method.
If we pass object in place of any primitive value, original value will be changed.
In this example we are passing object as a value.
class Operation2
{
int data=50;
void change(Operation2 op)
{
op.data=op.data+100;//changes will be in the instance variable
}
public static void main(String args[])
{
Operation2 op=new Operation2();
System.out.println("before change "+op.data);
op.change(op);//passing object
System.out.println("after change "+op.data);
}
}
Method Overloading in Java:
If a class has multiple methods having same name but different in parameters, it is
known as Method Overloading.
If we have to perform only one operation, having same name of the methods increases
the readability of the program.
There are two ways to overload the method in java:
By changing number of arguments
By changing the data type
Recursion:
The process in which a function calls itself directly or indirectly is called recursion
and the corresponding function is called as recursive function.
public class Test
{
// Factorial function
static int f(int n)
{
// Stop condition
if (n == 0 || n == 1)
return 1;
// Recursive condition
else
return n * f(n - 1);
}
// Driver code
public static void main(String[] args)
{
int n = 5;
System.out.println("factorial of " + n + " is: " + f(n));
}
}
Dealing with Static Members:
In Java, static members are those which belongs to the class and you can access these
members without instantiating the class.
The static keyword can be used with methods, fields, classes (inner/nested), blocks.
Static Methods − You can create a static method by using the keyword static.
Static methods can access only static fields, methods.
To access static methods there is no need to instantiate the class, you can do it just
using the class name as −
public class MyClass {
public static void sample(){
System.out.println("Hello");
}
public static void main(String args[])
{
MyClass.sample();
}
}
Static Fields:
You can create a static field by using the keyword static.
The static fields have the same value in all the instances of the class.
These are created and initialized when the class is loaded for the first time. Just like
static methods you can access static fields using the class name (without instantiation).
public class MyClass {
public static int data = 20;
public static void main(String args[]){
System.out.println(MyClass.data);
}
}
Static Blocks:
These are a block of codes with a static keyword. In general, these are used to
initialize the static members.
JVM executes static blocks before the main method at the time of class loading.
public class MyClass {
static{
System.out.println("Hello this is a static block");
}
public static void main(String args[]){
System.out.println("This is main method");
}
}
Object’s Memory:
An object is created in the memory using new operator. Constructor is used to
initialize the properties of that object.
When an object is no more required, it must be removed from the memory so that
memory can be reused for another objects.
Garbage collection:
Removing unwanted objects or abandoned objects from the memory is called garbage
collection.
In the languages like C,C++, GC is performed manually using destructors
In java, there is no destructors.
There exists better mechanism to handle the garbage collection.
JVM implicitly sweeps out abandoned objects from the memory.
Finalize Method():
Finalize is a method, which is available in object super class.
The purpose of finalize method is to release the resources that is allocated by unused
object, before removing unused object by garbage collector.
Ex: class object
{
Protected finalize()
{
Empty}}
Finalize() method is a protectd and non static method of java.lang.object class.