0% found this document useful (0 votes)
252 views64 pages

Advance OOP - 021814

This document provides an overview of Java concepts including its history and applications. It discusses key Java terminology like JVM, JRE, and JDK. It also covers core OOP concepts like objects, classes, inheritance, polymorphism, abstraction and encapsulation. Additionally, it details how to define classes and objects in Java including attributes, methods, constructors, access modifiers, overloading and interfaces.

Uploaded by

Danish Khan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
252 views64 pages

Advance OOP - 021814

This document provides an overview of Java concepts including its history and applications. It discusses key Java terminology like JVM, JRE, and JDK. It also covers core OOP concepts like objects, classes, inheritance, polymorphism, abstraction and encapsulation. Additionally, it details how to define classes and objects in Java including attributes, methods, constructors, access modifiers, overloading and interfaces.

Uploaded by

Danish Khan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 64

Contents

Introduction To Java ................................................................................................................................... 4


History ..................................................................................................................................................... 5
Applications of Java ................................................................................................................................... 5
Features of Java ................................................................................................................................... 5
Robust: ............................................................................................................................................... 6
The Terminologies in Java ................................................................................................................. 7
What is JVM?......................................................................................................................................... 8
What is JRE? ......................................................................................................................................... 8
What is JDK? ......................................................................................................................................... 9
Java vs C++ .................................................................................................................................................... 9
Java - OOPs (Object-Oriented Programming) Concepts ......................................................................... 11
OOPs (Object-Oriented Programming System) ............................................................................. 12
Java OOPs (Object-Oriented Programming) Concepts ................................................................. 12
1. Object ........................................................................................................................................ 13
2. Class ........................................................................................................................................... 13
3. Inheritance ............................................................................................................................. 13
4. Polymorphism ....................................................................................................................... 13
5. Abstraction ............................................................................................................................. 14
6. Encapsulation........................................................................................................................ 14
Java - Object and Classes ........................................................................................................................... 14
Java Classes ........................................................................................................................................... 15
Properties of Java Classes .................................................................................................. 15
Types of Java Class Variables ........................................................................................... 15
Creating (Declaring) a Java Class .................................................................................. 16
Syntax to create a Java class ............................................................................................ 16
Example of a Java Class ....................................................................................................... 16
Java Objects .......................................................................................................................................... 17
Creating (Declaring) a Java Object ............................................................................... 18
Syntax to Create a Java Object ........................................................................................ 18
Example to Create a Java Object .................................................................................... 18
Accessing Instance Variables and Methods .................................................................................... 20

1
Java Data Types .................................................................................................................................... 20
Types of Data Types in Java ............................................................................................................... 20
1. Java Primitive Data Types.............................................................................................................. 21
2. Java Reference/Object Data Type ................................................................................................ 21
Example ......................................................................................................................................... 21
Java Class Attributes ........................................................................................................................... 22
Creating (Declaring) Java Class Attributes ..................................................................................... 22
Syntax ............................................................................................................................................. 22
Example: Declaring Java Class Attributes ................................................................. 22
Java Class Methods .............................................................................................................................. 23
Creating (Declaring) Java Class Methods ........................................................................................ 23
Syntax ............................................................................................................................................. 23
Example ......................................................................................................................................... 24
this Keyword in Java Class Methods ................................................................................................ 24
Public Vs. Static Class Methods ......................................................................................................... 25
Example ......................................................................................................................................... 25
The finalize( ) Method ........................................................................................................................ 26
Java Methods ........................................................................................................................................ 27
Creating a Java Method....................................................................................................................... 27
Syntax to Create a Java Method ...................................................................................... 27
Example to Create a Java Method .................................................................................. 28
Calling a Java Method.......................................................................................................................... 28
Java Methods Overloading ................................................................................................................. 29
Example: Methods Overloading in Java ...................................................................... 29
Important Points About Variables Scope ........................................................................................ 31
Java Constructors ................................................................................................................................ 31
Rules for Creating Java Constructors ............................................................................................... 31
Creating a Java Constructor ............................................................................................................... 32
Syntax ............................................................................................................................................. 32
Example to create a Java Constructor ......................................................................... 32
Types of Java Constructors ................................................................................................................ 33
1. Default Constructor ........................................................................................................... 33
2. No-Args (No Argument) Constructor...................................................................... 34

2
3. Parameterized Constructor .......................................................................................... 35
Constructor Overloading in Java ...................................................................................................... 36
Example: Constructor Overloading................................................................................ 37
Java Interfaces...................................................................................................................................... 38
Java Interfaces and Classes: Similarities and Differences ........................................................... 39
Similarities ................................................................................................................................... 39
Differences ................................................................................................................................... 39
Declaring an Interface in Java ........................................................................................................... 40
Example to Declare a Java Interface ........................................................................... 40
Propeties of Java Interface................................................................................................................. 40
Example ......................................................................................................................................... 40
Implementing Interfaces in Java ...................................................................................................... 40
Example: Implement an Interface in Java ................................................................ 41
Difference between abstract class and interface................................................................................. 41
Java Packages ....................................................................................................................................... 43
Types of Java Packages ....................................................................................................................... 43
User-defined Java Packages............................................................................................................... 43
Creating a Java Package...................................................................................................................... 43
Compiling with Java Package ............................................................................................................ 44
Java Package Example ........................................................................................................................ 44
Java Abstraction................................................................................................................................... 46
Java Abstract Classes .......................................................................................................................... 46
What Is an Exception in Java? ........................................................................................................... 46
Why Exception Occurs? ...................................................................................................................... 46
The Throws/Throw Keywords.......................................................................................................... 47
Example ......................................................................................................................................... 47
Example ......................................................................................................................................... 47
The Finally Block ................................................................................................................................. 48
Syntax ............................................................................................................................................. 48
Example ......................................................................................................................................... 48
Java try and catch .............................................................................................................................. 49
The try Block ............................................................................................................................... 49
The catch Block .......................................................................................................................... 49

3
Syntax of Java try and catch Block ............................................................................... 50
Example of Java try and catch Block ............................................................................ 50
Java - Multithreading .............................................................................................................................. 50
Java Multithreading ............................................................................................................................ 51
Life Cycle of a Thread in Java Multithreading ................................................................................ 51
Java - Applet Basics.................................................................................................................................... 52
Life Cycle of an Applet in Java ....................................................................................................... 52
AWT ............................................................................................................................................................ 53
AWT Hierarchy .................................................................................................................................... 53
Introduction to Java Servlets .................................................................................................................. 54
What is CGI? .................................................................................................................................... 54
Difference between Servlet and CGI ......................................................................................... 55
if: ............................................................................................................................................................. 55
if-else: ................................................................................................................................................. 57
nested-if: .......................................................................................................................................... 58
if-else-if ladder: .................................................................................................................................. 59
switch-case: ........................................................................................................................................ 61
jump: ..................................................................................................................................................... 62
Break: .................................................................................................................................................... 62
Continue:.............................................................................................................................................. 63
Return: .................................................................................................................................................. 64

Introduction To Java
Java is an object-oriented, class-based programming language. The language is
designed to have as few dependencies implementations as possible. The intention of
using this language is to give relief to the developers from writing codes for every
platform. The term WORA, write once and run everywhere is often associated with this
language. It means whenever we compile a Java code, we get the byte code (.class
file), and that can be executed (without compiling it again) on different platforms
provided they support Java. In the year 1995, Java language was developed. It is
mainly used to develop web, desktop, and mobile devices. The Java language is known
for its robustness, security, and simplicity features. That is designed to have as few
implementation dependencies as possible.

