Java OOP (Object Oriented Programming) | Java OOPs Concepts

JAVA’s History:

Java is a general purpose, Object Oriented programming language. It is a powerful, versatile, and simple programming language. It is one of the most widely used high-level programming languages in the world.

Java developed by James Gosling at Sun Microsystems in 1991. The original name of Java was Oak but it was renamed to Java in 1995 as OAK was a registered trademark of another Tech company.

Sun Microsystems started a project called ‘Green’ in 1991, mot knowing that their project would lead them to develop a programming language called Java. The Green project was born as part of a larger project to develop advanced software for consumer electronic devices like TVs, VCRs, toasters and such other electronic machines. The plan was to develop the project in C++. The project team which included Patrick Naughton discovered that the existing languages like C and C++ had limitations. The developers ran into many problems as they tried to extend the C++ compiler. They needed a new language to develop this project. James Gosling began work on a new language called Oak. Later it was called Java because Oak failed the trade mark search.


Byte Code:

Bytecode in Java is a set of instructions for the Java Virtual Machine. Java Virtual Machine, abbreviated as JVM, enables a computer to run code written in Java. When a Java program is compiled, the bytecode gets generated. It is equivalent to the assembler in C++.

Bytecode is a machine-independent code. Code that runs on multiple computer architectures is called machine-independent code. It is not dependent on the properties of a specific machine, and can therefore be used on any machine. So basically it can run on any environment or system. It is a code that lies in between low-level language and high-level language. Since we write our code in high-level language, it gets compiled into bytecode and later JVM converts it into machine code which is a low level code hence we call bytecode as a code that lies between low-level language and high-level language. The bytecode can run on any device which makes it independent of the Operating System.



Java Virtual Machine (JVM):

The Java Virtual Machine (JVM) is at the heart of Java programming language. It is an abstract computing machine or virtual machine. It is a part of java runtime environment. Mostly in other Programming Languages, compilers translate source code into machine code for a particular system but Java compiler produces an intermediate code known as Byte-code for a machine that does not exist. This machine is called the Java Virtual Machine and it exists only inside the computer memory. It is a simulated computer within the computer and does all major functions of a real computer.


Fig: Process of compilation


The compiled Java byte code can run on any computer with the Java runtime environment installed on it.

The virtual machine code is not machine specific. The machine specific code (known as machine code) is generated by the java interpreter by acting as an intermediary between the virtual machine and the real machine.





Fig: Process of converting bytecode into machine code

The JVM plays an important role in making the Java language portable and platform independent as it hides the details of implementation between the hardware requirement and the operating system.

The JVM has two primary functions: to allow Java programs to run on any device or operating system (known as the "Write once, run anywhere" principle), and to manage and optimize program memory.


Data Type of Java:


As the name suggests, data types specify the type of data that can be stored inside variables in Java. Each variable has a data type that decides what type of value the variable will hold.

data type is an attribute of a variable which tells the compiler or interpreter how the programmer intends to use the variable. It defines the operations that can be done on the data and what type of values can be stored.

Data types in Java are mainly divided into 2 categories:

1. Primitive Data Types

2. Non-Primitive Data Types


Primitive Data Types: A primitive data type is pre-defined by the programming language. These data types are already hard coded into the compiler to be recognized when the program is executed. Examples are- int, float etc.


Non-Primitive Data Types: These data types are special types of data which are user defined. Examples are- classes, interfaces etc.

These data types are not actually defined by the programming language but are created by the programmer. They are also called “reference variables” or “object references” since they reference a memory location which stores the data.


Variables:

Variables are containers for storing data values. Variable is a name of memory location. The value stored in a variable can be changed during program execution. In Java, all variables must be declared before use.


Declaring (Creating) Variables:

To create a variable, you must specify the type and assign it a value:

Syntax:

Type variablename=value;


Where type is data type and variableName is the name of the variable. The equal sign is used to assign values to the variable.


Java Operators:


An operator can be defined as a symbol that specifies an operation to be performed. For example: +, -, *, / etc.

An operator is a symbol that tells the compiler to perform certain mathematical or logical computations.

Java divides the operators into the following categories:

  • Arithmetic operators
  • Assignment operators
  • Relational (Comparison) operators
  • Logical operators
  • Increment and decrement operators
  • Conditional operators
  • Bitwise operators


Arithmetic Operators: 