4
History
The Java language has a very interesting history. Patrick Naughton, Mike Sheridan, and
Jame Gosling, known as the Green team, started the development of Java in the year
1991. These people were the engineers at Sun Microsystems. In 1996, the first public
implementation was released as Java 1.0. The compiler of Java 1.0 was rewritten by
Arthur Van Hoff to comply strictly with its specification. With the introduction of Java 2,
the new versions have multiple different configurations that have been built for the
various platforms. It is worth noting that James Gosling is also known as the father of
Java.

The ISO standard body was approached by Sun Microsystems in the year 1997 to
formalize Java, but the process was withdrawn soon. At one point in time, Sun
Microsystems provided most of its implementation of Java available without any cost,
despite having the status of proprietary software.

Applications of Java
Java has become the most robust programming language because of its amazing
features. Some of its features are platform independence, high performance,
Object orientation, support for automatic garbage management, and many more.
In this blog, we will discuss the Top 10 Applications of Java in the real world
in a detailed manner.
• Desktop GUI Applications
• Mobile Applications
• Artificial intelligence
• Web applications
• Big Data technology
• Gaming applications
• Business applications
• Embedded systems
• Cloud applications
• Scientific applications

Features of Java
Platform Independent: Instead of directly generating the .exe file, Java compiler converts
the Java code to byte code, and this byte code can be executed on different platforms
without any issue, which makes Java a platform-independent language. Note that in order
to execute the byte code, JVM has to be installed on the system, which is platform
dependent.

5
Object-Oriented Programming Language: The concept of object-oriented programing
is based on the concept of objects and classes. Also, there are several qualities that are
present in object-oriented programming. A few of them are mentioned below.

o Abstraction
o Inheritance
o Polymorphism
o Encapsulation

The Java language also extensively uses the concepts of classes and objects. Also, all these
features mentioned above are there in Java, which makes Java an object-oriented
programming language. Note that Java is an object-oriented programming language but
not 100% object-oriented.

Simple: Java is considered a simple language because it does not have the concept of
pointers, multiple inheritances, explicit memory allocation, or operator overloading.

Robust:
Java language is very much robust. The meaning of robust is reliable. The Java language
is developed in such a fashion that a lot of error checking is done as early as possible. It
is because of this reason that this language can identify those errors that are difficult to
identify in other programming languages. Exception Handling, garbage collections, and
memory allocation are the features that make Java robust.

Secure: There are several errors like buffer overflow or stack corruption that are not
possible to exploit in the Java language. We know that the Java language does not have
pointers. Therefore, it is not possible to have access to out-of-bound arrays. If someone
tries to do so, ArrayIndexOutofBound Exception is raised. Also, the execution of the Java
programs happens in an environment that is completely independent of the Operating
System, which makes this language even more secure.

Distributed: Distributed applications can be created with the help of the Java language.
Enterprise Java beans and Remote Method Invocation are used for creating distributed
applications. The distribution of Java programs can happen easily between one or more
systems that are connected to each other using the internet.

Multithreading: The Java language supports multithreading. The multithreading feature


supports the execution of two or more parts of the program concurrently. Thus, the
utilization of the CPU is maximized.

6
Portability: We know that Java is a platform-independent language. Thus, the byte code
generated on one system can be taken on any other platform for execution, which makes
Java portable.

High-Level Performance: The architecture of Java is created in such a fashion that it


decreases runtime overhead. In some places, Java uses JIT (Just In Time) compiler when
the code is compiled on a demand basis, where the compiler is only compiling those
methods that are invoked and thus making the faster execution of applications.

Dynamic Flexibility: The Java language follows the Object-Oriented programming


paradigm, which gives us the liberty to add new methods and classes to the existing
classes. The Java language also supports functions mentioned in C/C++ languages and
which are generally referred to as the native methods.

SandBox Execution: It is a known fact that Java programs are executed in different
environment, which gives liberty to users to execute their own applications without
impacting the underlying system using the bytecode verifier. The Bytecode verifier also
gives extra security as it checks the code for the violation of access.

Write Once Run Anywhere: The Java code is compiled by the compiler to get the .class
file or the byte code, which is completely independent of any machine architecture.

Compiled and Interpreted Language: Most of languages are either interpreted


language or the compiled language. However, in the case of the Java language, it is
compiled as well as the interpreted language. The Java code is compiled to get the
bytecode, and the bytecode is interpreted by the software-based interpreter.

The Terminologies in Java


JVM (Java Virtual Machine): JVM is the specification that facilitates the runtime
environment in which the execution of the Java bytecode takes place. Whenever one
uses the command java, an instance of the JVM is created. JVM facilitates the
definition of the memory area, register set, class file format, and fatal error reporting. Note
that the JVM is platform dependent.

Byte Code: It has already been discussed in the introductory part that the Java compiler
compiles the Java code to generate the .class file or the byte code. One has to use
the javac command to invoke the Java compiler.

Java Development Kit (JDK): It is the complete Java Development Kit that encompasses
everything, including JRE(Java Runtime Environment), compiler, java docs, debuggers, etc.

7
JDK must be installed on the computer for the creation, compilation, and execution of a
Java program.

Java Runtime Environment (JRE): JRE is part of the JDK. If a system has only JRE
installed, then the user can only run the program. In other words, only the java command
works. The compilation of a Java program will not be possible (the javac command will
not work).

Garbage Collector: Programmers are not able to delete objects in Java. In order to do so,
JVM has a program known as Garbage Collector. Garbage Collectors recollect or delete
unreferenced objects. Garbage Collector makes the life of a developer/ programmer easy
as they do not have to worry about memory management.

Classpath: As the name suggests, classpath is the path where the Java compiler and the Java
runtime search the .class file to load. Many inbuilt libraries are provided by the JDK. However, if
someone wants to use the external libraries, it should be added to the classpath.

What is JVM?
JVM (Java Virtual Machine) is an abstract machine that enables your computer to run a
Java program.