The arithmetic operators are used to perform mathematical calculations such as addition, subtraction etc. Java supports all the basic arithmetic operators. 


Operator

Meaning

+

Addition

-

Subtraction

*

Multiplication

/

Division

%

Modulus (Remainder)


These operators can operate on any built–in data types such as int, char and float. However, the modulus operator requires an integral operand (must not be float).


Assignment Operator:

An assignment operator is used to assign a value to a variable or to assign the result of an expression to a variable. The = symbol is used as an assignment operator.

Or simply we can say, a data or value can be stored in a variable with the help of assignment operator. The assignment operator is used in assignment statement and assignment expression.

The syntax of an assignment is,

Variable name=expression;

For example,       

    a=5;

    Sum=a+b;

In many cases, the assignment operator can be combined with other operators to build a shorter version of the statement called a Compound Statement. For example, instead of a = a+5, we can write a += 5.


Relational Operators:

These operators are used to check for relations like equality, greater than, and less than. They return Boolean results after the comparison and are extensively used in looping statements as well as conditional if-else statements.

 

These are used to compare the values two variable or constants. The relational operators are symbols that are used to test the relationship between variables or between a variable and a constant. 

For example,

    (salary==5000)


Here == is the operator that is used to test equality.

There are six relational operators provided by Java. They are:



Operator

Meaning

= =

equal to

!=

not equal to

> 

greater than

< 

less than

>=

greater than or equal to

<=

less than or equal to



Logical Operators: 

Logical operators are symbols that are used to combine two or more expressions containing relational operators. This situations will arise when we want to perform a statement block on a combined condition, like x>5 and x<10. Then we code this using an AND operator. The AND operator is represented as &&.

Example: ((x>5)&&(x<10))

(Salary>=10000&&salary<=20000)

The logical operators are used to combine conditions. These operators are used with one or more operand and return either value zero (for false) or one (for true). The operand may be constant, variables or expressions. And the expression that combines two or more expressions is termed as logical expression.

Java has three logical operators:

Operator

Meaning

&&   

AND

||       

OR

!

NOT


Increment and Decrement Operators:

The increment and decrement operators are two very useful operator used in Java. Both increment and decrement operator are used on a single operand and variable, so it is called as a unary operator.


Increment operator:

Increment operators are used to increase the value of a variable by 1. This operator is represented by ++ symbol. The increment operator can either increase the value of the variable by 1 before assigning it to the variable or can increase the value of the variable by 1 after assigning the variable. Thus it can be classified into two types:

  • Pre-increment operator
  • Post-increment operator


Pre-increment operator (Prefix increment operator):

A pre-increment operator is used to increment the value of a variable before using it in an expression. In the pre-increment, first increment the value of variable and then used inside the expression.

Syntax:     ++variable;

For example:

 x=+i;

In this case, the value of i will be incremented first by 1. Then the new value will be assigned to x for the expression in which it is used.

 

Post –increment operator (Postfix increment operator):

A post increment operator is used to increment the value of the variable after executing the expression completely in which post increment is used. In the post-increment, first value of variable is used in the expression and then increment the value of variable.

 

Syntax:     variable++

For example:

x=i++;

In this case, the value of i is first assigned to x and after that, i is incremented.

 

Decrement Operators:


We use decrement operators in C to decrement the given value of a variable by 1. This operator is represented by -- symbol.

Decrement operator can be classified into two types:

  • Pre-decrement operator
  • Post-decrement operator

 

Pre-decrement operator (Prefix-decrement operators):

The pre-decrement operator first decrement the value of variable and then used inside the expression.

Syntax:     --variable;

Example:

x=--i;

Here, value of i will decrement first by 1 and then assign it to the variable x.

 

Post-decrement operator (Postfix-decrement operators):

In post-decrement first value of variable is used in the expression and then decrement the variable.

Syntax:     variable—

Example: x=i--;

Here, the value of i is first assigned to x and after that, value of i is decremented.


Conditional Operators:

Sometimes we need to choose between two expressions based on the truth value of a third logical expression. The conditional operator can be used in such cases. It sometimes called as ternary operator. Since it required three expressions as operand and it is represented as (?  :).

Syntax:   exp1 ? exp2 :exp3;

Here exp1 is first evaluated. It is true then value return will be exp2 . If false then exp3.

Example: c=(a>b)?a:b;

Where,  a and b are operands

?:  is the conditional operator

 >   is the relational operator

If the condition is true then value a is assigned to c otherwise b is assigned to c.


Bitwise Operators:

For manipulating data at the bit level C provides us special operators known as bitwise operators. The bitwise operators are the operators used to perform the operations on the data at the bit level. These operators are used to perform bitwise operations such as for testing the bits, shifting the bits to left or right, one’s complement of bits etc.

 Various bitwise operators in Java:

Operator

Meaning

~

one's complement

<< 

Shift left

>> 

Shift right

&

Bitwise AND

|

Bitwise OR

^

Bitwise XOR

(Exclusive OR)


Arrays:

An array is a collection of similar data elements stored at contiguous memory locations. This data type is useful when a group of elements are to be represented by a common name. An array is used to store a group of data items that belong to the same data type.

An array is a group of elements that share a common name, and is differentiated from one another by their positions within the array. An array is also defined as a collection of homogeneous data.

The array is the simplest data structure where each data element can be randomly accessed by using its index number. Array index always start from zero.

Array is beneficial if we have to store similar elements. For example, 70,78,80,95, 90 and 98 are marks in 6 subjects of a student. To store these 6 marks 6 variables would be required- mark1, mark2, mark3, mark4, mark5 and mark6. For such a representation, arrays are useful. This can be represented as mark[6]. We don’t need to define different variables for the marks in the different subject. Instead of that, we can define an array which can store the marks in each subject at the contiguous memory locations.


Types of Array in java:

There are two types of array.

  • Single Dimensional Array
  • Multidimensional Array


OOP (Object Oriented Programming) Fundamentals:

OOP is a programming model based on the concept of objects and classes. It is a methodology or paradigm to design a program using classes and objects. The four principles of object-oriented programming are encapsulation, abstraction, inheritance and polymorphism.

Abstraction: Hiding internal details and showing functionality is known as abstraction. For example phone call, we don't know the internal processing. We all know how to turn the TV on, but we don’t need to know how it works in order to enjoy it.

Encapsulation: Binding (or wrapping) code and data together into a single unit are known as encapsulation. For example, a capsule, it is wrapped with different medicines. Encapsulation is a protective barrier that keeps the data and code safe within the class itself.

Inheritance: A special feature of Object-Oriented Programming in Java. In object-oriented programming, inheritance is a mechanism where programmers can derive a class from another class. Inheritance lets programmers create new classes that share some of the attributes of existing classes. Inheritance also allows programmers to reuse previously written codes. This removes the burden of writing the same codes again, as programmers can make a derived class inherit the property of its parent class.

Polymorphism: If one task is performed in different ways, it is known as polymorphism. Polymorphism allows programmers to use the same word in Java to mean different things in different contexts. One form of polymorphism is method overloading. That’s when the code itself implies different meanings. The other form is method overriding. That’s when the values of the supplied variables imply different meanings. 


Class and Objects:

Class: Class is the core of Java language. It can be defined as a template that describes the behaviors and states of a particular entity.

According to OOPs concept in Java, a class is the blueprint/template of an object. It contains the similar types of objects having the same states (properties) and behavior.

In other words, a class can also be defined as “a class is a group of objects which are common to all objects of one type”. A class is a blueprint or prototype from which objects are created.

A class is defined as a template of data and methods that manipulate the data. For example, if you consider a template of the fan, then,
Data: Number of wings, type of motor, color.
Methods: on, off, rotate at various speeds.

A class is also defined as a blue print or a pattern that defines the data and the methods that operate on this data. Using this blueprint, objects are created. Using the same blueprint many objects can be created. All these objects are similar in their data content as well as their methods. The data content represents the attributes/properties or state of the object and the methods represent the behavior of the object.
A class is a model to create objects. It means that we write properties and actions of objects in the class.

In Java, to declare a class class keyword is used. A class contains both data and methods that operate on that data. The data or variables defined within a class are called instance variables and the code that operates on this data is known as methods. Thus, the instance variables and methods are known as class members.
Classes are also known as user-defined data types. A class defines new data type. Once defined, this new type can be used to create object of that type.

Suppose we create a class “Student” having probable attributes – student’s name, address, roll number and other related parameters.

So, students like Raja, Rishi, Rohit, etc., will be the objects of a class Student having the same properties like student’s name, address, roll number, etc.