When you run the Java program, Java compiler first compiles your Java code to
bytecode. Then, the JVM translates bytecode into native machine code (set of
instructions that a computer's CPU executes directly).

Java is a platform-independent language. It's because when you write Java code, it's
ultimately written for JVM but not your physical machine (computer). Since JVM
executes the Java bytecode which is platform-independent, Java is platform-
independent.

Working of Java Program

What is JRE?
JRE (Java Runtime Environment) is a software package that provides Java class
libraries, Java Virtual Machine (JVM), and other components that are required to run
Java applications.

8
JRE is the superset of JVM.

What is JDK?
JDK (Java Development Kit) is a software development kit required to develop
applications in Java. When you download JDK, JRE is also downloaded with it.

In addition to JRE, JDK also contains a number of development tools (compilers,


JavaDoc, Java Debugger, etc).

Java vs C++
Comparison C++ Java
Index

9
Platform- C++ is platform-dependent. Java is platform-independent.
independent

Mainly used for C++ is mainly used for system Java is mainly used for application
programming. programming. It is widely used in
Windows-based, web-based, enterprise,
and mobile applications.

Design Goal C++ was designed for systems Java was designed and created as an
and applications interpreter for printing systems but later
programming. It was an extended as a support network
extension of the C computing. It was designed to be easy to
programming language. use and accessible to a broader
audience.

Multiple C++ supports multiple Java doesn't support multiple


inheritance inheritance. inheritance through class. It can be
achieved by using interfaces in java.

Operator C++ supports operator Java doesn't support operator


Overloading overloading. overloading.

Pointers C++ supports pointers. You can Java supports pointer internally.
write a pointer program in C++. However, you can't write the pointer
program in java. It means java has
restricted pointer support in java.

Compiler and C++ uses compiler only. C++ is Java uses both compiler and interpreter.
Interpreter compiled and run using the Java source code is converted into
compiler which converts bytecode at compilation time. The
source code into machine interpreter executes this bytecode at
code so, C++ is platform runtime and produces output. Java is
dependent. interpreted that is why it is platform-
independent.

10
Call by Value C++ supports both call by value Java supports call by value only. There is
and Call by and call by reference. no call by reference in java.
reference

Structure and C++ supports structures and Java doesn't support structures and
Union unions. unions.

Thread Support C++ doesn't have built-in Java has built-in thread support.
support for threads. It relies on
third-party libraries for thread
support.

Virtual C++ supports virtual keyword Java has no virtual keyword. We can
Keyword so that we can decide whether override all non-static methods by
or not to override a function. default. In other words, non-static
methods are virtual by default.

Inheritance C++ always creates a new Java always uses a single inheritance
Tree inheritance tree. tree because all classes are the child of
the Object class in Java. The Object class
is the root of the inheritance tree in java.

Hardware C++ is nearer to hardware. Java is not so interactive with hardware.

Object- C++ is an object-oriented Java is also an object-oriented language.


oriented language. However, in the C However, everything (except
language, a single root fundamental types) is an object in Java. It
hierarchy is not possible. is a single root hierarchy as everything
gets derived from java.lang.Object.

Java - OOPs (Object-Oriented


Programming) Concepts

11
OOPs (Object-Oriented Programming System)

Object means a real-world entity such as a mobile, book, table,


computer, watch, etc. Object-Oriented Programming is a
methodology or paradigm to design a program using classes and
objects. It simplifies software development and maintenance by
providing some concepts.

In this tutorial, we will learn about the concepts of Java (OOPs)


object-oriented programming systems.

Java OOPs (Object-Oriented Programming) Concepts


• Object
• Class
• Inheritance
• Polymorphism
• Abstraction
• Encapsulation

12
1. Object

In object-oriented programming, an object is an entity that has two


characteristics (states and behavior). Some of the real-world
objects are book, mobile, table, computer, etc. An object is
a variable of the type class, it is a basic component of an object-
oriented programming system. A class has the methods and data
members (attributes), these methods and data members are
accessed through an object. Thus, an object is an instance of a
class.

2. Class

In object-oriented programming, a class is a blueprint from which


individual objects are created (or, we can say a class is a data
type of an object type). In Java, everything is related to classes and
objects. Each class has its methods and attributes that can be
accessed and manipulated through the objects.

3. Inheritance

In object-oriented programming, inheritance is a process by which


we can reuse the functionalities of existing classes to new classes.
In the concept of inheritance, there are two terms base (parent)
class and derived (child) class. When a class is inherited from
another class (base class), it (derived class) obtains all the
properties and behaviors of the base class.

4. Polymorphism

The term "polymorphism" means "many forms". In object-oriented


programming, polymorphism is useful when you want to create
multiple forms with the same name of a single entity. To implement
polymorphism in Java, we use two concepts method
overloading and method overriding.

The method overloading is performed in the same class where we


have multiple methods with the same name but different
parameters, whereas, the method overriding is performed by using

13
the inheritance where we can have multiple methods with the same
name in parent and child classes.

5. Abstraction

In object-oriented programming, an abstraction is a technique of


hiding internal details and showing functionalities. The abstract
classes and interfaces are used to achieve abstraction in Java.

The real-world example of an abstraction is a Car, the internal


details such as the engine, process of starting a car, process of
shifting gears, etc. are hidden from the user, and features such as
the start button, gears, display, break, etc are given to the user.
When we perform any action on these features, the internal process
works.

6. Encapsulation

In an object-oriented approach, encapsulation is a process of


binding the data members (attributes) and methods together. The
encapsulation restricts direct access to important data. The best
example of the encapsulation concept is making a class where the
data members are private and methods are public to access through
an object. In this case, only methods can access those private data.

Java - Object and Classes


Java is an Object-Oriented programming language. In Java,
the classes and objects are the basic and important features of object-
oriented programming system, Java supports the following
fundamental OOPs concepts –

• Classes
• Objects
• Inheritance
• Polymorphism
• Encapsulation
• Abstraction
• Instance

14
• Method
• Message Passing

In this tutorial, we will learn about Java Classes and Objects, the
creation of the classes and objects, accessing class methods, etc.

Java Classes

A class is a blueprint from which individual objects are created (or,


we can say a class is a data type of an object type). In Java,
everything is related to classes and objects. Each class has
its methods and attributes that can be accessed and manipulated
through the objects.

For example, if you want to create a class for students. In that case,
"Student" will be a class, and student records
(like student1, student2, etc) will be objects.

We can also consider that class is a factory (user-defined blueprint)


to produce objects.

Properties of Java Classes


• A class does not take any byte of memory.
• A class is just like a real-world entity, but it is not a real-world
entity. It's a blueprint where we specify the functionalities.
• A class contains mainly two things: Methods and Data
Members.
• A class can also be a nested class.
• Classes follow all of the rules of OOPs such as inheritance,
encapsulation, abstraction, etc.
Types of Java Class Variables

A class can contain any of the following variable types.

• Local variables − Variables defined inside methods, constructors


or blocks are called local variables. The variable will be
declared and initialized within the method and the variable will
be destroyed when the method has completed.
• Instance variables − Instance variables are variables within a
class but outside any method. These variables are initialized
15
when the class is instantiated. Instance variables can be
accessed from inside any method, constructor or blocks of that
particular class.
• Class variables − Class variables are variables declared within a
class, outside any method, with the static keyword.
Creating (Declaring) a Java Class

To create (declare) a class, you need to use access


modifiers followed by class keyword and class_name.

Syntax to create a Java class

Use the below syntax to create (declare) class in Java:

access_modifier class class_name{


data members;
constructors;
methods;
...;
}
Example of a Java Class

In this example, we are creating a class "Dog". Where, the class


attributes are breed, age, and color. The class methods
are setBreed(), setAge(), setColor(), and printDetails().

// Creating a Java class


class Dog {
// Declaring and initializing the attributes
String breed;
int age;
String color;

// methods to set breed, age, and color of the dog


public void setBreed(String breed) {
this.breed = breed;
}

16
public void setAge(int age) {
this.age = age;
}
public void setColor(String color) {
this.color = color;
}

// method to print all three values


public void printDetails() {
System.out.println("Dog detials:");
System.out.println(this.breed);
System.out.println(this.age);
System.out.println(this.color);
}
}
Java Objects

An object is a variable of the type class, it is a basic component of an


object-oriented programming system. A class has the methods and
data members (attributes), these methods and data members are
accessed through an object. Thus, an object is an instance of a
class.

If we consider the real world, we can find many objects around us,
cars, dogs, humans, etc. All these objects have a state and a
behavior.

If we consider a dog, then its state is - name, breed, and color, and
the behavior is - barking, wagging the tail, and running.

If you compare the software object with a real-world object, they


have very similar characteristics. Software objects also have a state
and a behavior. A software object's state is stored in fields and
behavior is shown via methods. So, in software development,
methods operate on the internal state of an object, and the object-
to-object communication is done via methods.

17
Creating (Declaring) a Java Object

As mentioned previously, a class provides the blueprints for objects.


So basically, an object is created from a class. In Java,
the new keyword is used to create new objects.

There are three steps when creating an object from a class −

• Declaration − A variable declaration with a variable name with


an object type.
• Instantiation − The 'new' keyword is used to create the object.
• Initialization − The 'new' keyword is followed by a call to a
constructor. This call initializes the new object.
Syntax to Create a Java Object

Consider the below syntax to create an object of the class in Java:

Class_name object_name = new Class_name([parameters]);

Note: parameters are optional and can be used while you're


using constructors in the class.

Example to Create a Java Object

In this example, we are creating an object named obj of Dog class


and accessing its methods.

// Creating a Java class


class Dog {
// Declaring and initializing the attributes
String breed;
int age;
String color;

// methods to set breed, age, and color of the dog


public void setBreed(String breed) {
this.breed = breed;
}

18
public void setAge(int age) {
this.age = age;
}
public void setColor(String color) {
this.color = color;
}

// method to print all three values


public void printDetails() {
System.out.println("Dog detials:");
System.out.println(this.breed);
System.out.println(this.age);
System.out.println(this.color);
}
}

public class Main {


public static void main(String[] args) {
// Creating an object of the class Dog
Dog obj = new Dog();

// setting the attributes


obj.setBreed("Golden Retriever");
obj.setAge(2);
obj.setColor("Golden");

// Printing values
obj.printDetails();
}
}
Output
Dog detials:
Golden Retriever
2
Golden

19
Accessing Instance Variables and Methods

Instance variables and methods are accessed via created objects.


To access an instance variable, following is the fully qualified path −

/* First create an object */


ObjectReference = new Constructor();

/* Now call a variable as follows */


ObjectReference.variableName;

/* Now you can call a class method as follows */


ObjectReference.MethodName();

Java Data Types

Java data types are used to define the type of data for the
different types of variables, constants, method parameters, returns
type, etc. The variables are nothing but reserved memory locations
to store some values. This means that when you create a variable
you reserve some space in the memory to store some data. The
data type tells the compiler about the type of data to be stored and
the required memory.

Based on the data type of a variable, the operating system allocates


memory and decides what can be stored in the reserved memory.
Therefore, by assigning different data types to variables, you can
store integers, decimals, or characters in these variables.

Types of Data Types in Java

There are two data types available in Java −

• Primitive Data Types


• Reference/Object Data Types

20
1. Java Primitive Data Types

Primitive data types are predefined by the language and named by


a keyword. There are eight primitive data types supported by Java.
Below is the list of the primitive data types:

• byte
• short
• int
• long
• float
• double
• boolean
2. Java Reference/Object Data Type

The reference data types are created using defined constructors of


the classes. They are used to access objects. These variables are
declared to be of a specific type that cannot be changed. For
example, Employee, Puppy, etc.

Class objects and various types of array variables come under


reference datatype. The default value of any reference variable is
null. A reference variable can be used to refer to any object of the
declared type or any compatible type.

Example

The following example demonstrates the reference (or, object) data


types.

// Creating an object of 'Animal' class


Animal animal = new Animal("giraffe");

// Creating an object of 'String' class


String myString = new String("Hello, World!");

21
Java Class Attributes

Java class attributes are the variables that are bound in a class i.e.,
the variables which are used to define a class are class attributes.

A class attribute defines the state of the class during program


execution. A class attribute is accessible within class methods by
default.

For example, there is a class "Student" with some data members


(variables) like roll_no, age, and name. These data members are
considered class attributes.

Creating (Declaring) Java Class Attributes

To create (declare) a class attribute, use the access


modifier followed by the data type and attribute name. It's similar
to declaring a variable.

Syntax

Use the below syntax to declare a class attribute:

access_modifier type attribute_name;


Example: Declaring Java Class Attributes
public class Dog {
String breed;
int age;
String color;

void barking() {
}

void hungry() {
}

void sleeping() {
}

22
}

In above class, we've fields like breed, age, and color which are also
known as class attributes.

Java Class Methods

The class methods are methods that are declared within a class. They
perform specific operations and can access, modify the class
attributes.

Creating (Declaring) Java Class Methods

Class methods declaration is similar to the user-defined


methods declaration except that class methods are declared within
a class.

The class methods are declared by specifying the access


modifier followed by the return type, method_name,
and parameters list.

Syntax

Use the below syntax to declare a Java class method:

public class class_name {


modifier returnType nameOfMethod(Parameter List) {
// method body
}
}

The syntax shown above includes −

• modifier − It defines the access type of the method and it is


optional to use.
• returnType − The returns data type of the class method.
• nameOfMethod − This is the method name. The method
signature consists of the method name and the parameter list.

23
• Parameter List − The list of parameters, it is the type, order,
and number of parameters of a method. These are optional,
method may contain zero parameters.
• method body − The method body defines what the method does
with the statements.
Example

Here is the source code of the above defined method


called minimum(). This method takes two parameters n1 and n2 and
returns the minimum between the two −

class Util {
/** the snippet returns the minimum between two numbers */
public int minimum(int n1, int n2) {
int min;
if (n1 > n2)
min = n2;
else
min = n1;

return min;
}
}

this Keyword in Java Class Methods

this is a keyword in Java which is used as a reference to the object


of the current class, with in an instance method or a constructor.
Using this you can refer the members of a class such as
constructors, variables and methods.

Note − The keyword this is used only within instance methods or


constructors

In general, the keyword this is used to −

• Differentiate the instance variables from local variables if they


have same names, within a constructor or a method.

24
class Student {
int age;
Student(int age) {
this.age = age;
}
}
• Call one type of constructor (parametrized constructor or
default) from other in a class. It is known as explicit
constructor invocation.
class Student {
int age
Student() {
this(20);
}

Student(int age) {
this.age = age;
}
}

Public Vs. Static Class Methods

There are two types of class methods public and static class method.
The public class methods are accessed through the objects whereas,
the static class methods are accessed are accesses without an object.
You can directly access the static methods.

Example

The following example demonstrates the difference between public


and static class methods:

public class Main {


// Creating a static method
static void fun1() {
System.out.println("fun1: This is a static method.");
}

25
// Creating a public method
public void fun2() {
System.out.println("fun2: This is a public method.");
}

// The main() method


public static void main(String[] args) {
// Accessing static method through the class
fun1();

// Creating an object of the Main class


Main obj = new Main();
// Accessing public method through the object
obj.fun2();
}
}
Output
fun1: This is a static method.
fun2: This is a public method.
The finalize( ) Method

It is possible to define a method that will be called just before an


object's final destruction by the garbage collector. This method is
called finalize( ), and it can be used to ensure that an object
terminates cleanly.

For example, you might use finalize( ) to make sure that an open
file owned by that object is closed.

To add a finalizer to a class, you simply define the finalize( )


method. The Java runtime calls that method whenever it is about to
recycle an object of that class.

Inside the finalize( ) method, you will specify those actions that
must be performed before an object is destroyed.

26
The finalize( ) method has this general form −

protected void finalize( ) {


// finalization code here
}

Here, the keyword protected is a specifier that prevents access to


finalize( ) by code defined outside its class.

This means that you cannot know when or even if finalize( ) will be
executed. For example, if your program ends before garbage
collection occurs, finalize( ) will not execute.

Java Methods

A Java method is a collection of statements that are grouped together


to perform an operation. When you call
the System.out.println() method, for example, the system actually
executes several statements in order to display a message on the
console.

In this tutorial, we will learn how to create your own methods with
or without return values, invoke a method with or without
parameters, and apply method abstraction in the program design.

Creating a Java Method

To create a Java method, there should be an access


modifier followed by the return type, method's name, and
parameters list.

Syntax to Create a Java Method

Considering the following example to explain the syntax of a


method −

modifier returnType nameOfMethod (Parameter List) {


// method body
}

27
The syntax shown above includes −

• modifier − It defines the access type of the method and it is


optional to use.
• returnType − Method may return a value.
• nameOfMethod − This is the method name. The method
signature consists of the method name and the parameter list.
• Parameter List − The list of parameters, it is the type, order,
and number of parameters of a method. These are optional,
method may contain zero parameters.
• method body − The method body defines what the method does
with the statements.
Example to Create a Java Method

Here is the source code of the above defined method


called minFunction(). This method takes two
parameters n1 and n2 and returns the minimum between the two −

/** the snippet returns the minimum between two numbers */

public static int minFunction(int n1, int n2) {


int min;
if (n1 > n2)
min = n2;
else
min = n1;

return min;
}
Calling a Java Method

For using a method, it should be called. There are two ways in


which a method is called i.e., method returns a value or returning
nothing (no return value).

The process of method calling is simple. When a program invokes a


method, the program control gets transferred to the called method.

28
This called method then returns control to the caller in two
conditions, when −

• the return statement is executed.


• it reaches the method ending closing brace.

The methods returning void is considered as call to a statement.


Lets consider an example −

System.out.println("This is tutorialspoint.com!");

The method returning value can be understood by the following


example −

int result = sum(6, 9);

Java Methods Overloading

When a class has two or more methods by the same name but
different parameters, it is known as method overloading. It is
different from overriding. In overriding, a method has the same
method name, type, number of parameters, etc.

Let's consider the example discussed earlier for finding minimum


numbers of integer type. If, let's say we want to find the minimum
number of double type. Then the concept of overloading will be
introduced to create two or more methods with the same name but
different parameters.

The following example explains the same −

Example: Methods Overloading in Java


public class ExampleOverloading {

public static void main(String[] args) {


int a = 11;
int b = 6;
double c = 7.3;
double d = 9.4;

29
int result1 = minFunction(a, b);

// same function name with different parameters


double result2 = minFunction(c, d);
System.out.println("Minimum Value = " + result1);
System.out.println("Minimum Value = " + result2);
}

// for integer
public static int minFunction(int n1, int n2) {
int min;
if (n1 > n2)
min = n2;
else
min = n1;

return min;
}

// for double
public static double minFunction(double n1, double n2) {
double min;
if (n1 > n2)
min = n2;
else
min = n1;

return min;
}
}
Output
Minimum Value = 6
Minimum Value = 7.3

30
Overloading methods makes program readable. Here, two methods
are given by the same name but with different parameters. The
minimum number from integer and double types is the result.

Important Points About Variables Scope


• By default, a variable has default access. Default access
modifier means we do not explicitly declare an access modifier
for a class, field, method, etc.
• A variable or method declared without any access control
modifier is available to any other class in the same package.
The fields in an interface are implicitly public static final and
the methods in an interface are by default public.
• Java provides a number of access modifiers to set access levels
for classes, variables, methods, and constructors. The four
access levels are −
o default − Visible to the package. No modifiers are needed.
o private − Visible to the class only.
o public − Visible to the world.
o protected − Visible to the package and all subclasses.
Java Constructors

Java constructors are special types of methods that are used to


initialize an object when it is created. It has the same name as its
class and is syntactically similar to a method. However, constructors
have no explicit return type.

Typically, you will use a constructor to give initial values to the


instance variables defined by the class or to perform any other
start-up procedures required to create a fully formed object.

All classes have constructors, whether you define one or not


because Java automatically provides a default constructor that
initializes all member variables to zero. However, once you define
your constructor, the default constructor is no longer used.

Rules for Creating Java Constructors

You must follow the below-given rules while creating Java


constructors:

31
•The name of the constructors must be the same as the class
name.
• Java constructors do not have a return type. Even do not use
void as a return type.
• There can be multiple constructors in the same class, this
concept is known as constructor overloading.
• The access modifiers can be used with the constructors, use if
you want to change the visibility/accessibility of constructors.
• Java provides a default constructor that is invoked during the
time of object creation. If you create any type of constructor,
the default constructor (provided by Java) is not invoked.
Creating a Java Constructor

To create a constructor in Java, simply write the constructor's name


(that is the same as the class name) followed by the brackets and
then write the constructor's body inside the curly braces ({}).

Syntax

Following is the syntax of a constructor −

class ClassName {
ClassName() {
}
}
Example to create a Java Constructor

The following example creates a simple constructor that will print


"Hello world".

public class Main {


// Creating a constructor
Main() {
System.out.println("Hello, World!");
}

public static void main(String[] args) {


System.out.println("The main() method.");

32
// Creating a class's object
// that will invoke the constructor
Main obj_x = new Main();
}
}

This program will print:

The main() method.


Hello, World!
Types of Java Constructors

There are three different types of constructors in Java, we have


listed them as follows:

• Default Constructor
• No-Args Constructor
• Parameterized Constructor

1. Default Constructor

If you do not create any constructor in the class, Java provides a


default constructor that initializes the object.

Example: Default Constructor (A Class Without Any


Constructor)

In this example, there is no constructor defined by us. The default


constructor is there to initialize the object.

33
public class Main {
int num1;
int num2;

public static void main(String[] args) {


// We didn't created any structure
// a default constructor will invoke here
Main obj_x = new Main();

// Printing the values


System.out.println("num1 : " + obj_x.num1);
System.out.println("num2 : " + obj_x.num2);
}
}

Output

num1 : 0
num2 : 0
2. No-Args (No Argument) Constructor

As the name specifies, the No-argument constructor does not accept


any argument. By using the No-Args constructor you can initialize
the class data members and perform various activities that you
want on object creation.

Example: No-Args Constructor

This example creates no-args constructor.

public class Main {


int num1;
int num2;

// Creating no-args constructor


Main() {
num1 = -1;

34
num2 = -1;
}

public static void main(String[] args) {


// no-args constructor will invoke
Main obj_x = new Main();

// Printing the values


System.out.println("num1 : " + obj_x.num1);
System.out.println("num2 : " + obj_x.num2);
}
}

Output

num1 : -1
num2 : -1
3. Parameterized Constructor

A constructor with one or more arguments is called a parameterized


constructor.

Most often, you will need a constructor that accepts one or more
parameters. Parameters are added to a constructor in the same way
that they are added to a method, just declare them inside the
parentheses after the constructor's name.

Example 1: Parameterized Constructor

This example creates a parameterized constructor.

public class Main {


int num1;
int num2;

// Creating parameterized constructor


Main(int a, int b) {

35
num1 = a;
num2 = b;
}

public static void main(String[] args) {


// Creating two objects by passing the values
// to initialize the attributes.
// parameterized constructor will invoke
Main obj_x = new Main(10, 20);
Main obj_y = new Main(100, 200);

// Printing the objects values


System.out.println("obj_x");
System.out.println("num1 : " + obj_x.num1);
System.out.println("num2 : " + obj_x.num2);

System.out.println("obj_y");
System.out.println("num1 : " + obj_y.num1);
System.out.println("num2 : " + obj_y.num2);
}
}

Output

obj_x
num1 : 10
num2 : 20
obj_y
num1 : 100
num2 : 200

Constructor Overloading in Java

Constructor overloading means multiple constructors in a class.


When you have multiple constructors with different parameters
listed, then it will be known as constructor overloading.

36
Example: Constructor Overloading

In this example, we have more than one constructor.

// Example of Java Constructor Overloading


// Creating a Student Class
class Student {
String name;
int age;

// no-args constructor
Student() {
this.name = "Unknown";
this.age = 0;
}

// parameterized constructor having one parameter


Student(String name) {
this.name = name;
this.age = 0;
}

// parameterized constructor having both parameters


Student(String name, int age) {
this.name = name;
this.age = age;
}

public void printDetails() {


System.out.println("Name : " + this.name);
System.out.println("Age : " + this.age);
}
}

public class Main {


public static void main(String[] args) {

37
Student std1 = new Student(); // invokes no-args constructor
Student std2 = new Student("Jordan"); // invokes parameterized constructor
Student std3 = new Student("Paxton", 25); // invokes parameterized
constructor

// Printing details
System.out.println("std1...");
std1.printDetails();

System.out.println("std2...");
std2.printDetails();

System.out.println("std3...");
std3.printDetails();
}
}

Output

td1...
Name : Unknown
Age : 0
std2...
Name : Jordan
Age : 0
std3...
Name : Paxton
Age : 25

Java Interfaces

Java interface is a collection of abstract methods. The interface is


used to achieve abstraction in which you can define methods
without their implementations (without having the body of the
methods). An interface is a reference type and is similar to
the class.

38
Along with abstract methods, an interface may also contain
constants, default methods, static methods, and nested types.
Method bodies exist only for default methods and static methods.

Writing an interface is similar to writing a class. However, a class


describes the attributes and behaviors of an object. An interface
contains behaviors that a class implements. Unless the class that
implements the interface is abstract, all the methods of the
interface need to be defined in the class.

Java Interfaces and Classes: Similarities and Differences


Similarities

An interface is similar to a class in the following ways −

• An interface can contain any number of methods.


• An interface is written in a file with a .java extension, with the
name of the interface matching the name of the file.
• The byte code of an interface appears in a .class file.
• Interfaces appear in packages, and their corresponding
bytecode file must be in a directory structure that matches the
package name.
Differences

However, an interface is different from a class in several ways,


including −

• You cannot instantiate an interface.


• An interface does not contain any constructors.
• All of the methods in an interface are abstract.
• An interface cannot contain instance fields. The only fields that
can appear in an interface must be declared both static and
final.
• An interface is not extended by a class; it is implemented by a
class.
• An interface can extend multiple interfaces.

39
Declaring an Interface in Java

The interface keyword is used to declare an interface. Here is a


simple example to declare an interface −

Example to Declare a Java Interface

Following is an example of an interface −

/* File name : NameOfInterface.java */


import java.lang.*;
// Any number of import statements

public interface NameOfInterface {


// Any number of final, static fields
// Any number of abstract method declarations\
}
Propeties of Java Interface

Interfaces have the following properties −

• An interface is implicitly abstract. You do not need to use


the abstract keyword while declaring an interface.
• Each method in an interface is also implicitly abstract, so the
abstract keyword is not needed.
• Methods in an interface are implicitly public.
Example
/* File name : Animal.java */
interface Animal {
public void eat();
public void travel();
}
Implementing Interfaces in Java

When a class implements an interface, you can think of the class as


signing a contract, agreeing to perform the specific behaviors of the
interface. If a class does not perform all the behaviors of the
interface, the class must declare itself as abstract.

40
A class uses the implements keyword to implement an interface. The
implements keyword appears in the class declaration following the
extends portion of the declaration.

Example: Implement an Interface in Java


/* File name : MammalInt.java */
public class MammalInt implements Animal {

public void eat() {


System.out.println("Mammal eats");
}

public void travel() {


System.out.println("Mammal travels");
}

public int noOfLegs() {


return 0;
}

public static void main(String args[]) {


MammalInt m = new MammalInt();
m.eat();
m.travel();
}
}
interface Animal {
public void eat();
public void travel();
}
Output
Mammal eats
Mammal travels

Difference between abstract class and interface

41
Abstract class and interface both are used to achieve abstraction where we can declare
the abstract methods. Abstract class and interface both can't be instantiated.

But there are many differences between abstract class and interface that are given below.

Abstract class Interface

1) Abstract class can have abstract and Interface can have only abstract methods.
non-abstract methods. Since Java 8, it can have default and static
methods also.