Object: Objects are the building blocks of OOP languages. Object is an instance of a class while class is a blueprint of an object. An object represents the class and consists of properties and behavior.
An object is a basic unit of an object-oriented programming language. It is any real-world thing that has properties and actions. In other words, an entity that has state and behavior is known as object in Java. Here, the state represents properties and behavior represents actions or functionality.

In real world, we can understand object as a cell phone that has its properties like: name, cost, color etc and behavior like calling, chatting etc.
For example, book, pen, pencil, TV, fridge, washing machine, mobile phone, etc.

All objects have three characteristics:

Identity: Any object that exists must have an identity i.e., an object is identified by a name.

Identity represents the unique name of an object. It differentiates one object from the other. The unique name of an object is used to identify the object.

State: State represents properties or attributes of an object. To say that an object has state means that a particular object has properties that can change over its lifetime.

Behavior: What the object can do. Every object knows how to do something. Different objects may have different capabilities. The airplane object can fly, the boat object can sail, the fan object can rotate.

Behavior represents functionality or actions. It is represented by methods in Java.


Method Overloading:

In Java it is possible to define two or more methods within the same class having same name, with different parameter declaration. This is known as method overloading.

When an overloaded method is invoked, Java uses the number of arguments and its type to decide which method to be executed. 


Constructor:

A Constructor in Java is a special method, which has the same name as the class. They have no return type, not even void. Constructors are similar to methods, but they are used to initialize an object. The constructor is invoked automatically when a new class object is instantiated.

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.


Syntax:

Following is the syntax of a constructor:

 

Class ClassName

{

ClassName()

{

}

}


Types of Constructor:

Primarily there are two types of constructors in java:

  • Default constructor
  • Parameterized Constructor

Default Constructor: A constructor that has no parameter is known as the default constructor. If we don’t define a constructor in a class, then the compiler creates a default constructor (with no arguments) for the class.

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.


Inheritance in Java:

Inheritance is defined as the creation of a new class from an existing class to provide better features. It is a mechanism in which one class acquires the property of another class. The parent class is called a super class and the inherited class is called a subclass. The keyword extends is used by the sub class to inherit the features of super class.

Inheritance is important since it leads to the reusability of code. In Java, when an “Is-A” relationship exists between two classes, we use Inheritance.

Java Inheritance Syntax:

class subClass extends superClass 

   //methods and fields 

 

Types of Inheritance:

Single Inheritance:


In Single Inheritance one class extends another class (one class only). It is the simplest form of inheritance where a class inherits only one parent class. Single inheritance enables code reusability and adds new features to the existing class.


Multiple Inheritance: 

Multiple Inheritance is one of the inheritance in Java types where one class extending more than one class. When a class inherits more than one parent class, it becomes a multiple inheritance. As the child class inherits properties from different parent classes, it has access to all of its objects. It is different from a single inheritance property, as it allows an object or class to inherit from more than one object or class. Java does not support multiple inheritance.


Multilevel Inheritance:

In Multilevel Inheritance, one class can inherit from a derived class. Hence, the derived class becomes the base class for the new class. When one class inherits properties from a derived class, it is multilevel inheritance. For example, class A extends class B and class B extends class C.

Hierarchical Inheritance:

In Hierarchical Inheritance, one class is inherited by many sub classes. Here, different child classes inherit a single parent class. For example, a parent class C can have three subclasses, D, E and F.

Hybrid Inheritance: 

Hybrid inheritance is one of the inheritance types in Java which is a combination of Single and Multiple inheritances.


Super Keyword: 

The super keyword is similar to “this” keyword.

The keyword super can be used to access any data member or methods of the parent class.

Super keyword can be used at variable, method and constructor level.

 

Syntax:

super.<method-name>();


Interfaces:

Java does not support multiple inheritance, i.e., classes in java cannot have more than one superclass. But, a large number of real life applications require the use of multiple inheritance where we inherit methods and properties from several distinct classes. So, Java provides an alternate approach known as interface to support the concept of multiple inheritance. Although a java class cannot be a subclass of more than one superclass, it can implement more than interface.

An interface in Java is similar to a class. Like class, interfaces also contain methods and variables. But the methods of interfaces are only abstract methods and variables of interfaces are declared as constants (i.e. static and final fields).

In other words, an interface is a collection of constants and abstract methods, which must be implemented in the class that uses it. Java does not support multiple inheritance but where there is need to share common methods Java uses an interface.

Interface is used to achieve complete abstraction. Every interface in java is abstract by default. So, it is not compulsory to write abstract keyword with an interface.  In Java, interfaces are declared using the interface keyword.

 

Syntax:

interace Interfacename

{

declare constant fields

declare method abstract by default;

}

Here, interface is the keyword and InterfaceName is any valid java variable name ( like class name)

 

 Example:

interface student

{

static final int roll=101;

static final String name= “Rohit”;

void show();

}

 

Implementing Interfaces:

In Java, an interface is implemented by a class.  To use an interface in a class, the class must use the keyword, implements. A class can implement any number of interfaces in Java.

An interface is used as “superclass” whose properties are inherited by a class. A class can implement one or more than one interface by using keyword implements followed by a list of interfaces separated by commas.

 

Syntax:

class ClassName implements InterfaceName

{

Body of the class

}

 

Programming Example:

 

interface  A          // interace defined

{

void  Ashow();      // interace defined

}

interface B

{

void Bshow()

}

class AB implements A,B    //interface implemented

{

public void Ashow()

{

System.out.println(“ Hello”);

}

public void Bshow()

{

System.out.println(“ Welcome to Assam”);

}

}

class ABC

{

public static void main(String args[])

{

AB obj=new AB();

obj.Ashow();

obj.Bshow();

}

}



Packages:

One of the reasons for the popularity of Java is the support of standard class libraries called packagesjava package is a group of similar types of classes and interfaces. Packages in Java are a way of grouping together related classes and interfaces. Packages act as containers for classes and interfaces.

A collection of classes and interfaces is known as Packages. Packages are used in Java in order to prevent naming conflicts, to control access, and to write a better maintainable code. It provides a convenient way to organize your work. The classes and interfaces of a package are like books in the library that can reuse several times when we need them. This reusability nature of packages makes programming easy.

 

Java packages are classified into two types:

     1. Built-in packages ( Java API packages )

     2. User-defined packages ( Create your own package)  


Built-in Packages (Java API packages):

Built-in packages are existing java packages that come along with the JDK. The Java API provides a large number of predefined classes grouped into different packages according to functionality.

     There are many built-in packages in java. Few of them frequently used in the program are given below:     

 

Package name

Contents

java.lang

Language support classes

java.util

Language utility classes

java.io

Input/output support classes

java.awt

Classes for implementing graphical user interface

java.net

Classes for networking

java.applet

Classes are creating and implementing applets

   

      We need to import the built-in packages to use them in our program. To import a package, we use the import statement.


User-Defined Package:

The package which is defined by the user is called a User-defined package. It contains user-defined classes and interfaces. The user-defined packages are created by the user. Users are free to create their own packages. Java allows you to create packages as per your needProgrammers can define their own packages to bundle group 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 are related. Using packages, it is easier to provide access control and it is also easier to locate the related classes.


Creating a 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 and interfaces.

To create a package in Java, you use the keyword package.

package packageName;


Here, packageName is the name of package. The package statement must be the first line in a java source code file followed by one or more classes.

 

Creating a package is a simple task as follows:


  • Choose the name of the package
  • Include the package command as the first line of code in your Java Source File.
  • The Source file contains the classes, interfaces, etc you want to include in the package
  • Compile to create the Java packages

                                                 


Exception Handling:


Exception:

An exception is an error in the program, which if handled properly the program can continue instead of terminating. By definition, an exception is a condition that is caused by a run-time error in the program.

An exception is an abnormal event that arises during the execution of the program and disrupts the normal flow of the program. Abnormality does occur when your program is running. For example, you might expect the user to enter an integer, but receive a text string; or an unexpected I/O error pops up at runtime.

If these exceptions are not handled properly, the program terminates abruptly and may cause severe consequences. For example, the network connections, database connections and files may remain opened; database and file records may be left in an inconsistent state.

Any computer application can terminate at any stage of its execution due to an error in the code. Such error situations, referred to as exceptions, can be overcome by Java.

 


Handling of Exception:

When the Java interpreter encounters an error such as dividing an integer by zero, it creates an exception object and throws it (i.e., informs us that an error has occurred). If the exception object is not caught and handled properly, the interpreter will display an error message and will terminate the program. If we want the program to continue with the execution of the remaining code, then we should try to catch the exception object thrown by the error condition and then display an appropriate message for taking corrective actions. This task is known as exception handling.