2) Abstract class doesn't support multiple Interface supports multiple inheritance.


inheritance.

3) Abstract class can have final, non-final, Interface has only static and final variables.
static and non-static variables.

4) Abstract class can provide the Interface can't provide the implementation
implementation of interface. of abstract class.

5) The abstract keyword is used to declare The interface keyword is used to declare
abstract class. interface.

6) An abstract class can extend another An interface can extend another Java interface
Java class and implement multiple Java only.
interfaces.

7) An abstract class can be extended using An interface can be implemented using


keyword "extends". keyword "implements".

8) A Java abstract class can have class Members of a Java interface are public by
members like private, protected, etc. default.

9)Example: Example:
public abstract class Shape{ public interface Drawable{
public abstract void draw(); void draw();
} }

42
Java Packages

Packages are used in Java in order to prevent naming conflicts,


control access, make searching/locating and usage of classes,
interfaces, enumerations, and annotations easier, etc.

A Java package can be defined as a grouping of related types


(classes, interfaces, enumerations, and annotations ) providing
access protection and namespace management.

Types of Java Packages

Java packages are of two types:

• Built-in Java Packages


• User-defined Java Packages

Some of the existing packages in Java are −

•java.lang − bundles the fundamental classes


• java.io − classes for input , output functions are bundled in this
package
User-defined Java Packages