An exception can be generated by the Java run-time system, or they can be generated manually. Exceptions generated (thrown) by Java are errors that violate the rules of the Java language. The Exception handling feature of Java provides a structural method by which run-time errors can be trapped and handled in a program. Java exception handling is managed through five keywords: try, catch, throw, throws and finally.

The basic concepts of exception handling are throwing an exception and catching it. This is illustrated in figure below:





Using try-catch:

The try-catch block is used to handle exceptions in Java. When an error occurs in your program, the code that finds the error can “throw” that exception. Throwing an exception is the process of signaling the current process that an error has occurred. Your program can catch the thrown exception and execute necessary code to recover from the error if possible.


To handle a particular exception, use the try statement with code that might throw that exception. To catch and act on thrown exceptions, use the catch statement to specify both the exceptions to catch and the code to execute if the exception is thrown.

Syntax:

try

{

statement; //generates an exception

}

catch(Exception-type  e)

{

statement;   //processes the exception

}


The try block can have one or more statements that could generate an exception. If any statement generates an exception, the remaining statements in the block are skipped and execution jumps to the catch block that is placed next to the try block.

The catch block too can have one or more statements that are necessary to process the exception. The catch block is added immediately after the try block. Every try block should be followed by at least one catch block.


Program: Using try and catch for exception handling

 

class ExceptionExample

{

  public static void main(String args[])

{

int a=5;
int b=2;
int c=2;
int x,y;

 

   try

    {

    x=a/(b-c);      //Exception here

    }

    catch(ArithmeticException e)

    {

    System.out.println(“Division by zero”);

    }

    y= a/(b+c)
    System.out.println("y= " + y);

  }

}

 


Output:

 

Division by zero

y=1



Catching Multiple Exceptions:

A try block can be followed by any number of catch blocks-only one of them will be executed.

When an exception in a try block is generated, Java treats the multiple catch statements like cases in a switch statement. The first statement whose parameter matches with the exception object will be executed, and the remaining statements will be skipped.

try

{

statement; //generates an exception

}

catch(Exception-type1  e)

{

statement;   //processes the exception

}

catch(Exception-type2  e)

{

statement;     //processes the exception

}

.

.

.

catch(Exception-typeN  e)

{

statement;   //processes the exception

}



Using finally clause:

Java supports another statement known as finally statement. The finally statement defines a block of code that must be executed regardless of whether an exception was caught or not.

 

try

{

……..

……..

}

catch()

{

…………………

………………..

}

finally

{

………………..

………………….

}


Types of Exceptions:

In Java, exceptions can be categorized into two types:

Checked Exceptions: They are checked at compile-time. For example, IOException, InterruptedException, etc.

Unchecked Exceptions: They are not checked at compile-time but at run-time. For example, ArithmeticException,  NullPointerException,  ArrayIndexOutOfBoundsException, exceptions under Error class, etc.


Throwing Exceptions:

There may be times when we would like to throw our own exceptions. The throw keyword in Java is used to throw an exception explicitly. Using throw keyword, we can throw either checked or unchecked exceptions in java programming.

When an exception occurs in the try block, throw keyword transfers the control of execution to the caller by throwing an object of exception.

Only one object of exception type can be thrown by using throw keyword at a time. Throw keyword can be used inside a method or static block provided that exception handling is present.

 

Syntax:

throw new exception_name(); 

where exception name is a reference to an object of Throwable class or its subclass 


Program: Throwing our own exception


import java.lang.Exception;

class MyException extends Exception

{

   MyException()

    {

    System.out.println("Invalid Marks");

    }

}


class test

{

public static void main(String args[])

{

int marks=107;

    try

    {

     if(marks>100)

     throw new MyException();

     System.out.println("marks:" +marks);

     }

    catch(Exception e)

     {

      System.out.println(e);

      }

}

}

 


Multithreading:


The Java Thread Model:

The java programming language allows us to create a program that contains one or more parts that can run simultaneously at the same time. This type of program is known as a multithreading program. Each part of this program is called a thread

A multithreaded program contains many threads. Threads are Java’s way of running multiple parts of a program simultaneously. The process of executing multiple threads simultaneously is known as multithreading.