You can define your own packages to bundle groups of


classes/interfaces, etc. It is a good practice to group related classes
implemented by you so that a programmer can easily determine
that the classes, interfaces, enumerations, and annotations are
related.

Since the package creates a new namespace there won't be any


name conflicts with names in other packages. Using packages, it is
easier to provide access control and it is also easier to locate the
related classes.

Creating a Java Package

While creating a package, you should choose a name for the


package and include a package statement along with that name at
the top of every source file that contains the classes, interfaces,

43
enumerations, and annotation types that you want to include in the
package.

The package statement should be the first line in the source file.
There can be only one package statement in each source file, and it
applies to all types in the file.

If a package statement is not used then the class, interfaces,


enumerations, and annotation types will be placed in the current
default package.

Compiling with Java Package

To compile the Java programs with package statements, you have


to use -d option as shown below.

javac -d Destination_folder file_name.java

Then a folder with the given package name is created in the


specified destination, and the compiled class files will be placed in
that folder.

Java Package Example

Let us look at an example that creates a package called animals. It


is a good practice to use names of packages with lower case letters
to avoid any conflicts with the names of classes and interfaces.

Following package example contains interface named animals −

/* File name : Animal.java */


package animals;

interface Animal {
public void eat();
public void travel();
}

Now, let us implement the above interface in the same


package animals −
44
package animals;
/* File name : MammalInt.java */

public class MammalInt implements Animal {

public void eat() {


System.out.println("Mammal eats");
}

public void travel() {


System.out.println("Mammal travels");
}

public int noOfLegs() {


return 0;
}

public static void main(String args[]) {


MammalInt m = new MammalInt();
m.eat();
m.travel();
}
}

interface Animal {
public void eat();
public void travel();
}
Output

Now compile the java files as shown below −

$ javac -d . Animal.java
$ javac -d . MammalInt.java

45
Java Abstraction

Abstraction is a process of hiding the implementation details from


the user, only the functionality will be provided to the user. In other
words, the user will have the information on what the object does
instead of how it does it. In Java programming, abstraction is
achieved using Abstract classes and interfaces.

Java Abstract Classes

A Java class which contains the abstract keyword in its declaration is


known as abstract class.

Java abstract classes may or may not contain abstract



methods, i.e., methods without body ( public void get(); )
• But, if a class has at least one abstract method, then the
class must be declared abstract.
• If a class is declared abstract, it cannot be instantiated.
• To use an abstract class, you have to inherit it from another
class, provide implementations to the abstract methods in it.
• If you inherit an abstract class, you have to provide
implementations to all the abstract methods in it.
What Is an Exception in Java?