Every thread defines a separate path of execution in java. A thread is a light weight process. They are smaller unit of a running process.

A thread may also be defined as follows:

A thread is a subpart of a process that can run individually.


Life Cycle of a Thread:

In java, a thread goes through different states throughout its execution. These stages are called thread life cycle states or phases. A thread may in any of the states like new, ready or runnable, running, blocked or wait, and dead or terminated state. The life cycle of a thread in java is shown in the following figure:




Newborn State:

When a thread object is created using new, then the thread is said to be in the New state. This state is also known as Born state.

 Example:

Thread t1 = new Thread();


Runnable / Ready State:

When a thread calls start( ) method, then the thread is said to be in the Runnable state. This state is also known as a Ready state.

 Example:

 t1.start( );


Running State:

When a thread calls run( ) method, then the thread is said to be Running. The run( ) method of a thread called automatically by the start( ) method.


Blocked / Waiting State:


A thread in the Running state may move into the blocked state due to various reasons like sleep( ) method called, wait( ) method called, suspend( ) method called, and join( ) method called, etc.

When a thread is in the blocked or waiting state, it may move to Runnable state due to reasons like sleep time completed, waiting time completed, notify( ) or notifyAll( ) method called, resume( ) method called, etc.

 Example:

Thread.sleep(1000);

wait(1000);

wait();

suspened();

notify();

notifyAll();

resume();


Dead / Terminated State

A thread in the Running state may move into the dead state due to either its execution completed or the stop( ) method called. The dead state is also known as the terminated state.


Understanding Threads:

Threads are Java’s way of running multiple parts of a program simultaneously. Java provides built-in support for multithreaded programming. A multithreaded program contains many threads. A thread is like a program executing a set of instructions in sequence from within a program. However, a thread cannot run on its own. A Java program during its execution can execute many threads, which can share data and run asynchronously. This way many things can be done at the same time.


Creating a Thread:

Creating thread in Java is simple. A thread can be created in two ways:

  • By extending the Thread class
  • By implementing Runnable interface.


By Extending the Thread Class:

class Multithread extends Thread

{

public void run()

{

System.out.println(“My thread is running”);

}

public static void main(“String args[])

{

Multithread obj=new Multithread();

obj.start();

}

}

Output:

My thread is running

 

By Implementing Runnable Interface:

class Multithread implements Runnable

{

public void run()

{

System.out.println(“My thread is running”);

}

public static void main(“String args[])

{

Multithread obj=new Multithread();

Thread tobj=new Thread(obj);

obj.start();

}

}

 Output:

My thread is running

 

Creating Multiple Threads:

The java program may create any number of threads. Normally, multiple threads are used for animation. Multiple threads can access the same object or method. There is no guarantee which thread will access an object at a given time, which can lead to unpredictable results. In the case of two or three threads sharing the same object, then only one thread must access the object at a time. In order to  do this, java synchronization logic can be applied which is make use of the keyword, synchronized, with which an object can be locked to execute  a block of code preventing other threads from accessing that particular object. That is, the method takes control of the “monitor” of the object.


Thread Priorities:

Java assigns a priority to each thread that determines how that thread should be treated with respect to others. A higher priority thread does not run faster than a lower priority thread. Instead, a thread’s priority is used to decide when to switch from one running thread to the next.

Thread priorities can be changed according to the importance of the task that the thread is executing.


In Java, each thread is assigned a different priority that will decide the order (preference) in which it is scheduled for running.

Thread priorities are represented by a number from 1 to 10 that specify the relative priority of one thread to another. The thread with the highest priority is selected by the scheduler to be executed first.

The default priority of a thread is 5. Thread class in Java also provides several priority constants to define the priority of a thread. These are:

 

1. MIN_PRIORITY = 1
2. NORM_PRIORITY = 5
3. MAX_PRIORTY = 10

When multiple threads are ready for execution, the highest priority thread is selected and executed by JVM. In case when a high priority thread stops, yields, or enters into the blocked state, a low priority thread starts executing.

If any high priority thread enters into the runnable state, it will preempt the currently running thread forcing it to move to the runnable state. The highest priority thread always preempts any lower priority thread.

Priority is set using the method, setPriority(n) where n is an integer ranging from 1 to 10. The current priority of a thread can be got by using the getPriority() method.


 


Post a Comment

0 Comments