An exception (or exceptional event) is a problem that arises during


the execution of a program. When an Exception occurs the normal
flow of the program is disrupted and the program/Application
terminates abnormally, which is not recommended, therefore, these
exceptions are to be handled.

Why Exception Occurs?

An exception can occur for many different reasons. Following are


some scenarios where an exception occurs.

• A user has entered an invalid data.


• A file that needs to be opened cannot be found.
• A network connection has been lost in the middle of
communications or the JVM has run out of memory.

46
Some of these exceptions are caused by user error, others by
programmer error, and others by physical resources that have failed
in some manner.

The Throws/Throw Keywords

If a method does not handle a checked exception, the method must


declare it using the throws keyword. The throws keyword appears at
the end of a method's signature.

You can throw an exception, either a newly instantiated one or an


exception that you just caught, by using the throw keyword.

Try to understand the difference between throws and throw


keywords, throws is used to postpone the handling of a checked
exception and throw is used to invoke an exception explicitly.

The following method declares that it throws a RemoteException −

Example
import java.io.*;
public class className {

public void deposit(double amount) throws RemoteException {


// Method implementation
throw new RemoteException();
}
// Remainder of class definition
}

A method can declare that it throws more than one exception, in


which case the exceptions are declared in a list separated by
commas. For example, the following method declares that it throws
a RemoteException and an InsufficientFundsException −

Example
import java.io.*;
public class className {

47
public void withdraw(double amount) throws RemoteException,
InsufficientFundsException {
// Method implementation
}
// Remainder of class definition
}
The Finally Block

The finally block follows a try block or a catch block. A finally block
of code always executes, irrespective of occurrence of an Exception.

Using a finally block allows you to run any cleanup-type statements


that you want to execute, no matter what happens in the protected
code.

A finally block appears at the end of the catch blocks and has the
following syntax −

Syntax
try {
// Protected code
} catch (ExceptionType1 e1) {
// Catch block
} catch (ExceptionType2 e2) {
// Catch block
} catch (ExceptionType3 e3) {
// Catch block
}finally {
// The finally block always executes.
}
Example
public class ExcepTest {

public static void main(String args[]) {


int a[] = new int[2];
try {
System.out.println("Access element three :" + a[3]);
48
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Exception thrown :" + e);
}finally {
a[0] = 6;
System.out.println("First element value: " + a[0]);
System.out.println("The finally statement is executed");
}
}
}

Output

Exception thrown :java.lang.ArrayIndexOutOfBoundsException: 3


First element value: 6
The finally statement is executed
Java try and catch

A method catches an exception using a combination of


the try and catch keywords. A try and catch block is placed around
the code that might generate an exception. Code within
a try and catch block is referred to as protected code, and the
syntax for using try/catch looks like the following −

The try Block

The code which is prone to exceptions is placed in the try block.


When an exception occurs, that exception occurred is handled
by catch block associated with it. Every try block should be
immediately followed either by a catch block or finally block.

The catch Block

A catch statement involves declaring the type of exception you are


trying to catch. If an exception occurs in protected code,
the catch block (or blocks) that follows the try is checked. If the
type of exception that occurred is listed in a catch block, the
exception is passed to the catch block much as an argument is
passed into a method parameter.

49
Syntax of Java try and catch Block
try {
// Protected code
} catch (ExceptionName e1) {
// Catch block
}
Example of Java try and catch Block

In following example, an array is declared with 2 elements. Then


the code tries to access the 3rd element of the array which throws
an exception. As we've enclosed the code with a try block, this
exception can be handled within next catch block which we've
declared to catch ArrayIndexOutOfBoundsException. After catching
the exception, we can take the corresponding action. Here we're
printing the details of the exception thrown.

package com.tutorialspoint;

public class ExcepTest {

public static void main(String args[]) {


try {
int a[] = new int[2];
System.out.println("Access element three :" + a[3]);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Exception thrown :" + e);
}
System.out.println("Out of the block");
}
}
Output
Exception thrown :java.lang.ArrayIndexOutOfBoundsException: 3
Out of the block

Java - Multithreading
50
Java is a multi-threaded programming language which means we
can develop multi-threaded program using Java. A multi-threaded
program contains two or more parts that can run concurrently and
each part can handle a different task at the same time making
optimal use of the available resources specially when your computer
has multiple CPUs.

By definition, multitasking is when multiple processes share


common processing resources such as a CPU. Multi-threading
extends the idea of multitasking into applications where you can
subdivide specific operations within a single application into
individual threads. Each of the threads can run in parallel. The OS
divides processing time not only among different applications, but
also among each thread within an application.

Java Multithreading

Multi-threading enables you to write in a way where multiple


activities can proceed concurrently in the same program. To achieve
the multithreading (or, write multithreaded code), you
need java.lang.Thread class.

Life Cycle of a Thread in Java Multithreading

A thread goes through various stages in its life cycle. For example,
a thread is born, started, runs, and then dies. The following diagram
shows the complete life cycle of a thread.

51
Java - Applet Basics
An applet is a Java program that runs in a Web browser. An applet can be a fully
functional Java application because it has the entire Java API at its disposal.

There are some important differences between an applet and a standalone Java
application, including the following −

• An applet is a Java class that extends the java.applet.Applet class.


• A main() method is not invoked on an applet, and an applet class will not
define main().
• Applets are designed to be embedded within an HTML page.
• When a user views an HTML page that contains an applet, the code for the
applet is downloaded to the user's machine.
• A JVM is required to view an applet. The JVM can be either a plug-in of the Web
browser or a separate runtime environment.
• The JVM on the user's machine creates an instance of the applet class and
invokes various methods during the applet's lifetime.
• Applets have strict security rules that are enforced by the Web browser. The
security of an applet is often referred to as sandbox security, comparing the
applet to a child playing in a sandbox with various rules that must be followed.
• Other classes that the applet needs can be downloaded in a single Java Archive
(JAR) file.
Life Cycle of an Applet in Java

Four methods in the Applet class gives you the framework on which you build any
serious applet −

• init − This method is intended for whatever initialization is needed for your
applet. It is called after the param tags inside the applet tag have been
processed.
• start − This method is automatically called after the browser calls the init method.
It is also called whenever the user returns to the page containing the applet after
having gone off to other pages.
• stop − This method is automatically called when the user moves off the page on
which the applet sits. It can, therefore, be called repeatedly in the same applet.
• destroy − This method is only called when the browser shuts down normally.
Because applets are meant to live on an HTML page, you should not normally
leave resources behind after a user leaves the page that contains the applet.
• paint − Invoked immediately after the start() method, and also any time the
applet needs to repaint itself in the browser. The paint() method is actually
inherited from the java.awt

52
AWT
Java AWT (Abstract Window Toolkit) is an API to develop Graphical User Interface (GUI)
or windows-based applications in Java.

Java AWT components are platform-dependent i.e. components are displayed according
to the view of operating system. AWT is heavy weight i.e. its components are using the
resources of underlying operating system (OS).

The java.awt package provides classes for AWT API such as TextField, Label, TextArea,
RadioButton, CheckBox, Choice, List etc.

The AWT tutorial will help the user to understand Java GUI programming in simple and
easy steps.

AWT Hierarchy
The hierarchy of Java AWT classes are given below.

53
Introduction to Java Servlets
Servlets are the Java programs that run on the Java-enabled web server or
application server. They are used to handle the request obtained from the web
server, process the request, produce the response, and then send a response
back to the web server.
The properties of Servlets are as follows:
• Servlets work on the server side.
• Servlets are capable of handling complex requests obtained from the
web server.
Execution of Servlets basically involves six basic steps:
1. The clients send the request to the webserver.
2. The web server receives the request.
3. The web server passes the request to the corresponding servlet.
4. The servlet processes the request and generates the response in the
form of output.
5. The servlet sends the response back to the webserver.
6. The web server sends the response back to the client and the client
browser displays it on the screen.
What is CGI?
CGI is actually an external application that is written by using any of the
programming languages like C or C++ and this is responsible for processing
client requests and generating dynamic content.
In CGI application, when a client makes a request to access dynamic Web
pages, the Web server performs the following operations:
• It first locates the requested web page i.e the required CGI application
using URL.
• It then creates a new process to service the client’s request.
• Invokes the CGI application within the process and passes the request
information to the application.
• Collects the response from the CGI application.
• Destroys the process, prepares the HTTP response, and sends it to
the client.

54
Difference between Servlet and CGI
CGI (Common Gateway
Servlet Interface)

Servlets are portable and efficient. CGI is not portable.

In Servlets, sharing data is possible. In CGI, sharing data is not possible.

Servlets can directly communicate CGI cannot directly communicate with


with the webserver. the webserver.

Servlets are less expensive than CGI. CGI is more expensive than Servlets.

Servlets can handle the cookies. CGI cannot handle the cookies.

if:
if statement is the most simple decision-making statement. It is used to decide
whether a certain statement or block of statements will be executed or not i.e if a
certain condition is true then a block of statements is executed otherwise not.
Syntax:
if(condition)
{
// Statements to execute if
// condition is true
}
Here, the condition after evaluation will be either true or false. if statement accepts
boolean values – if the value is true then it will execute the block of statements under
it.
If we do not provide the curly braces ‘{‘ and ‘}’ after if( condition ) then by default if
statement will consider the immediate one statement to be inside its block. For
example,
if(condition) //Assume condition is true

55
statement1; //part of if block
statement2; // separate from if block

// Here if the condition is true


// if block will consider statement1 as its part and executes in only true condition
// statement2 will be separate from the if block so it will always executes whether the
condition is true or false.

Example:
• Java

// Java program to illustrate If statement without curly block


import java.util.*;

class IfDemo {
public static void main(String args[])
{
int i = 10;

if (i < 15)
System.out.println("Inside If block"); // part of if block(immediate one statement after if
condition)
System.out.println("10 is less than 15"); //always executes as it is outside of if block
// This statement will be executed
// as if considers one statement by default again below statement is outside of if block
System.out.println("I am Not in if");
}
}

Output

56
Inside If block
10 is less than 15
I am Not in if
if-else:
The if statement alone tells us that if a condition is true it will execute a block of
statements and if the condition is false it won’t. But what if we want to do something
else if the condition is false? Here comes the else statement. We can use the else
statement with the if statement to execute a block of code when the condition is false.
Syntax:
if (condition)
{
// Executes this block if
// condition is true
}
else
{
// Executes this block if
// condition is false
}

Example:
• Java

// Java program to illustrate if-else statement


import java.util.*;

class IfElseDemo {
public static void main(String args[])
{
int i = 10;

57
if (i < 15)
System.out.println("i is smaller than 15");
else
System.out.println("i is greater than 15");
}
}

Output
i is smaller than 15
nested-if:
A nested if is an if statement that is the target of another if or else. Nested if
statements mean an if statement inside an if statement. Yes, java allows us to nest if
statements within if statements. i.e, we can place an if statement inside another if
statement.
Syntax:
if (condition1)
{
// Executes when condition1 is true
if (condition2)
{
// Executes when condition2 is true
}
}

Example:
• Java

// Java program to illustrate nested-if statement


import java.util.*;

58
class NestedIfDemo {
public static void main(String args[])
{
int i = 10;

if (i == 10 || i<15) {
// First if statement
if (i < 15)
System.out.println("i is smaller than 15");

// Nested - if statement
// Will only be executed if statement above
// it is true
if (i < 12)
System.out.println(
"i is smaller than 12 too");
} else{
System.out.println("i is greater than 15");
}
}
}

Output
i is smaller than 15
i is smaller than 12 too
if-else-if ladder:
Here, a user can decide among multiple options.The if statements are executed from
the top down. As soon as one of the conditions controlling the if is true, the statement
associated with that ‘if’ is executed, and the rest of the ladder is bypassed. If none of
the conditions is true, then the final else statement will be executed. There can be as

59
many as ‘else if’ blocks associated with one ‘if’ block but only one ‘else’ block is
allowed with one ‘if’ block.
if (condition)
statement;
else if (condition)
statement;
.
.
else
statement;

Example:
• Java

// Java program to illustrate if-else-if ladder


import java.util.*;

class ifelseifDemo {
public static void main(String args[])
{
int i = 20;

if (i == 10)
System.out.println("i is 10");
else if (i == 15)
System.out.println("i is 15");
else if (i == 20)
System.out.println("i is 20");
else

60
System.out.println("i is not present");
}
}

Output
i is 20
switch-case:
The switch statement is a multiway branch statement. It provides an easy way to
dispatch execution to different parts of code based on the value of the expression.
Syntax:
switch (expression)
{
case value1:
statement1;
break;
case value2:
statement2;
break;
.
.
case valueN:
statementN;
break;
default:
statementDefault;
}

• Java

/*package whatever //do not write package name here */

61
import java.io.*;

class GFG {
public static void main (String[] args) {
int num=20;
switch(num){
case 5 : System.out.println("It is 5");
break;
case 10 : System.out.println("It is 10");
break;
case 15 : System.out.println("It is 15");
break;
case 20 : System.out.println("It is 20");
break;
default: System.out.println("Not present");

}
}
}

Output
It is 20
jump:
Java supports three jump statements: break, continue and return. These three
statements transfer control to another part of the program.
Break:
In Java, a break is majorly used for:

• Terminate a sequence in a switch statement (discussed above).

62
• To exit a loop.
• Used as a “civilized” form of goto.
Continue:
Sometimes it is useful to force an early iteration of a loop. That is, you might want to
continue running the loop but stop processing the remainder of the code in its body for
this particular iteration. This is, in effect, a goto just past the body of the loop, to the
loop’s end. The continue statement performs such an action.

Example:
• Java

// Java program to illustrate using


// continue in an if statement
import java.util.*;

class ContinueDemo {
public static void main(String args[])
{
for (int i = 0; i < 10; i++) {
// If the number is even
// skip and continue
if (i % 2 == 0)
continue;

// If number is odd, print it


System.out.print(i + " ");
}
}
}

Output

63
13579
Return:
The return statement is used to explicitly return from a method. That is, it causes
program control to transfer back to the caller of the method.
Example:
• Java

// Java program to illustrate using return


import java.util.*;

public class Return {


public static void main(String args[])
{
boolean t = true;
System.out.println("Before the return.");

if (t)
return;

// Compiler will bypass every statement


// after return
System.out.println("This won't execute.");
}
}

Output
Before the return.

64

You might also like