Learn Java – Java Tutorial for Complete Beginners

What is Java?

Java is a general-purpose programming language and a platform. Java is a concurrent, object-oriented, robust, and secured computer-programming language. It is called a platform because it has its own API and runtime environment known as, Java Runtime Environment (JRE).  It is used by developers all over the world and it can run on all platforms that support Java. It is one of the most used programming languages and is reportedly used by more than 9 million developers.

Where is it used?

Java is a computer programming language which is currently used in more than 3 billion devices. Some of the devices where Java is used are Mobile, Smart Card, Robotics, Games, and Embedded System. Various desktop, web, and enterprise applications such as media player, irctc.cp.in, antivirus, banking applications, and acrobat reader also use Java.

Types of Java Applications

Java is mainly used to create 4 types of applications:

  1. Standalone Application

Standalone Application is the traditional desktop or window-based software that is installed on every system. It is the platform application that is installed independently in each operating system. The standalone application doesn’t need the operating system’s services to run as a separate computer process. Antivirus, acrobat reader, and the media player are some examples of a standalone application. Lang, Text, RMI, and Beans are some Java packages used to create such an application.

  1. Web Application

A Web application is an application that runs on the server side and makes a dynamic page. Such an application runs in a web browser and is a client-server program. Webmail, online auctions, wikis, etc. are some examples of web applications. Some of the technologies that are used in Java for creating such an application are Spring, JSF, Servlet, Struts, and JSP.

  1. Enterprise Application

Enterprise Application is such an application that is distributed in nature. They are complex, object-oriented, scalable, and component-based. Such application is mostly used in big businesses in order to solve business-related problems and achieve the organization’s objective. Banking applications are some example of this application. EJB is an important Java tool used to make enterprise application.

  1. Mobile Application

As the name suggests, a mobile application is an application that is made for cell phones. They are also known simply as an app and are created to operate on a smartphone or tablet computer. A mobile application is designed to provide services similar to a computer on mobile devices. Android and Java ME are the two tools used to make a mobile application.

Java Platforms

The four main editions or platforms of Java are:

  1. Java Standard Edition ( Java SE )

Java SE is a platform that is used to create and deploy the codes for computer and server environments. This edition helps the developers to create and operate Java applications on desktops and serves. It is the core Java programming platform and contains all of the libraries that the programmers should know about. Some of the packages used in this edition are java.lang, java.math, java.util, java.sql, java.swing, and org.omg.CORBA. String, Inner classes, Networking, Regex, AWT, Collection, OOPs, I/O Stream, Multithreading, Reflection, Exception, and Swing are the core topics included in it.

  1. Java Enterprise Edition ( Java EE )

Java EE is a platform that is specified for enterprise and web services. It is an extension of the Java SE platform and is mainly focused on enterprise feature. It includes topics likes Enterprise JavaBeans, JSP, JDBC, Servlets, Connectors, JPA, EJB, and Web Service. It has all the features of Java SE along with additional libraries in order to provide new functionality to the programmers. Java EE helps to develop software based largely on modular components.

  1. Java Micro Edition ( Java ME )

Java ME is a platform that is used to create an application for mobile devices. It is a micro platform and is used to develop code for sensors, printers, cell phones, and other mobile devices. It is also known as a micro version of Java SE and has functionalities are that specific to mobile devices. Java ME provides a flexible environment and robust security and helps to develop and deploy programs that are portable in nature.

  1. JavaFX

JavaFX is a platform used to create desktop and internet applications that can be operated in a number of devices. It is a set of graphics and packages that help the programmers to create, test, and operate applications that can be operated in various different platforms. It supports desktop and web browsers in various operating systems including Microsoft Windows, macOS, and Linux. It was created in order to perform as the standard GUI library for Java SE replacing Swing. JavaFX included classes and interfaces that are written in native Java code and is designed to be user-friendly.  if Important core Java topics

  • Control Statements

If-else statement

Java If-else statement is used to check if a Boolean condition is true or false. The types of Java If statements are:

  1. If statement

In Java, if a statement is used to test whether a Boolean expression is true or false. If the condition is true, if the command will be executed and if the condition is false, then the first set of code after the end of the statement will be executed.

  1. If-else statement

In this statement, if the Boolean expression is true then if the command of the code will be executed, and else block will be executed if the expression is false.

  1. If-else-if ladder

This statement is used in order to test multiple expressions. Multiple numbers of if-else order can be used in a single time so this statement is also called if else if ladder. In this statement, the order gets executed immediately after the condition is met and the rest is ignored. If the condition is not met, the then else block of the order gets executed. This way the statement helps the developer to check a wide range of mutually exclusive possibilities.

  1. Nested if statement

In Java, if or else statement can be used inside another if or else statement. If an order gets executed as long as the condition is met and if the condition is not met else order gets executed.

Example: If-else statements in Java

Switch Statement

Java Switch Statement is used to check conditions based on a single integer and enumerated value. It is used to execute a single statement from multiple expressions. Byte, Character, Short, and Integer are some data types that the switch statement works with. It is fall-through and is similar to the if-else-if ladder statement.

Loops in Java

Loops are an important tool used in programming languages in order to execute a set of functions again and again after some expressions become true. The main types of loops used in Java are:

# For Loop

A for loop is used to provide a short and easy way to debug the stricter of the loop in Java. It writes the structure of the loop in a concise was and checks the condition in one line. Java for loop is further divided into three types. They are:

  1. Java Simple For Loop

Simple for loop is used to initiate a variable and check condition. It is similar to a for loop in other programming languages and checks the increment or decrement value in the same way.

  1. Java for-each loop

Java for-each loop doesn’t need the increment value so it is easier to use than simple for loop. It uses subscript notation and works on elements basis. It does not work on an index and is used to return the element one by one in a defined variable and traverses an array or a collection.

  • Java Labeled For Loop

This loop is a type of for loop that is labeled and is used for a specific purpose. It is used to break or continue the loop in a specific condition.

# While Loop

Java While Loop is used when the number of iteration is not fixed. It performs a part of the program many times.

Java Infinitive While Loop

If a statement is passed as true in a while loop, the loop will become an infinitive while loop.

# Java Do While Loop

Like the while loop, do while loop is also used to perform a part of the program several times. The do-while loop is used when the loop must be executed at least a single time and the number of iteration is not fixed.

Java Infinitive do-while Loop

If a statement is passed as true in a do-while loop, the loop will become an infinitive do-while loop.

Example: for, while and do while in Java

# Break Statement

Java break statement is used to break the loop in java. A loop ends immediately after a break statement is encountered. After the loop gets terminated, the program will continue from the next part. It is also used to break the switch statement and inner loops.

# Continue Statement

Java Continue Statement can be used in both for and while loop to continue the loop. It is used to continue the flow of the program and is used to immediately jump to the next iteration of the loop. It can be used with an inner loop as well.

# Comments Statement

Java Comments Statements are those statements which provide information about a method, variable, or class. It is also used to hide code and is not executed by the interpreter or the computer.

The types of Java comments are:

  1. Single Line Comment

Single line comment explains only a single line.

  1. Multi-Line Comment

Multi-Line Comment explains multiple lines in a code.

  1. Documentation Comment

Documentation comment is used to explain an API by using the Javadoc tool.

Example: Switch, Break, Continue & Comment Statements in Java

Java OOPs Concepts

In this chapter, we will deal with the basic concept of Object Oriented Programming (OOP). OOP is a programming paradigm which is based on objects. It deals with other concepts such as data binding, polymorphism, and inheritance.

The first object-oriented programming language is Simula but the first true programming language to be fully based on an object is regarded as Smalltalk. The main concept of OOP is that everything in the language is represented as an object. Some of the other popular object-oriented programing languages are C#, Python, Java, PHP, and C++.

The main goal of OOP is to implement real-world entities such as classes, inheritance, abstraction, polymorphism, and objects.

Object-oriented Programming System (OOPs)

An object can be simply defined as any real-world entity such as pencil, paper, clothe, and so on. Object-oriented programming helps to design a program with the use of objects. This makes the development and maintenance of software easier. Some of the concepts that OOP deals with are:

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

Object

In simple words, an object is any type of physical and logical entity that has state and behaviors. Pencil, clothe, desk, mouse, etc. are some common examples of objects in the real world. The objects in the real world and the software objects have the same characters, that is, state, behaviors, and identity. State of an object is represented through attributes and reflects the features of an object.

On the other hand, the behavior of an object is represented through methods and reflects the response of an object with other objects. Similarly, identity refers to the unique name of the object that differentiates it from other objects and helps in the interaction between objects. An object resides in memory and has an address. They are an instance of a class that can communicate without the knowledge of data or code of each other.

Class

A class is a logical entity which has more than one object. Class doesn’t take up any space and are the collection of objects. They are the blueprints or prototypes which are used to make a single object. The features or methods that are common in a type of objects are represented by a class. A class has default access and its name begins with an initial letter.

A class contains three types of variables and they are, Local variables, Instance variable, and Class variables. Local variables are those variables that are inside methods and they are destroyed when the method gets completed. Instance variables are variables that are outside a method but are accessible from inside any method. Finally, class variables are variables that have a static keyword and are outside a method.

Inheritance

Inheritance is known as the phenomena in which an object gains properties of the parent object. It helps to use the code again and again and achieve runtime polymorphism.

Here, the superclass is those classes whose properties are inherited and subclasses are those classes that inherit the properties of the superclass. With the use of inheritance, we can easily reuse the field and methods of the existing class to create a new class. This phenomenon is known as reusability. Inheritance helps to manage the information in a hierarchical order.

There are five types of inheritance in Java and they are, Single Inheritance, Multilevel Inheritance, Hierarchical Inheritance, Multiple Inheritance, and Hybrid Inheritance.

Polymorphism

Polymorphism is the process of performing a task in various different methods. Method overloading and overriding are generally used in Java to achieve polymorphism. Polymorphism can be defined as the ability of an object that helps them take various different forms. It is mostly used in OOP when a child class object is referenced by using a parent class. Any object that can pass more than a single IS-A test is known to be polymorphic. All objects in Java pass this test so they are all polymorphic. The reference variable is the only method to access an object and the reference variable can only be of a single type. The kind of reference variable cannot be changed once it is declared.

Abstraction

Abstraction is the process of keeping the internal details a secret and only making the functionality visible. It is the quality of dealing with only ideas, not the events. In other words, it can be defined as a process to keep the implementation details a secret and only make the information about the functionality available. It helps the user to understand the function of the object rather than how the object performs its function. Abstract class and interface are used in Java to achieve abstraction.

Encapsulation

Encapsulation is the process of wrapping all the code and data and making a single unit from them. In it, the variable of a class will only be accessible through the methods of their current class and are hidden from other classes. It works as a kind of a shield to protect data from being accessed by the code outside. It is also known as data-hiding as it hides the data in a class from other classes. It is achieved by declaring all the variables in the class as private and writing public methods to find out the values of the variables. Java bean is an example of such encapsulation as all data members are private here.

Advantages of OOPs over Procedure-oriented programming language

  1. OOPs makes it easier to develop and maintain software, unlike Procedure-oriented programming language in which it becomes difficult to manage the software as the number of code increases.
  2. In OOPs, data can be hidden but in the Procedure-oriented programming language, the data can be accessed from anywhere.
  3. OOPs provide solutions to real-world problems and it has the ability to simulate real-world events.

Dissimilarities between an object-oriented programming language and an object-based programming language

The only difference between OOP and object-based programming language is that unlike OOP, the object-based programming language does not have the feature of inheritance. Some of the examples of such language are VBScript and JavaScript.

Java Naming Conventions

Java naming convention is the process of providing the identifiers unique names such as variable, package, class, method, and constant. It is not compulsory to name the identifiers so it is not called rule and is known as conventions. The names of all the interfaces, methods, classes, fields, and packages of Java programming language are decided on the basis of the Java naming convention.

Advantages of naming conventions in java

Java naming conventions make it easier to read the code. It helps to save programmers time while reading the code and figuring out the functions of each code.

Guidelines while using naming conventions:

Class name: a class name should always be a noun and should start with an uppercase letter.

Interface name: An interface name should be always an adjective and should also start with an uppercase letter.

Method name: a method name should always be a verb and should start with a lowercase letter.

Variable name: a variable name should start with a lowercase letter.

Package name: a package name should also start with a lowercase letter.

Constant name: a constant name should have all uppercase letters.

CamelCase in Java Naming Conventions 

In Java, camelcase syntax is used to name class, method, interface, and variable. In this syntax, if a name is composed of two different words then the second word starts with an uppercase letter.

Object and Class in Java

In this chapter, we will deal with Java objects and classes. Java is an object-oriented programming language so objects and classes are used to design a program. An object can be both physical and logical entity but class is only a logical entity.

Object in Java

An object is any type of physical and logical entity that has state and behaviors. It can be both tangible and intangible. An object has an address and occupies memory. They can communicate without the knowledge of data or code of each other.

The major characteristics of an object are:

  • State: It indicates the value of an object. It is represented through attributes and reflects the features of an object.
  • Behavior: It indicates the functionality of an object. It is represented through methods and reflects the response of an object with other objects.
  • Identity: Identity is the unique way to identify each object. The identity of an object is not always seen by the external user and it is implemented through a different ID. It refers to the unique name of the object that differentiates it from other objects and helps in the interaction between objects.

Objects are an instance of a class. A class is a logical entity which has more than one object and they are the blueprints which are used to make a single object.

Some other definitions of an object are:

  • An object can be defined as a real-world entity.
  • An object can be defined as a runtime entity.
  • An object has state and behaviors.
  • Objects are an instance of a class.

Class in Java

A class is a logical entity which has more than one object with common characteristics. They are the blueprints which are used to make a single object and don’t take up any space. The features or methods that are common in a type of objects are represented by a class.

A class in Java contains:

  • Fields
  • Methods
  • Constructors
  • Blocks
  • Nested class and interface

Instance variable in Java

An instance variable is such type of variable which is created inside a class but outside a method. They don’t consume any memory at compile time and only consumes memory when at runtime. As it only gets memory when an instance is created, it is called an instance variable.

Method in Java

A method in Java is like a function. It is used to define the behavior of an object.

Advantage of method

  • Optimization of code
  • Reuse of code

New Keyword in Java

The new keyword is used in Java for allocation of memory during the runtime. All objects consume memory in the Heap memory area.

Ways to initialize an object

  1. Through reference variable
  2. Through method
  3. Through constructor

Ways to create an object in Java

Some of the ways to create an object in Java are:

  • Through new keyword
  • Through new instance method
  • Through clone method
  • Through deserialization
  • Through factory method

Anonymous object

The simple meaning of anonymous is nameless. An anonymous object is an object without any reference. It is only used when an object is created and the object is only going to be used once.

Constructor in Java

A constructor in Java is defined as a block of codes. It is similar to a method and is called when an instance of an object is created and the allocation of memory for the object is done. It is used to initialize the object.

When is a constructor called?

A constructor is called each time a new keyword is used to create an object. It is also known as default constructor. Its main objective is to construct the value when an object is created so it is called the constructor. Java compiler automatically creates a default constructor for a class if it does not have any so it is not compulsory to create a constructor for a class.

Rules for creating Java constructor

The two rules to follow while defining a constructor and they are:

  1. The name of the constructor must be the same as the class name.
  2. A constructor should not have an explicit return type.

Type of Java constructors

The two types of constructors in Java are:

  1. Default or No-arg constructor
  2. Parameterized constructor

Java Default Constructor

A default constructor is such type of constructor that doesn’t have any parameter. The main function of the default constructor is to assign default values to objects like 0, null, etc. on the basis of the type.

Java Parameterized constructor

A parameterized constructor is a constructor with a specific number of parameters. It is used to provide separate values to the different objects.

Constructor overloading in Java

A constructor is like a method in Java, the only difference is it does not have a return type. So it can be overloaded like a method as well. Constructor overloading in Java is the process if creating more than a single constructor but with various parameter lists. Each of the constructors is arranged in such a way so that each of them carries out different tasks. The different constructors are separated by the compiler on the basis of the number and the types of parameters in their list.

Difference between a constructor and a method in Java

Several differences can be found between a constructor and a method. Some of them are:

  1. A constructor is mainly used to initialize the state of an object, whereas the main function of a method is to expose the behavior of an object.
  2. A constructor should not have return type but a method should.
  3. A constructor is invoked implicitly but a method is invoked explicitly.
  4. A default constructor is provided if there is not any by the Java compiler, whereas a method is not ever provided by the compiler.
  5. A constructor name is always the same as the class name but a method name may or may not be similar to the class name.

Java Copy Constructor

Copy constructor does not exist in Java. However, as in C++, the value of one object can be copied to another object in Java as well.

Some of the most used processes in Java to copy the value of one object to another are:

  • Through constructor
  • By assigning the value of one object to another
  • Through the clone method of an object class

Copying the value without constructor

There is no need to create a constructor when copying the value of one object to another by assigning the value of the first object to the second object.

A constructor does not have a return type but it returns the current class instance. It can also be used as a method to perform other various tasks such as starting a thread, object creation, and calling a method.

Java Static Keyword

The static keyword in Java can be applied with methods, variables, nested class, and blocks. It belongs to a class rather than an instance of the class and is mainly used for managing memory.

The types of static are:

  1. Variable or class variable
  2. Method or class method
  3. Block
  4. Nested Class

Java static variable

A static variable is any variable that is declared as a static. It is used to cite the common property of all the objects. Such a variable only gets memory a single time in the class area during the time of class loading.

The advantage of static variable

A static variable helps to save memory. This means it makes a program memory efficient.

Java static method

When a static keyword is used in a method, then it is called a static method. It can be referred to without an instance of a class as it belongs to a class not the object of a class. A static method can change the value of a static data member as it can easily access it.

Restrictions for the static method

There are a few restrictions while using the static method and they are:

  1. The static method cannot function with non-static data members.
  2. It cannot call a non-static method directly and cannot be used in a static context.

Why is Java’s main method static?

The Java main method is static it does not require an object. If a non-static method was used then an object must be created before calling the main method which will take up extra memory.

Java static block

Java static block is executed at first and then only the main method is executed during the time of class loading. It initializes the static data member.

This Keyword in Java

In Java, this keyword means a reference variable that cites the current object. It is used for various different functions.

Usage of This Keyword in Java

Some of the main uses of this keyword in Java are:

  1. This keyword is used to cite the current class instance variable.
  2. It is used to refer to the current class method or implicitly.
  3. It is used to refer to the current class constructor.
  4. In the method call, this keyword can be passed as an argument.
  5. It can also be passed as an argument in the constructor call.
  6. This keyword is used to return the current class instance from the method as well.

This: to cite the current class instance variable

This keyword is used to cite the current class instance variable. It helps to solve the problem of ambiguity in the case where there is ambiguity between the parameters and the instance variables.

This: to refer to the current class method

This keyword can be used to refer to the current class. The compiler adds this keyword even if it is not used in order to invoke the method.

This: to refer to the current class constructor

This keyword can be used to refer to the current class constructor as well. It is mainly used to construct chaining or to use the constructor again and again.

The real usage of this keyword in the constructor call

This keyword is used to maintain a chain between the constructors so that the constructors can be reused. In other words, it creates a constructor chaining.

This: to pass as an argument in the method

This keyword can also be used to handle an event. In the method, it is used to pass an argument.

Application of this that can be passed as an argument

This keyword can be used to use one object again and again in various different methods. It can be used to provide a reference of a class to another class while handling an event.

This: to pass as an argument in the constructor call

Like in the method, this keyword can be passed as an argument in the constructor call as well. It helps to use one object in many classes.

This: to return the current class instance

This keyword is used to return the current class instance from the method if the return type of the method is the class type.

Inheritance in Java

Inheritance is a significant feature of an Object-oriented programming system (OOPs). It is the process by which one object acquires the features and behaviors of the parent object. In Java, inheritance is used to build new classes on the basis of already created classes. The methods and featured of the parent class can be used to create new classes through inheritance. The new classes can also be provided with new fields and methods.

This way Inheritance helps in the reusability of codes multiple times and to achieve runtime polymorphism. The subclass inherits the properties of the superclass. The fields and methods of the existing class can be reused again and again to create new classes through the use of inheritance. Single Inheritance, Multilevel Inheritance, Hierarchical Inheritance, Multiple Inheritance, and Hybrid Inheritance are the types of inheritance that exist in Java. Inheritance helps to manage the information in a hierarchical order.

Inheritance represents a parent-child relationship which is called the IS-A relationship. IS-A relationship is the way of representing similar types of objects.

Why is inheritance used in Java?

  • Used for method overriding
  • Used for code reusability

Terms used in Inheritance

  • Class: A class is defined as a collection of objects which have common features. It refers to a blueprint or template which is used to create an object.
  • Subclass/ Child class: Subclass refers to a class that inherits other classes. It is also known as a derived class, child class, or extended class.
  • Superclass/ Parent class: Superclass is the class from which a subclass inherits the properties from. It is also known as parent class or base class.
  • Reusability: Reusability is a process that helps to use the fields and methods of the existing class again and again in creating a new class. It facilitates the use of the same methods and fields that have been already defined in a previous class.

Types of inheritance in Java

Inheritance can be further classified into five types on the basis of class in Java. They are:

  • Single Inheritance:

The single inheritance is such type of inheritance in which the properties of one superclass is inherited by a single subclass.

  • Multi-level Inheritance:

In multi-level inheritance, a subclass inherits the properties of another subclass that has inherited the properties of a superclass. In other words, a subclass that initially inherited its properties from a superclass will act as a superclass to other subclasses.

  • Hierarchical Inheritance:

The hierarchical inheritance is such type of inheritance in which one class serves as a superclass for multiple subclasses to inherit the properties from.

  • Multiple Inheritance:

In multiple inheritance, one subclass inherits the properties of more than one superclass. That means a subclass derives properties of two or more than two-parent classes.  Java does not support multiple inheritance of class. But it can be achieved through interfaces.

  • Hybrid Inheritance

The hybrid inheritance is the mix of more than one of the above inheritance. Hybrid inheritance is not supported in Java as well but like multiple inheritance, it can be achieved through interfaces.

The reason why multiple inheritance is not supported in Java:

Multiple inheritance is not supported in Java to simplify the language and to reduce complexity.

Aggregation in Java

An aggregation is a condition in which a class has an entity reference. It represents a HAS-A relationship. It is mainly based on usage and helps to reduce duplication of code as well as to identify and remove bugs from the program.

Usage of aggregation

To reuse the code

When is aggregation used?

  • When there is no IS-A relationship, aggregation can be used for code reusability.
  • Aggregation is the best way to maintain throughout the lifetime of the objects in the cases in which inheritance cannot be used because of the lack of an IS-A relationship.

Java Polymorphism

Polymorphism is the ability of an object that helps them take various different forms. To put it simply, it is the process of performing a task in various different methods. In Java, method overloading and overriding are used to achieve polymorphism.

Method Overloading in Java

In the situation in which a single class has different methods with the same name but dissimilar parameters, then it is called Method Overloading. Method overloading is used in Java to figuring out the program quickly as it allows different methods to have the same name, but different signatures. The signature can be differentiated through the number of input parameters or the type of input parameters. It helps to increase the readability of the program as only one operation that has the same name as the methods have to be performed.

Advantages of Method Overloading

The main advantage of method overloading is that it makes the program easily readable. There is no need to create and remember different named for functions doing a similar thing by using method overloading.

Different ways to overload the method

The two ways to perform method overloading in Java are:

  1. By changing the number of arguments
  2. By changing the data type

Why is method overloading not possible only by changing the return type of the method?

The reason because of which method overloading is not possible in Java only by changing the return type of the method is ambiguity.

Can Java main method be overloaded?

Yes, method overloading can be used in the main methods to have any number of main methods in a class.

Method overloading and Type promotion

By using method overloading, a single type can be promoted to another type implicitly if there is not a matching data type.

Method Overriding in Java

In Java, method overriding is the case in which a subclass/ child class has the same method as of the parent class. This means if a child class provides the same method that the parent class, then it is called method overriding. It is the property that allows the child class to carry out a specific method that has already been carried out by its parent class.

Such overridden method is not seen in the superclass and is not called until the subclass uses the super keyword. Method overriding is when a method in a child class has a similar name, signature, and return-type as a method in its parent class. It is used in Java to achieve runtime polymorphism.

Usage of Java Method Overriding

The various usage of method overriding in Java are:

  • Method overriding is used in Java to achieve runtime polymorphism.
  • Method overriding is used to specify methods that will be common to all of its derivatives and that has been already provided by the parent class.
  • Method overriding is used to invoke methods of any subclasses even without the knowledge of the type of the child class object.

Rules for Java Method Overriding

  1. The method in a subclass should not have a different name as in the superclass.
  2. The method in a subclass should have the same parameter as in the superclass.
  3. There must be an IS-A relationship to perform method overriding.
  4. Final methods and private methods cannot be overridden.

Can a static method be overridden?

A static method cannot be overridden which can be proved by runtime polymorphism.

Why cannot static methods be overridden?

A static method cannot be overridden because it is bound with class. A static method belongs to the class area not with object area so method overriding cannot be performed on it.

Can Java main method be overridden?

As the main method is also a static method, it cannot be overridden.

Dissimilarities between Method overloading and Method overriding in Java

  1. In method overloading, there is a similar method with different signatures. Whereas in method overriding, there is a similar method with the same signature but different classes.
  2. Method overloading helps to achieve compile-time polymorphism and method overriding helps to achieve runtime polymorphism.
  3. Method overloading increases the readability of the program. On the other hand, method overriding specifies methods that will be common to all of its derivatives and that has been already provided by the parent class.
  4. A method is overloaded within a class, however, a method is overridden in two different classes that have IS-A relationship between them.
  5. The parameter should be different in method overloading but it should be similar in method overriding.

Covariant Return Type

In the previous versions of Java before the JDK 5.0, it is not possible to override a method through changing the return type. The name, parameters, and return type of the method that is being overridden in the subclass should be exactly similar to that of the superclass method. But after Java 5.0, a method can be overridden by changing the return type. However, the subclass’s return type should be sub-type of the parent’s return type. This helps the programmers to have more specific return types when performing a method overriding. It helps to make the program easily readable, more usable, and easy to maintain.

How is covariant return types implemented?

The previous versions of Java did not allow method overloading based on return type but it is possible to overload a method on the basis of return type in JVM. This is because it uses the full signature of a method to implement a covariant return type and solves the problem. The meaning of the term ‘full signature’ is the inclusion of return type and argument types. This means a single class can have more than one methods separated only by return type.

Super Keyword in Java

In Java, a super keyword is a reference variable. It is used to refer to superclass objects and is called ‘super’ because of the use of inheritance in Java. An instance of a superclass is created when an instance of a subclass is created. Such instance of a superclass is referred using super reference variable.

Usage of Super Keyword in Java

  1. Use of super keyword to refer superclass instance variables.
  2. Use of super keyword to invoke the superclass method.
  3. Use of super keyword to invoke the superclass constructor.

Use of super keyword to refer superclass instance variables

In Java, the super keyword can be used to access the data member or field of a superclass. This can be done when a superclass and a subclass have the same data members. This creates a possibility of ambiguity for the JVM.

Use of super keyword to invoke a superclass method

The super keyword can be used to invoke a superclass method as well. When a method is overridden and both the subclass and superclass have the same method, the super keyword can be used to invoke the method to resolve ambiguity in the program. This way super keyword is used to invoke the superclass method.

Use of superclass to invoke the superclass constructor

The super keyword can also be used to invoke a superclass constructor. Depending on the situation, a super keyword can invoke both parametric and non-parametric constructors.

Instance Initializer Block

Instance initializer block is used to initialize the similar parts of different constructors of a class. It is executed when an instance is created to declare the instance data member. An instance variable can be initialized directly, however, the instance initializer block is used to declare the instance variable in order to perform extra operations. It always gets executed before a constructor and is placed above the constructors. There is no necessity to include the instance initializer block in the classes.

Why is an instance initializer block used?

An instance initializer block is used so that various other operations can be performed while initializing an instance variable.

Rules for instance initializer block

  1. An instance initializer block is created whenever a class is initialized.
  2. An instance initializer block is called only after the superclass constructor is invoked.
  3. The instance initializer block is invoked in the same order as they appear in the program.

Final Keyword in Java

In Java, a final keyword is a non-access modifier that is used to restrict the user. The final keyword can be used in a variable, in a method, and in a class. The final keyword restricts the user from modifying the code. It is represented by all uppercase and the words are separated using underscore. When a final keyword is used, it keeps the part of the code constant in which it has been used. It is used to keep the value of a part of the code constant throughout the execution of the program.

Java final variable

The final keyword is declared with a variable in order to stop the value of the variable from being modified. The final keyword makes the variable a constant when initialized. A final variable is initialized when it is declared by using an initializer or an assignment statement. If a final variable is not initialized, the compiler will face a compile-time error. A reference final variable is a final variable that is a reference to an object. Similarly, a local final variable is the final variable that is initialized inside a method or a block or a constructor.

Java final method

A final method is a method that has been declared with a final keyword. The method that is declared with a final keyword cannot be overridden. When an object class is declared with a final keyword, several of its methods become final methods. When a final method is declared, the same must be done throughout all the subclasses.

Java final class

A final class can be defined as the class that has been declared with a final keyword. When a final keyword with declared in a class, the class cannot be inherited. The final class is used to prevent the extension of the class and in order to create an immutable class.

Can a final method be inherited?

A final method can be inherited but the overriding of a final method is not possible.

What is the meaning of a blank or uninitialized final variable?

A final variable is known as a blank final variable when it is not initialized at the time of declaration. A black final variable can be initialized inside both the constructor and the instance initializer block. If there is a presence of two or more than two constructors, then a blank final variable must be initialized in all of the constructors. If not done so, the program will face a compile-time error.

Can a blank final variable be initialized?

A black final variable can be initialized in a constructor.

Static blank final variable

The final variable that is initialized inside a static block is known as a blank final static variable. It is not initialized at the time of declaration.

What is the meaning of a final parameter?

The parameter which has been declared with a final keyword is known as a final parameter. The value of the final parameter cannot be changed.

Can a constructor be declared as a final constructor?

A constructor is cannot be ever inherited so it cannot be declared as a final constructor.

Polymorphism in Java

The simple meaning of polymorphism is many forms. In Java, polymorphism is the process of performing a task in various different methods. It is the ability of an object that helps them take various different forms. It can be achieved through method overriding and method overloading. There are two kinds of polymorphism in Java.

They are runtime polymorphism and compile-time polymorphism. Method overloading in the static method is a type of compile-time polymorphism. In this chapter, we will deal with runtime polymorphism.

Runtime polymorphism in Java

Runtime polymorphism is achieved in Java through method overriding. It is a process in which a method overriding call in resolved at runtime, not at compile time. It is also known as Dynamic Method Dispatch. When an overridden method is called through a parent class reference, Java determines whether to execute the parent class method or the child class method.

This decision is taken by Java on the basis of the object being referred to at the time the call occurs. This whole process takes place at runtime, not at compile time. In this process, a parent class reference variable can also refer to a child class object. This phenomenon is known as upcasting.

Upcasting

When reference variable of a superclass refers to the object of a subclass, it is called upcasting. It is not usually necessary; however, upcasting is used to write code that only deals with the superclass.

Static binding and Dynamic binding

In Java, binding is the process of connecting a method call to a method body. There are two types of binding. They are Static binding/ Early binding, and Dynamic binding/ Late binding.

Understanding types of instance

  1. Variables have a type: Each variable can be divided into two types: primitive and non-primitive.
  2. References have a type
  3. Objects have a type: An object is an instance of a distinct Java class, but it is also an instance of its parent class.

Static binding

Static binding is the binding which is resolved at the compile time. It is used by private, final, and static methods and variables. It is better than dynamic minding in case of performance because it does not require extra overhead. It is bounded by the compiler during the compile-time.

The compiler is always accessible to the object of the local class so it doesn’t have any difficulty determining the object of the class. Type information is used by the static binding for binding. Method overloading is a type of static binding. It is also known as early binding.

Dynamic binding

Dynamic binding is the binding in which type of object is determined at runtime. In dynamic binding, it is not the compiler that decides the method to be called. Method overriding is a type of dynamic binding which is bonded during runtime based upon the type of runtime object. In this method, both subclass and superclass have the same method. Objects are used by the dynamic binding for binding. It is also known as late binding.

Java instanceof

Java instanceof operator is used to check the class of the object. It is used for checking whether a reference variable contains a given type of object reference or not. Java instanceof keyword is called a comparison operator as the keyword makes a comparison between instances with the types.  However, the class of the object cannot be checked dynamically using Java instanceof operator. It checks whether a Boolean expression is true or false. The keyword gives a compile-time error if the object with other classes which it doesn’t instantiate are checked.

Instanceof operator used with a variable that has a null value

If the Java instanceof operator is used with a variable with a null value, then it returns false.

Downcasting with Java instanceof operator

When reference variable of a subclass refers to the object of a superclass, it is called downcasting.  Downcasting is only possible through the use of Java instanceof operator. If we do it directly, we face compile-time error and if we use typecasting, then we face CalssCastException error. It involves a type check. Downcasting is used more regularly than upcasting and it is used to access specific behaviors of a child class.

Java abstraction

Abstract class in Java

A class that is declared with an abstract keyword is called an abstract class. All the abstract methods may or may not be present in the abstract class.

Before going into depth about abstract class, let’s first deal with the concept of abstraction in Java.

Abstraction in Java

Abstraction is the process of keeping the internal details a secret and only making the functionality visible to the user. It lets the user understand the function of the object rather than how the object performs its function. Only the important things are shown to the user and the internal details are hidden. It is the quality of dealing with only ideas, not the events by keeping the implementation details hidden.

The user won’t see the non-essential and irrelevant details and only deal with the required characteristic of an object through abstraction in Java. Abstraction helps to reduce the complexities of viewing the codes and can increase the reusability of code as well. It helps to avoid code duplication and increase the security of the program since only the essential parts are made visible to the user.

Methods to achieve abstraction in Java

There are two methods to achieve abstraction in Java. They are:

  • Abstract class
  • Interface

Abstract class in Java

An abstract class is such a type of class that is declared with an abstract keyword. There may or may not be the presence of all the abstract methods in the abstract class. There can also be the presence of concrete methods instead of abstract methods. An abstract class cannot be directly instantiated. In other words, an abstract class does not have an object.

A class that has at least one abstract method must be declared as an abstract class. There is always a default constructor present in an abstract class and it can also include a parameterized constructor. It can be used for some implementation of the interface. An abstract class must be inherited from another class so that it can be used.

Abstract method

A method that is declared without an implementation is called an abstract method. Such type of method should always be redefined in the child class. During the method declaration, the abstract keyword must be placed before the method name.

An abstract keyword is used to declare a method in the superclass as an abstract method when the programmer wants a class to contain a specific method but wants the actual implementation of that method to be determined by the subclass. It only has method signature but not a method body. Semi-colons are used instead of curly brackets.

Abstract class having constructor, methods, data members, and fields

An abstract class can have an abstract method, data member, fields, method body, main method, and constructor.

Interface in Java

An interface is a blueprint of a class that is used to achieve abstraction in Java. An interface contains abstract methods, static methods, constants, default methods, and nested types. It has methods and variables but the methods that are declared in interface only contain a method signature, not the method body.

It represents an IS-A relationship and cannot be instantiated like an abstract class. All methods of the interface need to be defined in the class unless the class is an abstract class. An interface contains behavior that a class implements and writing it is the same as writing a class. It specifies what a class needs to do but now the class needs to do it. It is related to capabilities. An interface can further extend to several interfaces.

Usage of Java interface

The main uses of an interface in Java are:

  1. Through the use of interfaces, abstraction is achieved in Java and is implemented.
  2. An interface can be used to support the functionality of multiple inheritance which is not supported in the case of class.
  3. Loose coupling can be achieved using interfaces.

How to declare an interface?

An interface is declared by the use of the interface keyword. Similarly, an implements keyword is used to implement the interface. Since all the methods in an interface are declared with an empty body and are public, it helps to achieve total abstraction in Java. All the fields are public, final, and static by default in an interface. All the methods declared in the interface must be implemented by the class that implements the interface.

Java 8 interface improvement

Since the Java 8 version, default and static methods can be included in an interface. This topic will be dealt with later.

Relationships between classes and interfaces

A class extends another class and an interface extends another interface. However, a class implements an interface. There are both similarities and differences between an interface and a class. Both class and interface can contain any number of methods and are written in a file with a .java extension. However, an interface cannot be instantiated and does not contain any constructors.

Multiple inheritance in Java by an interface

Multiple inheritance is not supported through class. But it can be achieved through an interface. A class implements multiple interfaces and an interface extends multiple interfaces. This is known as multiple inheritance.

In Java, multiple inheritance is not supported by a class but only possible by an interface. Why?

The fact that multiple inheritance is not supported in case of class because of ambiguity has already been dealt with in the inheritance chapter. However, multiple inheritance is supported in case of an interface. This is mainly because there is no ambiguity as the implementation of an interface is provided by the implementation of a class.

Interface Inheritance

An interface is implemented by a class. On the other hand, an interface extends another interface. To do so the extends keyword is used.

Java 8 default method in an interface

Since Java 8, a method body can be included in an interface. But in order to do so, it must be made a default method.

Java 8 static method in an interface

Java 8 has also added the feature of including a static method in an interface.

What is a marker or tagged interface?

A marker or tagged interface is an empty interface. Cloneable, remote, and serializable interfaces are tagged interfaces that have no member. They help the JVM to perform various important operations by providing useful information.

The nested interface in Java

An interface that is an extension of another interface is known as a nested interface. The details about nested interface will be dealt in the nested class’s chapter.

Dissimilarities between abstract class and interface

Abstract class and interface are both used to achieve abstraction and both cannot be instantiated. But there are various dissimilarities between an abstract class and an interface. They are:

  1. Type of methods:

An abstract class can have both abstract and non-abstract methods. However, an interface can only have abstract methods. It can also have static and default methods since Java 8.

  1. Supporting multiple inheritance:

An interface supports multiple inheritance but an abstract class does not.

  1. Type of variables:

An abstract class can include final, non-final, static, and non-static variables whereas an interface can only include final and static variable.

  1. Final variables:

An abstract class may have non-final variables but the variables that are declared in an interface are all final variables by default.

  1. Implementation:

An abstract class can implement an interface but an interface cannot implement an abstract class.

  1. Declaration:

An abstract class is declared by using an abstract keyword and an interface is declared by using an interface keyword.

  1. Multiple implementations:

An abstract class can extend another class and implement several interfaces but an interface can only extend another interface.

  1. Accessibility of data members:

An abstract class includes private and protected data members but an interface can only have public data members.

  1. Inheritance vs. Abstraction:

The extends keyword is used to extend an abstract class and the implements keyword is used to implement an interface.

Java encapsulation

Java Package

A package is a container of a group of related classes, sub-packages, enumerations, annotations, and interfaces. It is used for access protection as some of the classes in a package are exposed and otherss are kept hidden. It provides namespace management so it prevents naming conflicts with names in different packages. Packages are used to easily use and search classes, annotations, enumeration, and interfaces.

Packages can be further classified into two types, built0in packages, and user-defined packages. Built-in packages are the packages already present in Java such as java.lang, java.io, java.net, java.swing, java.util, and java.sql. User-defined packages are the packages that are defined by the users themselves to bundle a group of classes for their convenience. Creating user-defined packages helps the user to easily locate and use the classes, interfaces, annotation, and enumerations. Packages are created using the package keyword.

In this chapter, the process of how user-defined packages are created and used will be dealt with.

Benefits of Java package

The main advantages of using packages in Java are:

  1. Packages help to easily maintain, locate, and use the classes, interfaces, annotations, and enumerations as the related classes and interfaces are categorized together.
  2. In a package, some classes are easily accessible and others are protected from the user. So it provides controlled access.
  3. Packages remove naming conflicts by creating a new namespace.

How to access package from another package?

A package can be accessed from outside the package in three ways. They are:

  1. Import package.*
  2. Import package.classname
  3. Fully qualified name

 

  1. Using packagename.*

The classes and interfaces inside a package can be access from outside the package by using package.* But the subpackages of the package will not be accessible by using this method. The classes and interfaces of another package can be made accessible to the current page by using the import keyword.

  1. Using packagename.classname

By using packagename.classname to import a package from outside the package, only the declared class will be accessible.

  1. Using a fully qualified name

The fully qualified name is used to access classes and interface from outside the package when there are two classes with the same name in different packages. The fully qualified name of the class has to be used every single time to access it and only the declared class will be accessible. However, there is no need to import the package using this method.

Subpackage in Java

Subpackages are those packages that are inside another package. Subpackages are taken as a different package from the package that they are so that the classes are protected. The classes or interface of a subpackage lack the access privileges and they have to be imported explicitly.

Ways to load the class files or jar files

There are two methods used for loading the class files in Java. They are:

  1. Temporary way:
  • Through the classpath switch
  • Through setting the classpath in the command prompt
  1. Permanent way:
  • Through setting the classpath in the environment variables
  • By first creating the jar file first that contains all the class files. And then copy the created jar file in the jre/lib/ext folder.

How to put two public classes in a package?

Two public classes are put in a package by creating two java source files that contain one public class but naming them differently.

Access modifiers in Java

The keywords that are added to the definitions in order to change their meaning are called modifiers. In Java, there are two types of modifiers that are used. They are Access modifiers and Non-access modifiers.

Access modifiers are those modifiers that restrict the accessibility of class, variable, constructor, method, and data member. There are four types of access modifiers that are present in Java. They are private, default, protected, and public.

Besides the modifiers restricting the accessibility of the classes and variables, there are various other modifiers that perform various other functions in Java. Such modifiers are called non-access modifiers. Static modifier, final modifier, abstract modifier, synchronized modifier, and volatile modifier are some of the types of non-access modifiers.

Now let us deal with the types of access modifiers.

  1. Private access modifier

Private access modifier is visible only to the class in which they are declared. Other class cannot access the members or methods that are declared as private. Only methods and data members can be declared private using the private keyword, not the classes and interfaces.

Role of private constructor            

When a class constructor is declared as private, a user cannot create an instance of that class from outside the class.

  1. Default access modifier

Default access modifiers are declared by default in the situation where no access modifier is declared to a class, data member, and method. The classes, data members, and methods that are specified with a default access modifier are only accessible within the same package.

  1. Protected access modifier

The data members and methods that are specified with protected access modifier are visible to the same package and all the subclasses in a different package. Only methods and data members can be declared protected using the protected keyword, not the classes. The data members and methods that are specified with a protected access modifier are only accessible outside the package only through inheritance.

  1. Public access modifier

The classes, methods, and data members that are specified with public access modifiers are visible everywhere. It has the widest scope among all the access modifiers as there is no restriction on the accessibility of the classes and data members that are declared public using the public keyword.

Java access modifiers with method overriding

The methods that are overridden must be specified with public access modifiers to make it less restrictive. If the methods are declared as private or default then it becomes more restrictive and throws a compile-time error.

Encapsulation in Java

Encapsulation along with inheritance, polymorphism, and inheritance is a fundamental of OOP concepts. It is the process of wrapping all the code and data and making a single unit from them. In it, the variable of a class will only be accessible through the methods of their current class and are hidden from other classes.

Encapsulation is also known as data-hiding as it hides the data in a class from other classes. It works as a kind of shield to protect data from being accessed by the code outside. It is achieved by declaring all the variables in the class as private and writing public methods to find out the values of the variables. Java bean is an example of such encapsulation as all data members are private here.

Advantages of encapsulation in Java

  1. Data hiding:

Encapsulation is achieved by declaring all the variables in a class as private. This helps the user to hide the code and only make the essential parts visible.

  1. Easy to test the code:

It is easier to perform unit testing to test the codes that have been encapsulated.

  1. Flexibility is increased:

Encapsulation increases the flexibility to make the class read-only or write-only.

  1. Reusability:

Encapsulation makes the code easily reusable and new features can be easily added to the program.

Java Array

The simple meaning of an array is a collection of elements with the same features that have contiguous memory. In Java, an array is defined as an object that contains elements that have the same data type. Arrays are dynamically allocated and are referred by a common name. It can be used as a static field and a local variable. An array is a data structure where a fixed set of elements of similar types are stored. It is based on an index and has an index beginning from 0.

The length of an array can be found by using member length as they are objects. Both primitive data types and objects of a class can be included in an array on the basis of its definition. An array is used in a program by first declaring a variable to reference the array and then the type of the array is specified. The array in Java performs different functions than the array in C/C++ does. For loop or for each loop is most used to process an array.

Advantages of Java Array

  • Code optimization:

By defining an array, the programmer can easily retrieve and sort the data. Therefore, an array makes the code optimized.

  • Random access:

Any data can be located at any index position in an array.

Disadvantages of Java Array

  • Size limit:

In an array, only a fixed set of elements can be stored. The size of the array does not grow during runtime. But this problem can be solved by the use of the collection framework.

Type of Array in Java

There are two types of arrays in Java. They are:

  1. Single dimensional array
  2. Multidimensional array

Single dimensional array in Java

A single dimensional array is a collection of variables that have similar types. The variables in the array are denoted by a common name.  While cloning a single dimensional array, the new array will have the copies of the elements of the original array, not the references.

Multidimensional array

A multidimensional array is defined as arrays of arrays. In a multidimensional array, each element of one array holds the reference of another array. It is created in Java by using one set of square brackets per every dimension. The multidimensional array is also called jagged arrays. Data are stored in a matrix form in the multidimensional array, which is in row and column-based index. While cloning a multidimensional array, the new array with the elements of the original array also has references.

Passing Array to a method in Java

In Java, an array can be passed to a method like passing primitive type values to the method. This is done in order to reuse the same login on an array.

What is the class name of the Java Array?

As mentioned earlier, an array is an object. A proxy class is created for each array and the name of such class is known by using the getClass().getName() method.

Copying a Java Array

System class is an array method that is used to copy one array to another.

Java OOPs Misc.

Object Class in Java

An object class is the superclass of all the classes in Java. It is the topmost class from which every other class in Java is derived whether directly or indirectly. The class that does not extend any other class is directly derived from the object class and the class that extends other class is indirectly derived from the object class.  It can be used to refer any object whose type is not known. Every class in Java has the methods of the object class. An object class is the root of the inheritance hierarchy in Java.

Methods of the Object class

The methods provided by an object class are:

  • Public final class getClass()

This method returns the class object of this object. It is used to get metadata of this class and the actual runtime class of the object. It cannot be overridden.

  • Public int hashCode()

This method returns the hashCode number of the object and the distinct integers for distinct objects. It is native and uses an algorithm to convert the internal address of an object to an integer.

  • Public boolean equals (Object obj)

This method makes a comparison between this object and the given object.

  • Protected Object clone()

This method is used to make and return the clone of this object.

  • Public String toString()

This method converts an object to String and also provides a String representation of an object. It returns a string consisting of the name of the class of which the object in an instance.

  • Public final void notify()

This method wakes up a single thread but does not give up a lock on a resource.

  • Public final void notifyAll()

This method wakes up all the threads on the same object.

  • Public final void wait()

This method causes the current thread to go to sleep and wait until some other thread calls notify ().

  • Protected void finalize()

This method is called by the garbage collector when it decides that there are no more references to the object. It is called only for a single time before an object is being garbage collected.

Object Cloning in Java

Object cloning is the process of creating an exact copy of an object. An object is cloned in Java by using the clone() method. It is an object class method. The programmer must first implement the java.lang.Cloneable interface to the class whose object is going to be cloned. If not done so, the clone() method will throw a CloneNotSupportedException. By using the clone() method, a new instance of the class of the current object is created. The method also initializes all the fields of the object with the exact contents of the corresponding fields of the object.

Why use clone() method?

The clone() method copies the exact values of one object to another. If we don’t use the clone() method, to create an object as same as another object we must first use a new keyword and then assign the values of one object to another. This process takes up a lot of processing time. So to save the extra processing time, the clone() method is used as there is no need to write an explicit code to copy the value of one object to another using the method.

Advantages of object cloning

The clone() method is one of the most used and an easy way to copy objects. The various advantages of using the method are:

  • The clone() method removes the need for writing lengthy and repetitive codes to create an object with the same variables of an already created object.
  • The clone() method is an easy way to copy objects in the most efficient way if we are using it to a project that has already been created.
  • Along with copying an object, it is also the fastest method to clone an array.
  • The clone() method saves the extra processing time required if we copy objects using the copy constructor.

Disadvantages of object cloning

  • A lot of the syntaxes of the code have to be changed in order to use the clone() method. The programmer has to implement a Cloneable interface, define the clone() method, and handle the CloneNotSupportedException error, and call the Object.clone().
  • The programmer must tell the JVM that the clone() method can be performed on the object by implementing the Cloneable interface even if it does not have any methods in it.
  • The Object.clone () is protected, which means it is not visible and easily accessible. So the programmer must provide their own clone() method and call Object.clone() indirectly from the method.
  • The programmer does not have any control over the object construction as the Object.clone() does not invoke a constructor.
  • The super.clone() chain will fail if there is no clone() method defined in the parent class of the child class in which the programmer wants to write a clone method.
  • Shallow copying is only supported by the Object.clone() in Java. The programmer must first perform method overriding if a deep cloning is needed to be done.

Java Math class

Java Math Class provides several methods to perform mathematical calculations such as avg(),  round(), floor(), max(), tan(), abs(), and so on.

Java Math methods

The java.lang.Math method contains several methods that are used to perform basic numeric operations such as square root, cube root, logarithm, exponential, and trigonometric operations. The various Java methods are described below:

Basic Math methods

  • abs()

This method returns the absolute value of any type of the argument passed.

  • max()

This method returns the greater value out of the two arguments passed values.

  • min()

This method returns the smallest value out of the two arguments passed values.

  • round()

This method rounds off the passed argument up to closest decimal places.

  • sqrt()

This method returns the square root value of the argument passed.

  • cbrt()

This method returns the cube root value of the argument passed.

  • pow()

This method returns the value as base raised to the power of the exponent.

  • signum()

This method returns the signum value of the passed argument.

  • ceil()

This method is used to find the smallest possible value which is either greater or equal to the argument passed.

  • copySign()

This method returns the second argument with the sign of the first floating-point argument.

  • nextAfter()

This method returns the floating-point number adjacent to the first argument towards the second argument direction.

  • nextUp()

This method returns the floating-point value adjacent to d in the positive infinity direction.

  • nextDown()

This method returns the floating-point value adjacent to d in the negative infinity direction.

  • floor()

This method returns the closest possible value that is either less than or equal to the passed argument.

  • floorDiv()

This method returns the largest integer value that is less than or equal to the algebraic quotient.

  • random()

This method returns the double value with a positive sign that is greater than or equal to 0.0 and less than 1.0.

  • rint()

This method returns the double value that is closest to the argument passed and similar to the mathematical integer.

  • hypot()

This method returns the hypotenuse of the right-angled triangle without intermediate overflow or underflow.

  • ulp()

This method returns the least distance between two floating point numbers.

  • getExponent()

This method returns the unbiased exponent used in the representation of a value.

  • IEEEremainder()

This method returns the remainder when a dividend is divided by a divisor.

  • addExtract()

This method returns the sum of the specified method argument.

  • subtractExact()

This method returns the difference of the arguments passed.

  • multiplyExact()

This method returns the product of the arguments passed.

  • incrementExact()

This method returns the incremented value of the argument.

  • decrementExact()

This method returns the argument decremented by one.

  • negateExtract()

This method returns the negation of the argument.

  • toIntExact()

This method returns the value of the long argument.

Logarithmic Math Methods

  • log()

This method returns the logarithm value of the passed argument.

  • log10()

This method returns the base 10 logarithm value of the argument passed.

  • log1p()

This method returns the natural logarithm of the sum of the argument and 1.

  • exp()

This method returns the Euler’s number rose to the power of the passed argument.

  • expm1()

Trigonometric Math Methods

  • sin()

This method returns the trigonometric sine value of the passed argument.

  • cos()

This argument returns the trigonometric cosine value of the argument passed.

  • tan()

This method returns the trigonometric tangent value of the argument passed.

  • asin()

This method returns the arc sine value of the argument passed.

  • acos()

This method returns the arc cosine value of the argument passed.

  • atan()

This method returns the arc tangent value of the passed argument.

Hyperbolic Math Methods

  • sinh()

This method returns the hyperbolic sine of the argument arg.

  • cosh()

This method returns the hyperbolic cosine of the argument arg.

  • tanh()

This method returns the hyperbolic tangent of the argument arg.

Angular Math Methods

  • toDegree

This method converts the specified radians angle to equivalent angle measured in degree.

  • toRadians

This method returns the radians equivalent of the degree-argument passed.

Wrapper class in Java

A wrapper class is a class whose object contains primitive data types. The object in a wrapper class has field and primitive data types are stored inside the field. The wrapper class is used in Java to convert primitive data types into an object and vice-versa.

However, since J2SE 5.0, primitive data types are automatically converted into an object. Autoboxing is the feature that automatically converts primitive data types into object and unboxing is the feature that automatically converts an object into primitive data types.

The following are the eight primitive data types and their corresponding wrapper class:

Primitive Data Type                                      Wrapper class

char                                                                 Character

byte                                                                 Byte

short                                                                Short

long                                                                 Integer

float                                                                 Float

double                                                             Double

Boolean                                                           Boolean

Recursion in Java

Recursion is a process by which a method calls itself continuously directly or indirectly. The method which calls itself is known as a recursive method. Using recursion, a problem can be solved easily but it makes the code complex to understand and compact.

Call by value and Call by reference in Java

In Java, only the call by value method is used, not call by reference. Call by value is the process of calling a method that is passing a value. The change that occurs in the called method does not get affected in the calling method. Call by reference is not used in Java because objects and classes are always references and it will get complex if the programmer passes the object reference to methods. The original value is changed if the programmer has made changes in the called method in the situation of the call by reference. If the object is passed in place of a primitive value by the programmer, then the original value will get changed.

Java strictfp Keyword

The strictfp keyword is used in Java to achieve a similar result on all platforms while performing operations in the floating-point variable. Different floating-point values are obtained when a class file is run on different platforms as floating point calculations depend on the platform. To solve this problem and restrict floating-point calculations, the strictfp keyword was introduced in JDK 1.2 version. The strictfp keyword provides better control to the programmer over the floating-point calculations.

Legal code for strictfp keyword

The strictfp keyword can be used only with classes, methods, interfaces. It can be used with abstract classes and abstract interfaces as well.

Illegal code for strictfp keyword 

The strictfp keyword cannot be used with abstract methods, constructors, and variables. It cannot be used with any methods in an interface as all methods of an interface are abstract.

Creating API document by Javadoc tool

An API document is created in Java using the Javadoc tool. In order to post information for the class, constructor, data member, and method, /**…*/ documentation comment should be used. Both Javadoc tool and java file name are used to create an API document. Using the Javadoc tool, the programmer can create the Java code document in HTML file format.

Java command-line arguments               

Java command line arguments are those arguments that get passed during the time of running the Java program. When a user supplies command line arguments in the Java, the program wraps up the arguments in arguments array by checking the length of the arguments. The arguments are used as an input in Java and are passed from the console. The use of Java command line arguments is to check the nature of the program for different values.

Dissimilarities between object and class

The dissimilarities between an object and a class are described below:

  1. An object is an instance of a class. But a class is a blueprint from which objects get created.
  2. An object is a real-world entity, whereas a class is a collection of the same objects.
  3. An object is a physical entity; however, a class is a logical entity.
  4. The new keyword is used to create an object but the class keyword is used to declare a class.
  5. An object can be created as many times as necessary but a class can only be declared a single time.
  6. An object takes up memory during its creation but a class does not take up any memory when it is declared.
  7. Along with using the new keyword, an object can also be created using various other methods such as the newInstance() method and clone() method. But the only way to declare a class is by using the class keyword.

Dissimilarities between method overloading and method overriding in Java

  1. The main function of using method overloading in Java is to make the program more readable. But method overriding is used in Java to implement a specific method that has already been provided by its parent class.
  2. Method overloading takes place inside a single class, but method overriding takes place in two classes that have an IS-A relationship between them.
  3. The parameter is different in method overloading, whereas in method overriding the parameter is the same.
  4. Method overloading is a type of compile-time polymorphism; however, method overriding is a type of runtime polymorphism.
  5. Method overloading cannot only be performed by changing the return type of the method but the parameter must also be changed. On the other hand, method overriding can be performed by changing the return type.

String

In Java, string is an object and a sequence of characters. A sequence of char value is represented by it. Java string works the same way as an array of characters.

There are several methods provided by the Java string to carry out operations. Some of them are compare(), substring(), concat(), intern(), equals(), compareTo(), split(), replace(), and length().

There are three interfaces implemented by the java.lang.String class. They are Serializable, Comparable, and CharSequence interfaces.

CharSequence Interface

String, StringBuffer, and StringBuilder classes implement the CharSequence interface in order to represent the sequence of characters. This means that these three classes are used in Java to create strings.

The Java String class is unchangeable. In other words, it is immutable. A new instance gets created each time a string is changed. The StringBuffer and StringBuilder classes are used for mutable strings.

The immutable string will be dealt with later. Let’s first understand the concept of string and the way to create a string in Java.

What is a string?

A string is an object that is used in Java to represent a sequence of characters. It is created by using the java.lang.String.

Methods to create a string object

There are two methods that are used to create a string object and they are:

  1. By string literal
  2. By new keyword
  3. String Literal

A string literal is a sequence of characters that are created by using double quotation marks.

Why is the concept of string literal used in Java?

String literal is used in Java to save up more memory as new objects are not created if it already exists in the string constant pool.

  1. New Keyword

In this method, a new string object is created by the JVM in heap memory. The object in the heap memory will be referred by the variables.

Java String class methods

The various methods supported by Java string to perform several operations on a sequence of characters are:

  1. char chartA(int index):

This method returns the character value for the particular index.

  1. int length():

This method returns the length of the string.

  1. static String format(String format, Object…args):

This method returns the string in a particular format.

  1. static String format(Locale I, Strict format, Object…args):

This method returns the string in a particular format along with a given locale.

  1. static substring(int beginIndex):

This method returns a substring of the given beginning index.

  1. string substring(int begin Index, int endIndex):

This method returns a substring of the given beginning and ending index.

  1. boolean contains(CharSequence s):

This method returns whether the Boolean statement is true or false after matching the sequence of the character value.

  1. static String join(CharSequence delimiter, CharSequence…elements):

This method returns a joint string.

  1. static String join(CharSequence delimiter, Iterable<? extends CharSequence> elements):

This method also returns a joint string.

  1. boolean equals(Object another):

This method is used to check the equality between the string and a given object.

  1. boolean isEmpty():

This method is used to check whether the string is empty or not.

  1. String concat(String str):

This method is used to link specified strings.

  1. String replace(char old, char new):

This method is used to replace all occurrences of the particular character value.

  1. String replace(CharSequence old, CharSequence new):

This method is used to replace all occurrences of the particular character sequence.

  1. static String equalsIgnoreCase(String another):

This method is used to make a comparison between two strings.

  1. String[] split(String regex):

This method returns a split string that matches the regex.

  1. String[] split(String regex, int limit):

This method returns a split string that matches the regex and the limit as well.

  1. String intern():

This method returns an interned string.

  1. Int indexOf(int ch):

This method returns the particular character value index.

  1. int indexOf(int ch, int fromIndex):

This method returns the particular character value index beginning with the given index.

  1. int indexOf(String substring):

This method returns the particular substring index.

  1. int indexOf(String substring, int fromIndex):

This method returns the particular substring index beginning with the given index.

  1. String toLowerCase():

This method returns the string in a lowercase.

  1. String toLowerCase(Locale l):

This method returns the string in lowercase using a particular locale.

  1. String toUpperCase():

This method returns the string in uppercase.

  1. String toUpperCase(Locale l):

This method returns the string in uppercase using a particular locale.

  1. String trim():

This method removes the starting and ending spaces of the string.

  1. static String valueOf(int value):

This method is an overloaded method that converts given type into a string.

Immutable string in Java

The string objects are immutable in Java. In other words, it cannot be modified or be changed. The data and state of the string object cannot be changed once it is created; instead, a new string object is created.

Why are string objects immutable in Java?

String objects are immutable in Java because of the use of the string literal. When one reference variable gets changed, then it will affect all other reference variables that refer to the same object as well. So in order to avoid this, string objects are immutable in Java.

Java String Comparison

A string in Java can be compared on the basis of its content and reference. The string comparison is used in authentication, reference matching, and sorting through the use of equals() method, ==operator, and compareTo() method respectively.

The three methods used to compare string in Java are:

  1. By equals() method
  2. By == operator
  3. By compareTo() method
  4. String comparison through equals() method

The string equals() method compares the value of the string for equality. The original content of the string is compared through this method. There are further two types of equals() method and they are:

  • public boolean equals(Object another): This method compares the string to the specified object.
  • public boolean equalsIgnoreCase(String another): This method compares one string to another string and ignores the case.
  1. String comparison through == operator

The == operator does not compare the value of the string rather it compares the references.

  1. String comparison through compareTo() method

This method compares the values of the string lexicographically. It then returns an integer value that reports whether the string is greater than, equal to or less than the second string.

String concatenation in Java

String concatenation is the process of creating a new string by combining various different strings. The two methods used to combine strings to make a new string are:

  1. By + (string concatenation) operator
  2. By concat() method
  3. String concatenation by + (string concatenation) operator

The string concatenation operator (+) is used in Java to combine strings. After combing the strings, the StringBuilder or StringBuffer classes are used to implement string concatenation. Here, a new string is created by appending the second operand onto the end of the first operand. The operator not only combines strings but also the primitive values.

  1. String concatenation by concat() method

This method creates a new string by concatenating a particular string to the end of the current string.

Substring

Substring is a small part of a string. This means a subset of a string is called a substring. Here the startIndex is inclusive whereas the endIndex is exclusive.

A substring can be obtained from a string by the following two ways:

  1. public String substring(int startIndex):

This method returns a new string with the substring of a particular string from a specific startIndex.

  1. public String substring(int startIndex, int endIndex):

This method returns a new string with the substring of a particular string from a specific startIndex to endIndex.

Java string class methods

The java.lang.String class contains various methods that can be used to perform several operations on a string. Some of the functions of such methods include trimming, concatenating, comparing, converting, and replacing strings. The string is an important concept in Java as everything is treated as a string.

Some of the most used methods of string class are:

Java String toUpperCase() and toLowerCase() method:

In this method, the toUpperCase() method converts the string into the uppercase letter and the toLowerCase() method converts it into the lowercase letter.

Java String trim() method:

This method removes white spaces at the beginning and at the end of the string.

Java String startsWith() and endsWith() method

Java String charAt() method:

This method returns a character value at a particular index.

Java String length() method:

This method returns the length of the specified string.

Java String intern() method:

This method returns the string from the pool in the case in which the pool has a string equal to the string object as resolved by the equals() method. The reference to the string object is returned after the string object is added in the opposite case.

Java String valueOf() method:

This method converts int, long, double, float, boolean, char array, and char into a string.

Java String replace() method:

This method replaces every occurrence of a sequence of characters with another sequence of characters.

Java StringBuffer class

The Java StringBuffer class creates a string that can be modified or changed. It is similar to a string class but the only difference is that it is mutable.

Important Constructors of StringBuffer class

  • StringBuffer():

This constructor creates a string buffer that is initially empty and has a capacity of 16.

  • StringBuffer(String str):

This constructor creates a string buffer with a particular string.

  • StringBuffer(int capacity):

This constructor creates a string buffer that is initially empty and has the capacity as its length.

Important methods of StringBuffer class

  • append(String s):

This method combines a specific string with another string. It is an overloaded method and includes append(char), append(int), append(boolean), append(double), and append(float).

  • insert(int offset, String s):

This method inserts a particular string at a specific position of another string. It is also an overloaded method and includes insert(int, double), insert(int, char), insert(int, int), insert(int, boolean), and insert(int, float).

  • replace(int startIndex, int endIndex, String str):

This method replaces a string from the particular startIndex and endIndex.

  • delete(int startIndex, int endIndex):

This method deletes a string from the particular startIndex and endIndex.

  • reverse():

This method reverses the string.

  • capacity():

This method returns the current capacity of the string.

  • ensureCapacity(int minimumCapacity):

This method ensures the capacity of the string to same or more than the given minimum.

  • charAt(int index):

This method returns the character value at a particular position.

  • length():

This method returns the length of the string.

  • substring(int beginIndex):

This method returns a substring from a particular beginIndex.

  • substring(int beginIndex, int endIndex):

This method returns a substring from a particular beginIndex and endIndex.

What is a mutable string?

A mutable string is such type of string that can be modified or changed. It is created by using the StringBuffer and the StringBuilder classes.

Java StringBuilder class

The Java StringBuilder class is used like the StringBuffer class in order to create a modifiable string. The only difference between the two classes is that the StringBuilder class is non-synchronized. This feature was added on the JDK 1.5.

Important Constructors of StringBuilder class

  • StringBuilder():

This constructor creates a string builder that is initially empty and has a capacity of 16.

  • StringBuilder(String str):

This constructor creates a string builder with a particular string.

  • StringBuilder(int length):

This constructor creates a string builder that is initially empty and has the capacity as its length.

Important methods of StringBuilder class

  • public StringBuilder append(String s):

This StringBuilder method appends a specific string with another string. It is an overloaded method and includes append(boolean), append(char), append(double), append(int), and append(float).

  • public StringBuilder insert(int offset, String s):

This StringBuilder method inserts a particular string at a specific position of another string. It is also an overloaded method and includes insert(int, char), insert(int, int), insert(int, double), insert(int, boolean), and insert(int, float).

  • public StringBuilder replace(int startIndex, int endIndex, String str):

This StringBuilder method replaces a string from the particular startIndex and endIndex.

  • public StringBuilder delete(int startIndex, int endIndex):

This StringBuilder method deletes a string from the particular startIndex and endIndex.

  • public StringBuilder reverse():

This StringBuilder method reverses the string.

  • public int capacity():

This StringBuilder method returns the current capacity of the string.

  • public void ensureCapacity(int minimumCapacity):

This StringBuilder method ensures the capacity of the string to same or more than the given minimum.

  • public char charAt(int index):

This StringBuilder method returns the character value at a particular position.

  • public int length():

This StringBuilder method returns the length of the string.

  • public String substring(int beginIndex):

This StringBuilder method returns a substring from a particular beginIndex.

  • public String substring(int beginIndex, int endIndex):

This StringBuilder method returns a substring from a particular beginIndex and endIndex.

Dissimilarities between a String and a StringBuffer

  • A string class is immutable but a StringBuffer class can be changed or modified.
  • When multiple strings are combined, a new instance is created every time which consumes more memory and makes the program slow.
  • On the other hand, when strings are combines in StringBuffer, it consumes less memory and makes the program run faster.
  • The contents of two string class can be compared by using the equals() method as the string class overrides the method. However, it cannot be done in StringBuffer as it does not override the equals() method.

Dissimilarities between StringBuffer and StringBuilder

  • The StringBuffer is synchronized so more than one thread cannot call the methods simultaneously in it. But two threads can call methods simultaneously in the StringBuilder as it is not thread-safe.
  • In case of efficiency, the StringBuffer is more efficient than the StringBuilder.

Methods to create an immutable class

In Java, the wrapper classes and string classes like String, Byte, Boolean, Integer, Short, Long,

Float and Double are called immutable as they cannot be changed or be modified. A class is called immutable if the instance variable of the class is final, there are no setter methods in the class, and a subclass cannot be created from the class. The immutable class can be created by creating a final class with final data members.

Java toString() method

The Java toString() method is used to represent an object as a string. It is internally invoked by the Java compiler when an object is printed in order to return the string representation of the object. So depending on the implementation, the overriding of the toString() method returns the desired output such as the state of the object.

The benefit of Java toString() method

The use of the Java toString() method returns the values of the object. This helps to avoid the need of writing more code in the program which saves the programmer’s time.

StringTokenizer in Java

In Java, a string can be broken down into tokens by using the java.util.StringTokenizer. This is the simplest way to break down strings but it does not provide other facilities such as identifiers, differentiate numbers, and quoted strings. The concept of StringTokenizer will be dealt with further in the I/O chapter.

Constructors of StringTokenizer class

The following are the three constructors defined in the StringTokenizer class.

  • StringTokenizer(String str):

This constructor creates StringTokenizer with a particular string.

  • StringTokenizer(String str, String delim):

This constructor creates StringTokenizer with a particular string and a specific delimeter.

  • StringTokenizer(String str, String delim, boolean returnValue):

This constructor creates StringTokenizer with a particular string, a specific delimeter, and a specific returnValue as well. The delimeter characters will be tokens when the return value is true otherwise they will serve to separate tokens.

Methods of StringTokenizer class

The methods used by StringTokenizer class are:

  • boolean hasMoreTokens():

This method checks whether or not more tokens are available.

  • String nextToken():

This method returns the following token from the StringTokenizer object.

  • String nextToken(String delim):

This method returns the following token on the basis of the delimeter.

  • boolean hasMoreElements():

This method checks whether or not more elements are available.

  • Object nextElement():

This method returns the following object.

  • int countTokens():

This method returns the total number of tokens present in the object.

Java String Methods

Java String charAt():

This method returns the character value for the particular index. The index number begins from 0 and ends at n-1, where n is the length of the string. In the case in which the given index is greater than or equal to the length of the string or is a negative number, then the method returns StringIndexOutOfBoundsException.

Java String compareTo()

This method compares the values of the string lexicographically on the basis of the Unicode value of each character in the strings. It then returns an integer value that reports whether the string is greater than, equal to or less than the second string.

When the first string is greater than the second string, it returns a positive number. It returns a negative number when the first string is less than the second string. In the case in which both the string are equal, the method returns 0.

Java String concat

The Java string concat() method creates a new string by concatenating a particular string to the end of the current string. It then returns the combined string.

Java String contains()

This method returns true when the sequence of characters values searched are found in the string otherwise it returns false.

Java String endsWith()

This method returns true if the string ends with a specific suffix otherwise it returns false.

Java String equals()

This method makes a comparison between two strings on the basis of their contents. If all characters of both strings are same, it returns true otherwise it returns false. It overrides the equals() method of the object class.

Java String equalsIgnoreCase()

This method performs the same function as the string equals() method and returns true if all characters of both strings match. However, this method only checks the content of the strings, not the case.

Java String format()

This method returns the formatted string by a specific format, locale, and arguments. It is similar to the sprint() function in C language and the printf() method. The Locale.getDefault() method is called as a default, in the case in which the programmer does not specifies the locale in this method.

Java String getBytes()

This method returns the sequence of bytes of the string. In other words, it returns the byte array of the string.

Java String getChars()

This method does not return any value but copies the content of a string into a particular character array. This method passes four arguments and in the case in which beginIndex is greater than endIndex, the method gives out StringIndexOutOfBoundsException.

Java String indexOf()

This method returns an index of a specified char value or substring. The counter of index begins from 0 and the method returns -1 when the char value is not found in the string. The types of the indexOf method in Java are as follows:

  • int indexOf(int ch):

This method of the indexOf method returns the position of the index for a specific character value.

  • int indexOf(int ch, int fromIndex):

This method of the indexOf method returns the position of the index for a specific character value from the index.

  • int indexOf(String substring):

This method of the indexOf method returns the position of the index for a specific substring.

  • int indexOf(String substring, int fromIndex):

This method of the indexOf method returns the position of the index for a specific substring from the index.

Java String intern()

This method returns the canonical representation of the string or the interned string.  When the method is created by using a new keyword, it returns a string from the memory. It can also be used to create a copy of heap string object in string constant pool.

Java String isEmpty()

This method returns true if the length of the string is empty or 0 and returns false in other cases. This method was added in the Java string from JDK 1.6.

Java String join()

This method returns a string joined with a specific delimiter. The delimiter is copied for all elements and null is added for the null elements. This method was added in the Java string from JDK 1.8.

Java String lastIndexOf()

This method returns the last index of a specific char value of substring. The counter of index begins from 0 like the indexOf() method and the method also returns -1 when the char value is not found in the string. The types of the lastIndexOf method in Java are as follows:

  • int lastIndexOf(int ch):

This method of the lastIndexOf method returns the position of the last index for a specific character value.

  • int lastIndexOf(int ch, int fromIndex):

This method of the lastIndexOf method returns the position of the last index for a specific character value from the index.

  • int lastIndexOf(String substring):

This method of the lastIndexOf method returns the position of the last index for a specific substring.

  • int lastIndexOf(String substring, int fromIndex):

This method of the lastIndexOf method returns the position of the last index for a specific substring from the index.

Java String length()

This method returns the total number of character present in the string. The length of a Java string is exactly same as the Unicode units of it.

Java String replace()

This method returns a new string after replacing all the previous character of a string with new characters. This method was added from the JDK 1.5 to make the replacing of characters of a string easier.

Java String replaceAll()

This method returns a new string after replacing all the characters matching regex with a new sequence of characters.

Java String split()

This method returns a character array after splitting a particular string with a specific regular expression. This method was added from the JDK 1.4.

Java String startsWith()

This method returns true if the string begins with a specified prefix and returns false if not.

Java String substring()

This method returns a substring. The substring can either be passed from the beginning index which is 0 or from the ending index which is 1. There are further two types of methods using to return substring.

Java String toCharArray()

This method returns a newly created char array after converting a string. The length of the char is equal to the string from which it is created and the contents are initialized from the characters of the string.

Java String toLowerCase()

This method returns a new string after converting all the characters of a specific string into lowercase letters. The function of this method is similar to the function of the toLowerCase(Locale.getDefault()) method.

Java String toUpperCase()

This method returns a new string after converting all the characters of a specific string into uppercase letters. The function of this method is similar to the function of the toUpperCase(Locale.getDefault()) method.

Java String trim()

This method removes the unnecessary spaces in a string that is leading and trailing spaces. It returns a new string after removing the spaces that are found by checking the Unicode value of the string.

Java String valueOf()

This method converts different values into a string such as an int to string, object to a string, long to string, float to a string, character to a string, boolean to string, double to a string, and char array to string.

Java Regex

Java regex is defined as an API that is used to describe a pattern to be used to search or manipulate strings. It is also known as Regular Expression. The main function of the Java regex is to explain the constraint on strings like email and password validation. After finishing the following tutorial on Java regex, a programmer will be able to test any regular expressions in Java by using the Java Regex Tester Tool. There consists of one interface and three classes in the java.util.regex package.

java.util.regex package

The java.util.regex package provides the following interface and classes to deal with regular expressions:

  • MatchResult interface
  • Matcher class
  • Pattern class
  • PatternSyntaxException class

Matcher class

The matcher class is a regex engine. It carries out match operations on a sequence of char and executes the MatchResult interface. The various methods provided by the matcher class are:

  • boolean matches():

This method is used to check whether or not the regular expression matches the pattern.

  • boolean find():

This method is used to locate the next expression that matches the pattern.

  • boolean find(int start):

This method is used to locate the next expression that matches the pattern from a specified starting number.

  • String group():

This method returns the subsequences that match.

  • int start():

This method returns the beginning index of the subsequences that have matched.

  • int end():

This method returns the ending index of the subsequences that have matched.

  • int groupCount():

This method returns the total number of subsequences that have matched.

Pattern class

The pattern class is defined as the version of regular expressions that have been compiled together. The main function of this class is to describe a pattern for the regex engine. The various methods provided by the pattern class are as follows:

  • static Pattern compile(String regex):

This method returns an instance of the pattern after compiling the specified regex.

  • Matcher matcher(CharSequence input):

This method matches the specified input with the pattern by creating a matcher.

  • static boolean matches(String regex, CharSequence input):

This method combines the regular expression and matches the specified input with the pattern. It functions as a combination of matcher and compiles methods.

  • String[] split(CharSequence input):

This method splits the specified input string around matches of a particular pattern.

  • String pattern():

This method returns the pattern of the regex.

Regex character classes

  • [abc]:

This class refers to simple classes such as a, b, or c.

  • [^abc]:

This class refers to any other character except a, b, or c.

  • [a-zA-Z]:

This class refers to an inclusive range that includes the characters from a through z or A through Z.

  • [a-d[m-p]]:

This class refers to a union that includes the characters from a through d or m though p.

  • [a-z&&[def]]:

This class refers to an intersection that includes the characters d, e, or f.

  • [a-z&&[^bc]]:

This class refers to subtraction that includes the characters from a through z, except for b and c.

  • [a-z&&[^m-p]]:

This class refers to subtraction that includes the characters from a through z, but not m through p.

Regex quantifiers

The quantifiers are used in a regex to specify how many times each character occurs. The following are the regex quantifiers used:

  • X? :

This means that the X occurs only one time or does not occur at all.

  • X+ :

This means that the X occurs a single time or multiple times.

  • X* :

This means that the X does not occur at all or occurs multiple times.

  • X{n} :

This means that the X occurs for the n times only.

  • X{n,} :

This means that the X occurs for the n times or more than the n times.

  • X{y,z} :

This means that the X occurs at least y times but not more than z times.

Regex Metacharacters

The following are the regular expression metacharacters that are used as shortcodes:

  • .

This metacharacter refers to any character. Such character might or might not match the terminator.

  • \d

This metacharacter refers to any digit character. It is the shortcode of [0-9].

  • \D

This metacharacter refers to any non-digit character. It is the shortcode of [^0-9].

  • \s

This metacharacter refers to any whitespace character. It is the shortcode of [\t\n\x0B\f\r].

  • \S

This metacharacter refers to any non-whitespace character. It is the shortcode of [^\s].

  • \w

This metacharacter refers to any word character. It is the shortcode of [a-zA-Z_0-9].

  • \W

This metacharacter refers to any non-word character. It is the shortcode of [^\w].

  • \b

This metacharacter refers to a word boundary.

  • \B

This metacharacter refers to a non-word boundary.

 

Exception Handling in Java

Exception handling is one of the most important mechanisms that are used in Java to manage the runtime errors. It helps in maintaining the flow of the application to be normal. In this chapter, various subjects related to Java exceptions including its type and the dissimilarities between checked and unchecked exceptions will be dealt with.

What is an exception in Java?

The simple meaning of exception is an unusual situation. In Java, an exception is defined as an event that disturbs the usual flow of the program. It is an error that is thrown by the program during its run.

What is exception handling?

Exception handling is the mechanism that is used to manage errors during the runtime. It handles various runtime errors including IO, Remote, SQL, and ClassNotFound.

The benefit of exception handling

The main function of exception handling is to maintain the normal flow of the program. When an exception occurs in a program, it disturbs the normal flow of the program. So exception handling is used to handle such errors. It executes all the statements in which there is no error and skips the statement in which there is an exception.

Hierarchy of Java exception classes

The root class of Java exception hierarchy is the java.lang.Throwable class. It is further inherited by Exception and Error subclasses. The following is a hierarchy of Java exception classes:

Throwable

  1. Exception:       Error:
  2. IOException a) StackOverflowError
  3. SQLException b) VirtualMachineError
  4. ClassNotFoundException                   c) OutOfMemoryError
  5. RuntimeException:
  6. ArithmeticException
  7. NullPointerException
  • NumberFormatException
  1. IndexOutOfBoundsException
  • ArrayIndexOutOfBoundsException
  • StringIndexOutOfBoundsException

Types of Java Exceptions

There are two types of exceptions that mainly occur and they are:

  1. Checked exception
  2. Unchecked exception

However, Oracle has added another type of exception which is:

  1. Error
  2. Checked exception

Checked exceptions are those exceptions that inherit Throwable class directly and are checked during compile-time. IOException and SQLException are a few examples of checked exceptions and it does not include RuntimeException and Error.

  1. Unchecked exception

ArithmeticException, NullPointerException, and ArrayIndexOutOfBoundsException are the unchecked exceptions that are checked during runtime, not during the compile-time. Such exceptions inherit RuntimeException.

  1. Error

VirtualMachineError, OutOfMemoryError, and AssertionError are the errors that cannot be covered.

Java Exception Keywords

These are the keywords that are used in Java to handle exceptions:

  • try:

The function of the try keyword is to specify the block in which the exception code is to be placed. It cannot be used alone and must be followed by either the catch keyword or the finally keyword.

  • catch:

The catch keyword is used after the try keyword and the finally block can be used after it. So it cannot be used alone in handling exceptions.

  • finally:

The finally keyword is used after the try and the catch keyword to execute if an exception has been handled or not. It executes the main code of the program.

  • throw:

The main function of the throw keyword is to throw an exception.

  • throws:

The throws keyword is used with the method signature in order to declare exceptions. Like the throw keyword, the throws keyword does not throw an exception but it specifies that there might be a presence of exceptions in the method.

Common scenarios of Java exceptions

The following are the scenarios in which unchecked exceptions may occur:

  1. A scenario in which ArithmeticException occurs

The NullPointerException occurs if any number is divided by zero.

  1. A scenario in which NullPointerException occurs

The NullPointerException occurs while performing an operation on a variable if there is a null value in the variable.

  1. A scenario in which NumberFormatException occurs

The NumberFormatException occurs if the programmer wrongly formats a value.

  1. A scenario in which ArrayIndexOutOfBoundsException occurs

The ArrayIndexOutOfBoundsException occurs if the programmer inserts a value in the wrong index.

Java try-catch

Java try block

The Java try block is used within a method and cannot be used alone. It must be followed by catch or finally block. The main function of the try block is to enclose the code that might throw an exception.

Java catch block

The Java catch block cannot be used alone and can only be used after the try block. Multiple numbers of catch blocks can be used in a single try in order to manage the exception.

Internal working of Java try-catch block

The JVM checks if the exception has been managed or not. In the case in which the exception has been handled, then the rest of the code gets executed. However, in the opposite case, the JVM supplies a default exception handler that carries out the following functions:

  • In the first step, the exception description is printed out.
  • In the second step, the stack trace is printed out.
  • In the final step, the program gets terminated.

Java Catch multiple exceptions

Java multi-catch block

In Java, a multi-catch block is used when the programmer has to carry out various tasks at the occurrence of several exceptions.

Java nested try block

In Java, a nested try block is a try block that exists inside another try block.

Why use nested try block?

The nested try block is used to handle an exception in the case in which one error might arise from one block and the rest of the block might cause other errors.

Java finally block

The finally block is used in Java to carry out important functions in a code including stream and closing connection. It cannot be used alone and is used after either a try block or a catch block. The finally block is used even if the exception is handled.

Why use finally block?

The function of the finally block is to execute cleanup code in the programs. It executes code such as closing connection and closing a file.

Java Throw exception

Java Throw keyword

The main function of the throw keyword in Java is to throw an exception explicitly. It throws both checked and unchecked exception and mainly throws custom exceptions that are defined by the programmer.

Java Exception propagation

An exception gets thrown from the top of the stack in the first place. If it does not get caught, it then drops down the call stack to the previous method. If not caught in this step, the exception drops down to the previous method again. This goes on until the exception gets caught or reaches the bottom of the call stack. This whole process is called exception propagation.

Java throws keyword

The throws keyword is used in Java to handle the checked exceptions. It is used to declare the checked exceptions but it cannot declare unchecked exceptions or the errors. This is because the unchecked exceptions and the errors are the programmers’ own fault and they should be checked by the programmer themselves before using the code. The throws keyword provides information to the programmer that an exception might occur in the program and gives suggestion to them to provide the exception handling code in order to ensure the normal flow of the program.

Which exceptions can be declared?

Only the checked exception can be declared by using the throws keyword. This is because unchecked exceptions like NullPointerException are under the control of the programmer so they can themselves correct the code. And errors like VirtualMachineError and StackOverflowError are beyond the control of the programmer so they cannot do anything if these errors occur.

The benefit of throws keyword in Java

The main advantage of the throws keyword in Java is that it provides information about the exception to the programmer.

Dissimilarities between throw and throws keyword in Java

There are various dissimilarities between the throw and throws keyword in Java. Some of them are mentioned below:

  • The main function of the throw keyword is to throw an exception explicitly. On the other hand, the main function of the throws keyword is to declare an exception.
  • By using the throw keyword, the checked exception cannot be propagated. But the checked exception can be propagated by using the throws keyword.
  • The throw keyword is followed by an instance but a class follows the throws keyword.
  • The throw keyword functions inside a method but the throws keyword functions inside a method signature.
  • The programmer cannot throw multiple exceptions using the throw keyword. However, the throws keyword can declare multiple exceptions.

Dissimilarities between final, finally, and finalize

Some of the dissimilarities between final, finally, and finalize are explained below:

  • The main function of the final keyword is to restrict class, variable, and method. It restricts the class from being inherited, the variable from being changed, and the method from being overridden. The main function of finally block is to execute codes whether the exception is managed or not. And the main function of the finalize method is to carry out clean up processing just before an object gets garbage collected.
  • Final is a keyword, finally is a block, and finalize is a method.

Exception handling in Java with method overriding

The rules to be followed while handling an exception with method overriding are as follows:

  • In the case in which an exception is not declared by the superclass method:

In the case in which an exception is not declared by the superclass method, the checked exception cannot be declared by the subclass overridden method but the unchecked exception can be declared by it.

  • In the case in which an exception is declared by the superclass method:

In the case in which an exception is declared by the superclass method, subclass exception and same exception can be declared by the subclass overridden method. It can also declare no exception at all but the parent exception cannot be declared by it.

Java custom exception

A custom exception is defined in Java as an exception that is created by the programmer themselves. It is also known as a user-defined exception and is it customizes the exception as per the need of the programmer. This way, the programmer can have their own exception and message by using the custom exception.

Java Inner Classes

The inner class in Java is the class that is declared within another class or within another interface. It is also known as nested class. As classes and interfaces are logically grouped in a single place by using the inner classes, it makes the program easily maintainable and more readable. The inner class can access each member of the outer class, even the private methods, and data members.

Benefits of Java inner classes

Some of the benefits of using inner classes in Java are:

  • The inner class can access all the members of the outer class, even the private ones as it represents a greater type of relationship.
  • The classes and interfaces are logically grouped in a single place by using the inner classes so it makes the code easily maintainable and readable.
  • The use of inner class decreases the need to write more code.

The dissimilarity between nested class and inner class in Java

The inner class is the part of the nested class that is non-static.

Types of nested classes

The nested class is divided into two types: Static nested class and non-static nested class. The non-static classes or the inner classes are further divided into three types.

  • Static nested class
  • Non-static nested class:
  • Member inner class:

A class created inside a class but outside a method.

  • Anonymous inner class:

A class that has no name and implements interface or extends a class.

  • Local inner class

A class created inside a class and inside a method.

Static nested class

A static nested class is the type of nested class that is created within a class. The static nested class can only access static data members and method, not the non-static. It can also access the private data members of the outer class. The outer class name can only access the static nested class.

Non-static nested class

The three types of non-static nested class are explained below:

Member inner class:

A member inner class is the type of inner class that is created inside a class but outside a method.

Internal working of Java member inner class

In the case of the member inner class, the program created two class files. The class file is named Outer$Inner. The instance of the outer class must be created by the programmer if they want to instantiate the inner class. In this situation, an instance of the inner class is created inside the instance of the outer class.

The internal code generated by the compiler

In case of the member inner class, the program created a class file named Outer$Inner. The member inner class can access all the data members of the outer class as it has the reference of the outer class.

Anonymous inner class:

An anonymous inner class is the type of inner class that implements an interface or extends a class. The Java compiler decides the name of the anonymous inner class as it does not have any name. It is used when the programmer has to perform method overriding of a class or an interface. There are two methods to create an anonymous inner class and they are:

  • Through class
  • Through interface

Local inner class:

A local inner class is the type of inner class that is created inside another class and also within a method. The class inside the method must be instantiated if the programmer wants to call on the methods of the local inner class.

Rules for Java local inner class

  • The local inner class cannot be called on from outside the method.
  • The local inner class could only access the final local variable till JDK 1.7 but after JDK 1.8 it can also access the non-final local variable.

Java nested interface

In Java, a nested interface can be defined as an interface that is declared inside another interface on a class. The main function of the nested interface is to group related interfaces to make the code easily maintainable. The outer interface or class can only refer to the nested interface and it cannot be accessed directly.

Main features of nested interfaces

The following are some of the major features of the nested interfaces:

  • If a nested interface is declared within another interface, it should be public. However, if it is declared inside a class, the nested interface can include any access modifier.
  • The nested interfaces are totally declared as static.

Can a class be defined inside an interface?

When the programmer defines a class within an interface, a static nested class is created by the program.

Java Multithreading

In Java, multithreading is defined as the process of executing multiple threads simultaneously. Here, a thread means the smallest unit of processing or in other words, a lightweight sub-process. Both multithreading and multiprocessing can be used in order to achieve multitasking. But multithreading is used in Java rather than multiprocessing as a shared memory area is used by threads. Multithreading saves memory as they don’t take up separate memory area and the processing time is also less as they take less time while context-switching among the threads. It is mainly used in animations and games.

Benefits of Java multithreading

  • The programmer does not get blocked by multithreading as the threads do not depend on each other and multiple operations can be carried out by the programmer at the same time.
  • Multithreading saves up time as multiple operations can be carried out at the same time.
  • In the case in which an exception occurs in one thread, other threads are not affected as the threads are not dependent on each other.

Multitasking

Multitasking can be defined as the process of carrying out multiple tasks at the same time. It is used in order to utilize the CPU. The two ways by which multitasking can be achieved are:

  • Process-based multitasking or Multiprocessing
  • Thread-based multitasking or Multithreading
  1. Process-based multitasking or multiprocessing

The main points to remember in multiprocessing are:

  • Each process takes up an address in the memory which means that each process takes up a separate memory area.
  • A process is a heavyweight.
  • The cost of communication in the process is high.
  • Switching from one process to another takes up some time for performing functions such as updating lists, saving and loading registers, and memory maps.
  1. Thread-based multitasking or Multithreading

The main points to remember in multithreading are:

  • All the threads allocate the same address space,
  • A thread is a lightweight.
  • The cost of communication among the threads is low.

What is a thread in Java?

In Java, a thread can be defined as the smallest unit of processing. It is a lightweight subprocess that is a distinct path of execution. Other threads are not affected when an exception occurs in one thread because the threads are not dependent on each other. A thread is executed inside a process and there is context-switching in the threads. Inside an OS there may be multiple processes and multiple threads can be within a process.

Java thread class

The thread class is supplied by the Java in order to achieve thread programming. The operations on a thread are created and performed by the constructors and methods provided by the thread class. The object class is extended by the thread class and it implements the runnable interface as well.

Java thread methods

The various thread methods are explained below:

  1. void start():

This method starts the execution of the thread.

  1. void run():

This method carries out an action for the thread.

  1. static void sleep():

This method makes the thread sleep for a particular amount of time.

  1. static thread currentThread():

This method returns a reference to the thread object that is currently being executed.

  1. void join():

This method waits until a thread dies.

  1. int getPriority():

This method returns the priority of the specific thread.

  1. void setPriority():

This method changes the priority of the specific thread.

  1. string getName():

This method returns the name of the specific thread.

  1. void setName():

This method changes the name of the specific thread.

  1. long getId():

This method returns the id of the specific thread.

  1. boolean isAlive():

This method returns true if the thread is alive, otherwise returns false.

  1. static void yield():

This method allows threads to execute temporarily after the thread object that is currently being executed is paused.

  1. void suspend():

This method suspends the specified thread.

  1. void resume():

This method is used to resume the thread that has been suspended.

  1. void stop():

This method stops a specific thread.

  1. void destroy():

This method destroys a specific thread group and all of its subgroups.

  1. boolean isDaemon():

This method returns true if the thread is a daemon thread, otherwise returns false.

  1. void setDaemon():

This method is used to mark the thread as a daemon thread.

  1. void interrupt():

This method interrupts a specific thread.

  1. boolean isinterrupted():

This method returns true if the thread has been interrupted, otherwise returns false.

  1. static boolean interrupted():

This method returns true if the current thread has been interrupted, otherwise returns false.

  1. static int activeCount():

This method is used to find out the total number of threads in the current thread’s group that are active.

  1. void checkAccess():

This method checks whether the currently running thread has the permission to modify thread or not.

  1. static boolean holdLock():

This method is used to check if the current thread holds the monitor lock on a particular object or not.

  1. static void dumpStack():

This method prints a stack trace of the current thread to the standard error stream.

  1. StackTraceElement[] getStackTrace():

This method returns an array of stack trace elements that represent the stack dump of the thread.

  1. static int enumerate():

This method copies all active thread’s group and its subgroup into a particular array.

  1. State getState():

This method returns the state of the thread.

  1. ThreadGroup getThreadGroup():

This method returns the thread group that the thread belongs to.

  1. String toString():

This method returns a string representation of the thread which includes the name of the thread, its group, and priority.

  1. void notify():

This method provides the notification to one thread that is waiting for a specified object.

  1. void notifyAll():

This method provides the notification to all waiting threads of a specified object.

  1. void setContextClassLoader():

This method is used to set the context ClassLoader for a specific thread.

  1. ClassLoader getContextClassLoader():

This method is used to return the context ClassLoader for a specific thread.

  1. static Thread.UncaughtExceptionHandler getDefaultUncaughtExceptionHan:

This method is used to return the default handler called on when a thread abruptly terminates because of an uncaught exception.

  1. static void setDefaultUncaughtExceptionHandler():

This method is used to set the default handler called on in the case in which a thread abruptly terminates because of an uncaught exception.

The lifecycle of a thread (Thread states)

In general, there are five states that a thread can be. However, Sun has removed the running state so there are only four states and they are: new, runnable, non-runnable, and terminated.

But to better understand the concept of the thread, all of the five states will be dealt with in this chapter.

The Java thread states that are controlled by the JVM are as follows:

  1. New:

A thread is said to be in the new state before the invocation of the start() method when an instance of a thread is created.

  1. Runnable:

A thread is said to be in the runnable state when the start() method has been invocated but it has not been chosen by the thread scheduler as a running thread.

  1. Running:

A thread is said to in the running state after it gets chosen by the thread scheduler to run.

  1. Non-runnable (Blocked):

A thread is said to be in the non-runnable or the blocked state when it is alive but not currently eligible to run.

  1. Terminated:

A thread is said to be in the terminated state when the run() method is executed.

How to create a thread

There are two ways that can be used to create a thread and they are:

  1. By extending the thread class
  2. By implementing the runnable interface

Thread class

Various constructors and methods are provided by the thread class in order to create and carry out operations on a thread. The object class is extended by the thread class and it implements the runnable interface as well.

The commonly used constructors of the thread class:

Below are some of the most commonly used constructors of the thread class:

  • thread()
  • thread(string name)
  • thread(runnable r)
  • thread(runnable r, string name)

The commonly used methods of the thread class:

Some of the most commonly used methods of the thread class are explained below:

  1. public void run():

This method carried out an action for a specific thread.

  1. public void start():

This method starts the execution of the thread. The program invokes the run() method on the thread.

  1. public void sleep(long milliseconds):

This method makes the currently executing thread sleep for a particular number of milliseconds.

  1. public void join():

This method waits until a thread dies.

  1. public void join(long milliseconds):

This method waits until a thread dies for a particular number of milliseconds.

  1. public int getPriority():

This method returns the priority of the specific thread.

  1. public int setPriority(int priority):

This method changes the priority of the specific thread.

  1. public String getName():

This method returns the name of the specific thread.

  1. public void setName(String name):

This method changes the name of the specific thread.

  1. public Thread currentThread():

This method returns a reference to the thread that is currently being executed.

  1. public int getId():

This method returns the id of the specific thread.

  1. public Thread.State getState():

This method returns the state of the thread.

  1. public boolean isAlive():

This method returns true if the thread is alive, otherwise returns false.

  1. public void yield():

This method allows threads to execute temporarily after the thread object that is currently being executed is paused.

  1. public void suspend():

This method suspends the specified thread.

  1. public void resume():

This method is used to resume the thread that has been suspended.

  1. public void stop():

This method stops a specific thread.

  1. public boolean isDaemon():

This method returns true if the thread is a daemon thread, otherwise returns false.

  1. public void setDaemon(boolean b):

This method is used to mark the thread as a daemon thread.

  1. public void interrupt():

This method interrupts a specific thread.

  1. public boolean isInterrupted():

This method returns true if the thread has been interrupted, otherwise returns false.

  1. public static boolean interrupted():

This method returns true if the current thread has been interrupted, otherwise returns false.

Runnable interface

A class whose instances have been intended to be executed by a thread implements the runnable interface. The only method that is in the runnable interface is the run() method.

  • public void run():

This method is used to carry out an action for a specific thread.

Starting a thread:

A newly created thread is started by using the start() method. The following functions are carried out by it:

  • A new thread is started with a new call stack.
  • The thread transforms to the runnable state from the new state.
  • The run() method will get executed when the thread receives a chance to be executed.

Thread scheduler in Java

The thread scheduler is the part of the program that selects the thread to run. In a single process, only a single thread can be run and there is no assurance that which runnable thread will be selected to run. The preemptive or time slicing scheduling is used to schedule the threads by the thread scheduler.

Dissimilarities between preemptive scheduling and time slicing

The highest priority task gets executed under the preemptive scheduling until it enters the waiting or dead states or another higher priority task gets created. But under the time slicing scheduling, a task gets executed for a specified slice of time and then enters to the pool of ready tasks. The scheduler then makes the decision on which task should be executed next on the basis of priority and other factors.

Sleep method in Java

In Java, the sleep() method of the thread class makes a thread sleep for a particular amount of time. The thread scheduler selects another thread to run when a thread is made to sleep for a particular time.

Syntax of the sleep() method in Java

The following are the two methods that are provided by the thread class to make a thread sleep:

  • public static void sleep(long milliseconds)throws InterruptedException
  • public static void sleep(long milliseconds, int nanos)throws InterruptedException

Can a thread be started twice?

A thread cannot be started twice. In other words, a thread can never be started again, once it has been already started. If the programmer tries to do so, an IllegalThreadStateException is thrown. That means the thread will only run a single time and in the second time, it will throw the exception.

What if the run() method is called directly instead of the start() method?

  • Each thread starts in a distinct call stack.
  • When the run() method is called on from the main thread, the run() method will not go to the beginning of a new call stack but it will go into the current call stack.

The join() method

The join() method waits until a thread dies. That means the join() method stops the currently running thread from executing until the thread it joins with finishes its job.

Syntax:

  • public void join()throws InterruptedException
  • public void join(long milliseconds)throws InterruptedException

getName(),setName(String) and getId() method:

  • public String getName()
  • public void setName(String name)
  • public long getId()

The currentThread() method:

The currentThread() method returns a reference to the thread object that is currently being executed.

Syntax:

  • public static Thread currentThread()

Naming thread and the current thread

Naming thread

There are methods provided by the thread class that is used in Java in order to get the name of a thread and to change its name. The threads are named like thread-0, thread-1 and so on by default and the getName() method is used to find it. The name of the threads can be changed by using the setName() method.

Syntax:

  • public String getName():

This method returns the name of a specific thread.

  • public void setName(String name):

This method changes the name of a specific thread.

Priority of a thread (Thread priority):

Every thread in Java has a different priority. A number between 1 and 10 is used to represent these priorities. Preemptive scheduling of the thread scheduler schedules the threads on the basis of their priorities. But this is not always the case as the JVM specification selects the scheduling method to be used.

Three constants defined in thread class:

  • public static int MIN_PRIORITY:

The value of MIN_PRIORITY is 1.

  • public static int NORM_PRIORITY:

The value of NORM_PRIORITY is 5. This is the default priority of any thread.

  • public static int MAX_PRIORITY:

The value of MAX_PRIORITY is 10.

Daemon thread in Java

The daemon thread in Java is a type of thread that provides the services to the user thread. SO it is also known as a service provider thread. The daemon thread gets automatically terminated by the JVM when all the user thread dies. In other words, the life of daemon thread depends on the life of user threads. There are various daemon threads that automatically runs in Java such as finalizer and gc. The detail on these threads can be seen by typing the jconsole in the command prompt. The jconsole tool also provides other useful information related to the memory usage, loaded classes, and running threads.

Main points to remember about the daemon thread in Java

  • The only function of the daemon thread is to serve user threads. It provides services to the user threads in carrying out background supporting tasks.
  • The life of a daemon thread is dependent on the life of the user threads.
  • The daemon thread is a thread with low priority.

Why is the daemon thread terminated when there is no user thread?

The only function of the daemon thread is to provide services the user threads in carrying out background supporting tasks. There is no point in running a daemon thread if there is no user thread in the JVM. Therefore, the JVM immediately terminates the daemon thread if there is no user thread.

Methods for Java daemon thread by the thread class

The following are the two methods provided by the java.lang.Thread class for the daemon thread:

  • public void setDaemon(boolean status):

This method marks the current thread as a daemon thread.

  • public boolean isDaemon():

This method returns true if the current thread is a daemon thread otherwise returns false.

Java Thread Pool

In Java, the thread pool is defined as a collection of worker threads that are waiting for a task and are reused many times. Here, a fixed size of threads is collected in a group. Then the programmer selects a thread from the thread pool and pulls it out and assigns a task to it. After the thread completes its task, it is contained in the thread pool again.

Benefits of Java thread pool

The thread pool makes the performance of the program better because there will be no need to create a new thread, the programmer can select a thread from the thread pool to complete a task.

Real-time usage

The thread pool is used in JSP and Servlet where it is used to process the request.

ThreadGroup in Java

There is a convenient way provided by the Java to group multiple threads in a single object. This way, the programmer can interrupt, resume, or suspend a group of threads by using only one method call. The java.lang.ThreadGroup class is used to implement the thread group in Java.

A set of threads is represented by a ThreadGroup and it can also have other thread groups inside it. The thread group creates a tree. In it, all the threads have a parent but not the initial thread group.

A thread group can only access the information about its own thread group but it is not allowed to access the information related to its thread group’s parent thread group or any other thread groups.

Constructors of ThreadGroup class

The following are the two constructors of the ThreadGroup class:

  • ThreadGroup(String name):

This constructor is used to create a thread group with the name provided by the programmer.

  • ThreadGroup(ThreadGroup parent, String name):

This constructor is used to create a thread group with the parent group and name that is given by the programmer.

Methods of ThreadGroup class

The following are the various methods used in the ThreadGroup class:

  1. void checkAccess():

This method is used to check whether the currently running thread has the permission to modify the thread group or not.

  1. int activeCount():

This method is used to estimate the number of active threads present in the thread group and its subgroups and then it returns the number.

  1. int activeGroupCount():

This method is used to estimate and return the number of active groups in the thread groups and its subgroups.

  1. void destroy():

This method is used to destroy a thread group and all its subgroups.

  1. int enumerate(Thread[] list):

This method is used to copy every active thread in the thread group and its subgroups into the specified array

  1. int getMaxPriority():

This method is used to return the maximum priority of the thread group.

  1. string getName():

This method is used to return the name of the thread group.

  1. ThreadGroup getParent():

This method is used to return the parent of the thread group.

  1. void interrupt():

This method is used to interrupt all threads in the thread group.

  1. boolean isDaemon():

This method returns true if the thread group is a daemon thread group otherwise return false.

  1. void setDaemon(boolean daemon):

This method is used to modify the daemon status of the thread group.

  1. boolean isDestroyed():

This method returns true if the thread group has been destroyed otherwise returns false.

  1. void list():

This method is used to print the information related to the thread group to the standard output.

  1. boolean parentOf(ThreadGroup g):

This method returns true if the thread group is either the thread group argument or one of its ancestor thread groups otherwise returns false.

  1. void suspend():

This method suspends all thread in the thread group.

  1. void resume():

This method resumes all the threads in the thread group that were suspended before with the suspend() method.

  1. void setMaxPriority(int pri):

This method is used to set the priority of the group to the maximum.

  1. void stop():

This method stops all the threads in the thread group.

  1. string toString():

This method is used to return a string representation of the thread group.

Java Shutdown Hook

The shutdown hook is used in Java when the program shuts down normally or abruptly to save the state of the code or to clean up the resources. Here, cleaning up the resources means closing log file and sending alerts. Therefore, the shutdown hook is used to execute codes before the program shuts down.

When does the JVM shut down?

The JVM shuts down in the following conditions:

  • When the programmer presses the ctrl+c on the command prompt.
  • When the user logs off.
  • When the System.exit(int) method is called on.
  • When the user shutdowns the program.

The addShutdownHook(Thread hook) method

The addShutdownHook() method registers the thread with the virtual machine. The syntax of this method is:

  • public void addShutdownHook(Thread hook){}

The static factory method getRuntime() is used to obtain the object of the runtime class.

Factory method

The factory method is used to return the instance of a class.

How to perform a single task by multiple threads?

Only one run() method is used when the programmer wants to perform one task by many threads.

How to perform multiple tasks by multiple threads?

Multiple run() methods are used when the programmer wants to perform multiple tasks by multiple threads.

Garbage collection

In Java, the meaning of garbage is unreferenced objects. So, garbage collection is the process of destroying these unused objects. In other words, it is the process that automatically reclaims the runtime unused memory.

To destroy the unused objects, the free() function is used in C language and the C++ uses the delete() function. But this function is carried by the Java itself so it is said that the memory management of Java is better than other languages.

Benefits of garbage collection

  • Since the garbage collector destroys the unused objects from the heap memory, it makes Java memory efficient.
  • No extra efforts are needed as the JVM automatically performs the garbage collection function.

How can an object be unreferenced?

There are many ways that can make an object unreferenced and a few of them are:

  • By nulling the reference
  • By assigning a reference to another
  • By anonymous object

The finalize() method

The finalize() method is called on before each object is garbage collected. It is used to perform clean up processing. The syntax of this method is:

  • protected void finalize(){}

The gc() method

The gc() method is used to call the garbage collector to carry out the cleanup processing. This method is present in the system and the runtime classes and its syntax is:

  • public static void gc(){}

Java Runtime class

The Java runtime class interacts with the Java runtime environment. The class provides various methods that are used in executing a process, calling on the garbage collector, and getting total and free memory. A single instance of the java.lang.Runtime class is there for a single Java application.

The Runtime.getRuntime() method is used to return the singleton instance of the runtime class.

Important methods of Java Runtime class

  1. public static Runtime getRuntime():

This method is used to return the instance of the runtime class.

  1. public void exit(int status):

This method is used to destroy the current virtual machine.

  1. public void addShutdownHook(Thread hook):

This method is used to register a new hook thread.

  1. public Process exec(String command)throws IOException:

This method is used to execute a specific command in a separate process.

  1. public int availableProcessors():

This method is used to figure out the total number of processors that are available.

  1. public long freeMemory():

This method is used to figure out the amount of free memory in the JVM.

  1. public long totalMemory():

This method is used to figure out the total memory in the JVM.

How to shut down the system in Java?

The shutdown -s command is used to shut down the system in Java. The -r switch is used to restart the system and the -t switch is used to specify the time delay.

Java synchronization

In Java, synchronization is the capability that controls the access of multiple threads to every shared resource.  When the programmer wants to allow only a single thread to access the shared resource, the Java synchronization is the best option to use.

Why is synchronization used?

The main uses of synchronization in Java are:

  • In order to prevent the interference of the thread
  • In order to prevent the problem of consistency

Type of synchronization:

The following are the two types of synchronization:

  • Process synchronization
  • Thread synchronization

Only thread synchronization will be dealt with in this chapter.

Thread synchronization

The following is the classification of the thread synchronization:

  1. Mutual Exclusive:
  2. Synchronized method
  3. Synchronized blocked
  4. Static synchronization
  5. Cooperation (Inter-thread communication)

Mutual Exclusive

The mutual exclusive is a type of thread synchronization that prevents the threads from interfering with each other while the data is being shared. There are three ways to achieve this in Java and they are:

  • By synchronized method
  • By synchronized block
  • By static synchronization

The concept of lock in Java

The lock is an internal entity in Java around which the synchronization is built. It is also known as a monitor and the lock is associated with all the objects. Through convention, a thread must first acquire an object’s lock before accessing the object’s field. After achieving consistent access to the object’s fields, the thread must then release the lock of the object.

The java.util.concurrent.locks package has several lock implementation added since the Java 5.

Java synchronized method

A synchronized method is a method that is declared as synchronized. It locks an object for any shared resource. A thread automatically acquires the lock for an object when it calls on a synchronized method and the thread then releases the lock after its job has been completed.

Synchronized block in Java

The synchronized block is used to perform synchronization on any particular resource of the method. The synchronized block can be used to synchronize only a few lines when there are many lines of code in the method. The program will work as same as the synchronized block when the programmer puts all the codes of the method inside the synchronized block.

Main points to remember for the synchronized block

  • The main function of the synchronized block is to lock an object for any shared resources.
  • The scope of the synchronized block is smaller than that of the method.

Static synchronization

If the programmer declared any static method as synchronized, then the lock will be on the class rather than on the object.

The problem without static synchronization

The static synchronization helps to remove the problem of interference between objects of a shared class.

Deadlock in Java

Deadlock is a part of multithreading in Java. Suppose there is a thread waiting for a lock of an object which is currently acquired by another thread and the second thread is waiting for a lock on an object that is currently acquired by the first thread. Deadlock appears in this situation. This case is known as deadlock because both the threads are waiting for each other to release the object’s lock.

Inter-thread communication in Java

The definition of inter-thread communication is the communication between synchronized threads in the Java. It is also known as co-operation. It is the process in which one thread that is currently running is paused in its critical section and another thread is allowed to lock in the same critical section and is executed. The inter-thread communication is implemented by the methods of the object class mentioned below:

  • wait()
  • notify()
  • notifyAll()
  1. wait() method

The wait() method is used to make the current thread release the lock and make it wait until another thread calls on the notify() method or the notifyAll() method for the object or for a specific amount of time. It can only be invoked from the synchronized method because the current thread should own this object’s monitor. If not, the method with throw an exception. The following are the syntaxes of the wait() method:

  • public final void wait():

This method causes the current thread to wait until the object is notified.

  • public final void wait(long timeout):

This method causes the current thread to wait for a particular amount of time.

  1. notify() method

The notify() method is used to wake up a single thread that was paused by using the wait() method. One of the threads that are waiting on the object’s lock is selected arbitrarily and awakened using this method. The following is the syntax of the notify() method:

  • public final void notify()
  1. notifyAll() method

The notifyAll() method wakes up all the threads that were paused by using the wait() method and are waiting on the object’s lock. The following is the syntax of this method:

  • public final void notifyAll()

Understanding the process of inter-thread communication

The following are the main points needed to understand the process of inter-thread communication:

  1. In the first step, threads enter to acquire an object’s monitor.
  2. The thread then acquires the monitor.
  3. If the programmer invokes the wait() method, the thread is paused. Otherwise, it will release the monitor and exit.
  4. When the programmer invokes the notify() method or the notifyAll() method, the thread that is paused will move to the runnable state.
  5. The thread again becomes available to acquire monitor.
  6. After the thread completes its task, it releases the monitor and exits.

Why are these methods defined in object class rather than in the thread class?

The wait(), notify(), and notifyAll() methods are defined in object class and not in the thread class because these methods are related to lock or monitor and the objects have the lock.

Dissimilarities between wait and sleep method

There are various dissimilarities between the wait and the sleep method and they are:

  1. The wait method releases the lock but the sleep method does not.
  2. The wait method is of object class but the sleep method is of the thread class.
  3. The wait method is a non-static method. Whereas, the sleep method is a static one.
  4. The thread becomes active after the wait method has been called by invoking the notify method or the notifyAll method. However, the thread becomes active after a specified amount of time when the sleep method is invoked to make them sleep.

Interrupting a thread

The interrupt() method is used to break put the sleeping or the waiting state of the threads that are in those states after the sleep() method or the wait() method had been invoked on them. This method does so by throwing an InterruptedException and performs normal behavior if it has been invoked while a thread is not in a waiting or in a sleeping state. In this situation, the method sets the interrupt flag to true but does not actually interrupt the thread. Let’s first deal with the methods that are provided by the thread class to interrupt a thread.

Methods provided by the thread class to interrupt a thread

There are three methods that are used to interrupt a thread and they are:

  • public void interrupt():

This method is used to interrupt a thread from the waiting or the sleeping state.

  • public static boolean interrupted():

This method returns true if the static thread has been interrupted otherwise returns false.

  • public boolean isInterrupted():

This method returns true if the thread has been interrupted otherwise returns false.

Reentrant Monitor in Java

The Sun Microsystems defines the Java monitors as a reentrant. This means that a thread can reuse the same monitor for different synchronized methods in the case in which the method is called from the method.

The benefits of reentrant monitor

The reentrant monitor removes the possibility of deadlocking a single thread.

Java I/O

Java I/O is the part of the program that processes the input and produces the output. The concept of the stream is used to make the I/O operation fast. All the classes necessary for input and output operations are included in the java.io.package. Through the Java I/O API, file handling can be performed in the Java.

Stream

In Java, a stream is a sequence of data that is composed of bytes. Since its structure looks like a stream of water that flows continually, it is called a stream.

There are three streams that the Java automatically creates for the programmer and all of the three streams are attached with the console. The following are the three types of stream:

  1. out:

It is the standard output stream.

  1. in:

It is the standard input stream.

  1. err:

It is the standard error stream.

OutputStream vs. InputStream

The OutputStream and InputStream classes are explained below:

OutputStream

The output stream is used by Java in order to write data to the destination. The said data may be a file, an array, socket, or a peripheral device.

InputStream

The input stream is used by Java in order to read data such as a file, an array, socket, or a peripheral device from the source.

OutputStream class

The OutputStream class is a type of abstract class. It is a superclass among other classes that represents the output stream of bytes. Here, the output stream accepts output bytes and moves them to some sink.

Methods used by the OutputStream

The following are the methods of the OutputStream:

  • public void write(int):

This method writes a byte to the present output stream.

  • public void write(byte[]):

This method writes an array of byte to the present output stream.

  • public void flush():

This method is used to flush the present output stream.

  • public void close():

This method closes the present output stream.

OutputStream Hierarchy

OutputStream:

  1. FileOutputStream
  2. ByteArrayOutputStream
  3. FilterOutputStream
  4. DataOutputStream
  5. BufferedOutputStream
  6. PrintStream
  7. PipedOutputStream
  8. ObjectOutputStream

InputStream class

The InputStream class is also a type of an abstract class. It is a superclass among other classes that represent the input stream of bytes.

Methods used by the InputStream

The following are the methods of the InputStream:

  • public abstract int read():

This method is used to read the next byte of data from the input stream and at the end of the file, it returns -1.

  • public int available():

This method is used to figure out the number of bytes that can be read from the present input stream.

  • public void close():

This method closes the current input stream.

InputStream Hierarchy:

InputStream:

  1. FileInputStream
  2. ByteArrayInputStream
  3. FilterInputStream
  4. DataInputStream
  5. BufferedInputStream
  6. PushBackInputStream
  7. PipedInputStream
  8. ObjectInputStream

Java FileOutputStream Class

The FileOutputStream is a type of the output stream that is used in Java to write data to a file. This class is used when the programmer has to write primitive values into a file. Both byte-oriented and character-oriented data can be written by using this class. However, the FileWriter is more preferred than the FileOutputStream class to write the character-oriented data.

FileOutputStream class declaration

The declaration of the Java.io.FileOutputStream class is:

  • public class FileOutputStream extends OutputStream

FileOutputStream class methods:

The following are the methods that are used in the FileOutputStream class:

  • protected void finalize():

This method is used to clean up the connection among the file output stream.

  • void write(byte[] ary):

This method writes ary.length bytes from the byte array to the file output stream.

  • void write(byte[] ary, int off, int len):

This method writes len bytes from the byte array beginning at offset off to the file output stream.

  • void write(int b):

This method writes the specified byte to the file output stream.

  • FileChannel getChannel():

This method returns the file channel object associated with the file output stream.

  • FileDescriptor getFD():

This method returns the file descriptor associated with the stream.

  • void close():

This method closes the file output stream.

Java FileInputStream Class:

The Java FileInputStream class is used to get the input bytes from a file. It reads byte-oriented data like image data, video, and audio which are streams of raw bytes. This class can also read character-stream data but the FileReader class is more preferred for such data than the FileInputStream class.

Java FileInputStream class declaration

The declaration of the java.io.FileInputStream class is as follows:

  • public class FileInputStream extends InputStream

Java FileInputStream class methods

The following are the methods used by the FileInputStream class:

  1. int available():

This method estimates the number of bytes that can be read from the input stream and returns it.

  1. int read():

This method reads the byte of data from the input stream.

  1. int read(byte[] b):

This method reads up to b.length bytes of data from the input stream.

  1. int read(byte[] b, int off, int len):

This method reads up to len bytes of data from the input stream.

  1. long skip(long x):

This method skips over and discards x bytes of data from the input stream.

  1. FileChannel getChannel():

This method returns the unique FileChannel object associated with the file input stream.

  1. FileDescriptor getFD():

This method is used to figure out the FileDescriptor object.

  1. protected void finalize():

This method ensures that the close method is invoked only if there is no more reference to the file input stream.

  1. void close():

This method closes the stream.

Java BufferedOutputStream Class

The main function of the BufferedOutputStream class is to buffer an output stream. It internally makes the use of the buffer in order to store data which adds more efficiency than to write data into the stream directly. This makes the performance of the program better.

The syntax for adding the buffer in the OutputStream is as following:

  • OutputStream os= new BufferedOutputStream(new FileOutputStream(“D:\\IO Package\\testout.txt”));

Java BufferedOutputStream class constructors

The following are the constructors used in the Java BufferedOutputStream class:

  • BufferedOutputStream(OutputStream os):

This constructor is used to create a new buffered output stream that is used to write the data to a particular output stream.

  • BufferedOutputStream(OutputStream os, int size):

This constructor is used to create a new buffered output stream that is used to write the data to a particular output stream with a specific buffer size.

Java BufferedOutputStream class methods:

The following are the methods used in the Java BufferedOutputStream class:

  • void write(int b):

This method is used to write a particular byte to the buffered output stream.

  • void write(byte[] b, int off, int len):

This method is used to write the byte from a particular byte-input stream into a particular byte array, beginning with the offset provided.

  • void flush():

This method is used to flush the buffered output stream.

Java BufferedInputStream Class:

The Java BufferedInputStream Class reads the information from the stream. It makes use of the buffer mechanism internally in order to increase the performance of the program.

These are the main points to remember about BufferedInputStream:

  • The internal buffer is automatically refilled many bytes at a time from the contained input stream when the bytes from the stream are skipped or read.
  • An internal buffer array comes into existence when a BufferedInputStream comes into existence.

Java BufferedInputStream class declaration:

The following is the declaration of the Java.io.BufferedInputStream class:

  • public class BufferedInputStream extends FilterInputStream

Java BufferedInputStream class constructors:

The following are the two constructors used by the Java BufferedInputStream class:

  • BufferedInputStream(InputStream IS):

This constructor creates the BufferedInputStream and saves the input stream and the argument for later purposes.

  • BufferedInputStream(InputStream IS, int size):

This constructor is used to create the BufferedInputStream with a particular buffer size and to save the argument and input stream for later purposes.

Java BufferedInputStream class methods

The following are the methods used in the Java BufferedInputStream class:

  • int available():

This method is used to find out the number of bytes that can be read from the input stream which does not block the following invocation method for the input stream.

  • int read():

This method is used to read the following bye of data from the input stream.

  • int read(byte[] b, int off, int ln):

This method is used to read the bytes from a particular byte-input stream into a specified byte array, beginning with the offset provided.

  • void close():

This method is used to close the input stream and release any of the system resources related to the stream.

  • void reset():

This method is used to change the position of the stream to the position at which the mark method was last called on this input stream.

  • void mark(int readlimit):

This method is used to view the common contract of the mark method of the input stream.

  • long skip(long x):

This method is used to skip over and remove x bytes of data from the input stream.

  • boolean markSupported():

This method is used to check whether the input stream supports the mark and reset methods or not.

Java SequenceInputStream Class

The SequenceInputStream Class reads the data from multiple streams in Java. The data is read one by one in the class.

Java SequenceInputStream Class declaration

The following is the declaration of the Java.io.SequenceInputStream class:

  • public class SequenceInputStream extends InputStream

Constructors of SequenceInputStream class

The following are the two constructors used by the SequenceInputStream class:

  • SequenceInputStream(InputStream s1, InputStream s2):

This constructor is used to make a new input stream by reading the data of two input stream in order i.e. first s1 and then s2.

  • SequenceInputStream(Enumeration e):

This constructor is used to make a new input stream by reading the data of enumeration whose type is InputStream.

Methods of SequenceInputStream class

The following are the methods of the SequenceInputStream class:

  • int read():

This method reads the following byte of data from the input stream.

  • int read(byte[] ary, int off, int len):

This method reads len bytes of data from the input stream into the array of bytes.

  • int available():

This method is used to find out the maximum number of the byte which can be read from an input stream.

  • void close():

This method closes the input stream.

Java ByteArrayOutputStream Class

In Java, the ByteArrayOutputStream Class writes common data into various files. In this stream, the data gets written into a byte array that can be written to various streams in the future. It holds a copy of data and then forwards it to various streams. The buffer of the ByteArrayOutputStream automatically grows based on the data.

Java ByteArrayOutputStream class declaration

The declaration of the Java.io.ByteArrayOutputStream class is as follows:

  • public class ByteArrayOutputStream extends OutputStream

Java ByteArrayOutputStream class constructors

The following are the constructors used by the ByteArrayOutputStream class:

  • ByteArrayOutputStream():

This constructor is used to create a new byte array output stream which has the capacity of 32 bytes in the beginning. The size can be further increased if required.

  • ByteArrayOutputStream(int size):

This constructor is used to create a new byte array output stream that has the buffer capacity of a specific size in bytes.

Java ByteArrayOutputStream class methods

The following are the methods that are used in the ByteArrayOutputStream class:

  • int size():

This method is used to find out the present size of the buffer.

  • byte[] toByteArray():

This method makes a newly allocated byte array.

  • String toString():

This method converts the content to a string decoding bytes through the use of a platform default char set.

  • String toString(String charsetName):

This method converts the content into a string decoding bytes through the use of a particular charsetName.

  • void write(int b):

This method writes the byte that is specific to the byte array output stream.

  • void write(byte[] b, int off, int len:

This method writes len bytes from a particular byte array beginning from the offset off to the byte array output stream.

  • void writeTo(OutputStream out):

This method writes the complete content of a byte array output stream to a particular output stream.

  • void reset():

This method resets the count field of a byte array output stream to a zero value.

  • void close():

This method closes the ByteArrayOutputStream.

Java ByteArrayInputStream Class

There are two parts in the ByteArrayInputStream and they are ByteArray and InputStream. This class reads byte array as an input stream. It makes use of an internal buffer to read data from a byte array. The buffer of the ByteArrayInputStream automatically increases on the basis of the data.

Java ByteArrayInputStream class declaration

The declaration of the ByteArrayInputStream class is as follows:

  • public class ByteArrayInputStream extends InputStream

Java ByteArrayInputStream class constructors:

The following are the two constructors used in the ByteArrayInputStream class:

  • ByteArrayInputStream(byte[] ary):

This constructor is used to make a new byte array input stream that makes the use of ary as its buffer array.

  • ByteArrayInputStream(byte[] ary, int offset, int len):

This constructor is used make a new byte array input stream that makes the use of ary as its buffer array that can read up to a particular len byte of data from an array.

Java ByteArrayInputStream class methods

The following are the methods used in the ByteArrayInputStream class:

  • int available():

This method is used to find out the number of remaining bytes which can be read from the input stream.

  • int read():

This method reads the following bye of data from the input stream.

  • int read(byte[] ary, int off, int len):

This method reads up to len bytes of data from an array of bytes in the input stream.

  • boolean markSupported():

This method returns true if the input stream has mark and reset method otherwise returns false.

  • long skip(long x):

This method finds the x bytes of input from the input stream and skips them.

  • void mark(int readAheadLimit):

This method sets the present marked position in the stream.

  • void reset():

This method resets the buffer of a byte array.

  • void close():

This method closes the ByteArrayInputStream.

Java DataOutputStream Class

The function of the DataOutputStream Class in Java is to permit an application to write primitive Java data types to the output stream in a way that is not dependent to the machine. This class is normally used by the Java to write data which can be read by a data input stream in the future.

Java DataOutputStream class declaration

The following is the declaration of this class:

  • public class DataOutputStream

Java DataOutputStream class methods

The following are the methods that are used by the DataOutputStream class:

  • int size():

This method is used to find out the number of bytes written to the data output stream.

  • void write(int b):

This method writes a particular byte to the underlying output stream.

  • void write(byte[] b, int off, int len):

This method writes len bytes of data to the output stream.

  • void writeBoolean(boolean v):

This method writes a Boolean statement as a 1-byte value to the output stream.

  • void writeChar(int v):

This method writes a character as a 2-byte value to the output stream.

  • void writeChars(String s):

This method writes the string as a sequence of characters to the output stream.

  • void writeByte(int v):

This method writes a byte as a 1-byte value to the output stream.

  • void writeBytes(String s):

This method writes the string as a sequence of bytes to the output stream.

  • void writeInt(int v):

This method writes an int to the output stream.

  • void writeShort(int v):

This method writes a short to the output stream.

  • void writeLong(long v):

This method writes a long to the output stream.

  • void writeUTF(String str):

This method writes a string to the output string by making the use of the UTF-8 encoding in a portable manner

  • void flush():

This method flushes the data output stream.

Java DataInputStream Class

The function of the DataInputStream Class in Java is to permit an application to read primitive Java data types from the input stream in a way that is not dependent to the machine. This class normally makes use of the data output stream in order to write data which can be read by a data input stream in the future.

Java DataInputStream class declaration:

The following is the declaration of this class:

  • public class DataInputStream

Java DataInputStream class Methods:

The following are the methods used in the DataInputStream class:

  • int read(byte[] b):

This method reads the number of bytes from the input stream.

  • int read(byte[] b, int off, int len):

This method reads the len bytes of data from the input stream.

  • int readInt():

This method returns an int value after reading the input bytes.

  • byte readByte():

This method returns the one input byte after reading it.

  • char readChar():

This method returns a character value after reading two input bytes.

  • double readDouble():

This method returns a double value after reading eight input bytes.

  • boolean readBoolean():

This method checks whether or not a byte is a non zero value by reading the input byte. It returns true if the byte is non zero otherwise returns false.

  • int skipBytes(int x):

This method finds x bytes of data from the input stream and skips it.

  • String readUTF():

This method reads a string that has been encoded by using the UTF-8 format.

  • void readFully(byte[] b):

This method stores bytes from the input stream into a buffer array after reading them.

  • void readFully(byte[] b, int off, int len):

This method reads len bytes from the input stream.

Java FilterOutputStream Class

The Java FilterOutputStream Class is not used individually as it provides various subclasses to add more functionality. BufferedOutputStream and DataOutputStream are some of the subclasses that this class uses in order to implement the OutputStream class.

Java FilterOutputStream class declaration

The following is the declaration of this class:

  • public class FilterOutputStream extends OutputStream

Java FilterOutputStream class Methods

The following are the methods used in the FilterOutputStream class:

  • void write(int b):

This method writes a particular byte to the output stream.

  • void write(byte[] ary):

This method writes ary.lenght to the output stream.

  • void write(byte[] b, int off, int len):

This method writes len bytes from the offset off to the output stream.

  • void flush():

This method flushes the output stream.

  • void close():

This method closes the output stream.

Java FilterInputStream Class

The FilterInputStream Class is not used individually in Java as it provides various subclasses to add more functionality. BufferedInputStream and DataInputStream are some of the subclasses of this class that are used to implement the InputStream.

Java FilterInputStream class declaration

The following is the declaration of this class:

  • public class FilterInputStream extends InputStream

Java FilterInputStream class Methods

The following are the methods that are used in the FilterInputStream class:

  • int available():

This method estimates the number of bytes which can be read from the input stream and returns the number.

  • int read():

This method reads the following byte of data from the input stream.

  • int read(byte[] b):

This method reads up to the byte.length bytes of data from the input stream.

  • long skip(long n):

This method skips over and destroys n bytes of data from the input stream.

  • boolean markSupported():

This method returns true if the input stream supports the mark and the reset method otherwise returns false.

  • void mark(int readlimit):

This method marks the present position of the input stream.

  • void reset():

This method resets the input stream.

  • void close():

This method closes the input stream.

Java ObjectStreamClass

The ObjectStreamClass of Java includes the name and serialVersionUID of the class. This class works as a serialization descriptor for other class.

Fields

  • static ObjectStreamField[]NO_FIELDS:

This field contains the serialPersistentFields value that does not indicate the serializable fields

Methods

The following are the methods used in the ObjectStreamClass:

  • Class<?> forClass():

This method is used to return the class in the local virtual-machine that is mapped to this version.

  • ObjectStreamField getField(String name):

This method is used to find out the field of this class by name.

  • ObjectStreamField[] getFields():

This method is used to find out an array of the fields of this serialization class and return it.

  • String getName():

This method is used to find out the name of the class described by this descriptor and return it.

  • Long getSerialVersionUID():

This method is used to find out the serialVersionUID for this class and return it.

  • Static ObjectStreamClass lookup(Class<?> cl):

This method is used to figure out the descriptor for a class which can be serialized.

  • Static ObjectStreamClass lookupAny(Class<?> cl):

This method is used to find out the descriptor for any class that may or may not implement serializable and to return it.

  • String toString():

This method is used to find out the string that describes the ObjectStreamClass and return it.

Java ObjectStreamField class

The ObjectStreamField class is used to get the field of a class by name. It is the definition of a serializable field from a serializable class and is used to declare the serializable fields of a class.

Constructors

The following are the constructors used in the ObjectStreamField class:

  • ObjectStreamField(String name, Class<?> type):

This constructor is used to make a serializable field with a particular type.

  • ObjectStreamField(String name, Class<?> type, boolean unshared):

This constructor is used to make an ObjectStreamField that represents a serializable field with the name and type provided.

Methods

The following are the methods that are used in the ObjectStreamField class:

  • int compareTo(Object obj):

This method is used to compare the ObjectStreamField with another field.

  • string getName():

This method returns the name of the field.

  • int GetOffset():

This method returns the Offset of a field within the instance data.

  • Class<?> getType():

This method returns the type of the field.

  • char getTypeCode():

This method is used to find out the character encoding of field type and return it.

  • string getTypeString():

This method is used to find the JVM type signature and return it.

  • boolean isPrimitive():

This method is used to check whether the field has a primitive type or not.

  • boolean isUnshared():

This method returns true if the serializable field represented by this ObjectStreamField instance is unshared otherwise returns false.

  • protected void setOffset(int offset):

This method returns the Offset within the instance data.

  • string toString():

This method is used to find out the string that defines this field.

The character encoding of the field type that is returned by the public char getTypeCode() is as follows:

B          byte

C          char

D          double

F          float

I           int

J           long

L          class or interface

S          short

Z          boolean

[           array

Java console class

The console class in Java gets the input from the console and gives methods to read text and passwords. The password will not be displayed to the user if it is read by using the console class. The console class is internally attached to the system console and was added since the JVM 1.5.

Java Console class declaration

The following is the declaration of this class:

  • public final class Console extends Object implements Flushable

Java Console class methods

The following are the methods that are used in the Java console class:

  • Reader reader():

This method is used to retrieve the read object attached to the console.

  • String readLine():

This method reads a single line of text from the console.

  • String readLine(String fmt, Object… args):

This method is used to give a formatted prompt that reads a single line of text from the console.

  • char[] readPassword():

This method reads a password that is not being shown on the console.

  • char[] readPassword(String fmt, Object… args):

This method is used to give a formatted prompt that reads the password that is not being shown on the console.

  • Console format(String fmt, Object… args):

This method is used to writes a string to the console output stream in a formatted way.

  • Console printf(String format, Object… args):

This method is used to retrieve the PrintWriter object that is attached with the console.

  • PrintWriter writer():

This method flushed the console.

The way to get the object of a console

The following method is used to get the singleton instance of Console class:

  • public static Console console(){}

Java FilePermission Class

The FilePermission Class in Java includes the permission associated with a directory or a file. The path on which all the permissions are associated with are of two types and they are:

  • D:\\IO\\-:

This path shows that the permission is related to all sub directories and files recursively.

  • D:\\IO\\*:

This path shows that the permission is related to all directory and files inside the current directory excluding sub directories.

Java FilePermission class declaration

The following is the declaration of this class:

  • public final class FilePermission extends Permission implements Serializable

Constructors of FilePermission class

The following are the constructors that are used in the FilePermission class:

  • ByteArrayOutputStream():

This constructor is used to create a new byte array output stream that has the capacity of 32 bytes in the beginning. However, its size can be later raised if required.

  • ByteArrayOutputStream(int size):

This constructor is used to make a new byte array output stream with a buffer capacity of a particular size in bytes.

Methods of FilePermission class

The following are the methods that are used in the FilePermission class:

  • int hashCode():

This method is used to find out the hash code value of an object and returns it.

  • String getActions():

This method is used to find out the canonical string representation of an action and returns it.

  • boolean equals(Object obj):

This method returns true if two FilePermission objects are equal otherwise returns false.

  • boolean implies(Permission p):

This method returns true in the case in which the FilePermission object has a particular permission otherwise returns false.

  • PermissionCollection newPermissionCollection():

This method finds out the new PermissonCollection object for storing the FilePermission object and returns it.

Java Writer

The writer class in Java is an abstract class. Its main function is to write character streams. Some of the methods that are implemented by the subclass are write(char[], int, int), flush(), and close(). The methods mentioned here are overridden by the subclasses in order to increase the efficiency and functionality.

Fields

  • protected Object lock:

This field includes the object that is used to synchronize operations on this stream.

Constructors

The following are the constructors that are used in the writer class:

  • protected writer():

This constructor is used to create a new character-stream writer of which critical sections synchronizes itself on the writer.

  • protected Writer(Object lock):

This constructor is used to create a new character-stream writer of which critical sections will synchronize on the object provided.

Methods

The following are the methods that are used in the writer class:

  • writer append(char c):

This method is used to combine a particular character to the current writer.

  • writer append(CharSequence csq):

This method is used to combine a particular character sequence to the current writer.

  • writer append(CharSequence csq, int start, int end):

This method is used to combine a subsequence of a particular character sequence to the current writer.

  • abstract void close():

This method is used to close the stream after the stream has been flushed.

  • abstract void flush():

This method is used to flush the stream.

  • void write(char[] cbuf):

This method is used to write an array of characters.

  • abstract void write(char[] cbuf, int off, int len):

This method is used to write a part of an array of characters.

  • void write(int c):

This method is used to write a single character.

  • void write(String str):

This method is used to write a string.

  • void write(String str, int off, int len):

This method is used to write a part of a string.

Java reader

The reader class in Java is an abstract class. It reads character streams. The methods that are implemented by the subclass are read(char[], int, int) and close(). Some of these methods are overridden by the subclass in order to increase the efficiency and the functionality. BufferedReader, PipedReader, FilterReader, StringReader, InputStreamReader, FilterReader, and CharArrayReader are a few of the implementation classes.

Fields

  • protected Object lock:

This field includes the object that synchronizes the operations on the current stream.

Constructors

The following are the constructors that are used in the reader class:

  • protected Reader():

This constructor is used to create a new character-stream reader of which critical sections will synchronize on the reader itself.

  • protected Reader(Object lock):

This constructor is used to create a new character-stream reader of which critical sections will synchronize on the object provided.

Methods

The following are the methods that are used in the reader class:

  • abstract void close():

This method is used to close the stream and release any system resources related to it.

  • void mark(int readAheadLimit):

This method is used to mark the current position in the stream.

  • boolean markSupported():

This method returns true if the current stream supports the mark operation otherwise returns false.

  • int read():

This method is used to read a single character.

  • int read(char[] cbuf):

This method is used to read characters into an array.

  • abstract read(char[] cbuf, int off, int len):

This method is used to read characters into a part of an array.

  • int read(CharBuffer target):

This method is used to attempt to read characters into a particular character buffer.

  • boolean ready():

This method returns true if the stream is ready to be read otherwise returns false.

  • void reset():

This method is used to reset the stream.

  • long skip(long n):

This method is used to skip the characters.

Java FileWriter Class

In Java, the FileWriter Class writes character-oriented data to a file. This class is derived from the character and handles the file in Java. The strings must be converted into a byte array in the FileOutputStream class but this is not necessary for this class because the methods provided by this class can directly write strings.

Java FileWriter class declaration

The following is the declaration of this class:

  • public class FileWriter extends OutputStreamWriter

Constructors of FileWriter class

The following are the constructors that are used in the FileWriter class:

  • FileWriter(String file):

This constructor is used to create a new file with the name in the string.

  • FileWriter(File file):

This constructor is used to create a new file with the name in the file object.

Methods of FileWriter class

The following are the methods that are used in the FileWriter class:

  • void write(String text):

This method writes a string into the FileWriter.

  • void write(char c):

This method writes a character into the FileWriter.

  • void write(char[] c):

This method writes a character array into the FileWriter.

  • void flush():

This method flushes the data of the FileWriter.

  • void close():

This method closes the FileWriter.

Java FileReader Class

In Java, the FileReader Class reads data from the file. Like the FileInputStream class, this class is used to return data in byte format. The class is derived from the character and handles the file in Java.

Java FileReader class declaration

The following is the declaration of this class:

  • public class FileReader extends InputStreamReader

Constructors of FileReader class

The following are the constructors that are used in the FileReader class:

  • FileReader(String file):

This constructor is used to find out the file name in the string. The provided file is opened in the reading mode by it and the constructor throws FileNotFoundException if there is no such file in the program.

  • FileReader(File file):

This constructor is used to find the file name is the file instance. The provided file is opened in the reading mode by the constructor and it throws FileNotFoundException if such file does not exist.

Methods of FileReader class

The following are the methods that are used in the FileReader class:

  • int read():

This method is used to find out a character in ASCII form and returns it. At the end of the file, this method returns -1.

  • void close():

This method closes the FileReader class.

Java BufferedWriter Class

In Java, the BufferedWriter class provides buffering for the writer instances. This class inherits the writer class and increases the performance of the program. Here, the buffering characters provide efficient writing of single arrays, strings, and characters.

Class declaration

The following is the declaration of this class:

  • public class BufferedWriter extends Writer

Class constructors

The following are the constructors that are used in this class:

  • BufferedWriter(Writer wrt):

This constructor creates a buffered character output stream which makes uses of the default size for an output buffer.

  • BufferedWriter(Writer wrt, int size):

This constructor creates a buffered character output stream which makes use of a particular size for an output buffer.

Class methods

The following are the constructors that are used in this class:

  • void newLine():

This method writes a line separator to add a new line.

  • void write(int c):

This method writes a single character.

  • void write(char[] cbuf, int off, int len):

This method writes a part of an array of characters.

  • void write(String s, int off, int len):

This method writes a part of a string.

  • void flush():

This method flushes the input stream.

  • void close():

This method closes the input stream.

Java BufferedReader Class

In Java, the BufferedReader Class reads the text from the input stream that is based on the character. This class inherits the reader class and increases the performance of the program. Here, the readLine() method reads the data line by line.

Java BufferedReader class declaration

The following is the declaration of this class:

  • public class BufferedReader extends Reader

Java BufferedReader class constructors

The following are the constructors that are used in the BufferedReader class:

  • BufferedReader(Reader rd):

This constructor creates a buffered character input stream which makes use of the default size for an input buffer.

  • BufferedReader(Reader rd, int size):

This constructor creates a buffered character input stream which uses a particular size for an input buffer.

Java BufferedReader class methods

The following are the methods that are used in the BufferedReader class:

  • int read():

This method reads a single character.

  • int read(char[] cbuf, int off, int len):

This method reads characters into a part of an array.

  • boolean markSupported():

This method returns true if the input stream supports for the mark and the reset method otherwise returns false.

  • String readLine():

This method reads a line of text.

  • boolean ready():

This method returns true if the input stream is ready to be read otherwise returns false.

  • long skip(long n):

This method skips the characters.

  • void reset():

This method changes the position of the stream to such a position at which the mark method was called before on this input stream.

  • void mark(int readAheadLimit):

This method marks the current position in the stream.

  • void close():

This method is used to close the input stream and to release any of the system resources attached to the stream.

Java CharArrayReader Class

In Java, the CharArrayReader Class reads the character array as a stream. It inherits the reader class and contains two words: CharArray and Reader.

Java CharArrayReader class declaration

The following is the declaration of this class:

  • public class CharArrayReader extends Reader

Java CharArrayReader class methods

The following are the methods that are used in the CharArrayReader class:

  • int read():

This method reads a single character.

  • int read(char[] b, int off, int len):

This method finds the characters of a part of an array and reads them.

  • boolean ready():

This method returns true if the stream is ready to be read otherwise returns false.

  • boolean markSupported():

This method returns true if the stream supports the mark operation otherwise returns false.

  • long skip(long n):

This method skips the character in the input stream.

  • void mark(int readAheadLimit):

This method marks the current position in the stream.

  • void reset():

This method resets the stream to the last mark.

  • void close():

This method closes the stream.

Java CharArrayWriter Class

In Java, the CharArrayWriter class writes normal data to various files. It inherits the writer class and there is no point in invoking the close() method on this object. The buffer of this class automatically increases when data is written in this stream.

Java CharArrayWriter class declaration

The following is the declaration of this class:

  • public class CharArrayWriter extends Writer

Java CharArrayWriter class Methods

The following are the methods that are used in the CharArrayWriter class:

  • int size():

This method is used to find out the present size of the buffer and returns it.

  • char[] toCharArray():

This method is used to find out the copy of an input data and returns it.

  • String toString():

This method converts an input data to a string.

  • CharArrayWriter append(char c):

This method is used to combine a particular character to the writer.

  • CharArrayWriter append(CharSequence csq):

This method combines a particular character sequence to the writer.

  • void write(int c):

This method writes a character to the buffer.

  • void write(char[] c, int off, int len):

This method also writes a character to the buffer.

  • void write(String str, int off, int len):

This method writes a part of a string to the buffer.

  • void writeTo(Writer out):

This method writes the content of a buffer to another character stream.

  • void flush():

This method flushes the stream.

  • void reset():

This method resets the buffer.

  • void close():

This method closes the stream.

Java PrintStream Class

In Java, the PrintStream Class is used to provide methods that write data to another stream. The methods of this class do not throw IOException and there is no requirement to invoke the flush() method because this class flushes the data automatically.

Class declaration

The following is the declaration of this class:

  • public class PrintStream extends FilterOutputStream implements Closeable

Methods of PrintStream class

The following are the methods that are used in the PrintStream class:

  • void print(boolean b):

This method is used to print a particular boolean value.

  • void print(char c):

This method is used to print a particular character value.

  • void print(char[] c):

This method is used to print a particular character array values.

  • void print(int i):

This method is used to print a particular int value.

  • void print(long l):

This method is used to print a particular long value.

  • void print(float f):

This method is used to print a particular float value.

  • void print(double d):

This method is used to print a particular double value.

  • void print(String s):

This method is used to print a particular string value.

  • void print(Object obj):

This method is used to print a particular object value.

  • void println(boolean b):

This method is used to print a particular boolean value and then it destroys the line.

  • void println(char c):

This method is used to print a particular character value and then it destroys the line.

  • void println(char[] c):

This method is used to print a particular character array values and then it destroys the line.

  • void println(int i):

This method is used to print a particular int value and then it destroys the line.

  • void println(long l):

This method is used to print a particular long value and then it destroys the line.

  • void println(float f):

This method is used to print a particular float value and then it destroys the line.

  • void println(double d):

This method is used to print a particular double value and then it destroys the line.

  • void println(String s):

This method is used to print a particular string value and then it destroys the line.

  • void println(Object obj):

This method is used to print a particular object value and then it destroys the line.

  • void println():

This method is used only to destroy the line.

  • void printf(Object format, Object… args):

This method is used to write the formatted string to the present stream.

  • void printf(Locale l, Object format, Object… args):

This method is also used to write the formatted string to the present stream.

  • void format(Object format, Object… args):

This method is used to write the formatted string to the present stream by making the use of a particular format.

  • void format(Locale l, Object format, Object… args):

This method is also used to write the formatted string to the present stream by making the use of a particular format.

Java PrintWriter class

In Java, the PrintWriter class prints the formatted representation of the objects to the text-output stream. The writer class implements this class.

Class declaration

The following is the declaration of this class:

  • public class PrintWriter extends Writer

Methods of PrintWriter class

The following are the methods that are used in the PrintWriter class:

  • void println(boolean x):

This method prints a boolean value.

  • void println(char[] x):

This method prints an array of characters.

  • void println(int x):

This method prints an int.

  • PrintWriter append(char c):

This method combines a particular character to the writer.

  • PrintWriter append(CharSequence ch):

This method combines a subsequence of a particular character sequence to the writer.

  • PrintWriter append(CharSequence ch, int start, int end):

This method combines a subsequence of a particular character to the writer.

  • boolean checkError():

This method flushes the stream and returns true if the stream is an error state otherwise returns false.

  • protected void setError():

This method indicates that an error has occurred.

  • protected void clearError():

This method removes the error state of a stream.

  • PrintWriter format(String format, Object… args):

This method writes a formatted string to the writer using particular arguments and format string.

  • void print(Object obj):

This method prints an object.

  • void flush():

This method flushes a stream.

  • void close():

This method closes a stream.

Java OutputStreamWriter

In Java, the OutputStreamWriter class converts character stream to byte stream. In other words, the class is used to encode the characters to byte by using a particular charset. The write operation invokes the encoding converter that converts the character into bytes. The converted bytes are then grouped in a buffer before writing them to the underlying output stream.

The characters that are passed to the write operation are not buffered. This class is used along with the BufferedWriter in order to increase the performance of the program by avoiding frequent convertor invocation.

Constructor

The following are the constructors that are used in the OutputStreamWriter class:

  • OutputStreamWriter(OutputStream out):

This constructor is used to create an OutputStreamWriter that makes the use of the default character encoding.

  • OutputStreamWriter(OutputStream out, Charset cs):

This constructor is used to create an OutputStreamWriter that makes use of the charset provided.

  • OutputStreamWriter(OutputStream out, CharsetEncoder enc):

This constructor is used to create an OutputStreamWriter that makes use of the charset encoder provided.

  • OutputStreamWriter(OutputStream out, String charsetName):

This constructor is used to create an OutputStreamWriter that makes use of the charset named.

Methods

The following are the methods that are used in the OutputStreamWriter class:

  • void close():

This method is used to close a stream after first flushing it.

  • void flush():

This method is used to flush a stream.

  • string getEncoding():

This method is used to find out the name of the character encoding that this stream is using and return it

  • void write(char[] cbuf, int off, int len):

This method is used to write a part of an array of characters.

  • void write(int c):

This method is used to write a single character.

  • void write(String str, int off, int len):

This method is used to write a part of the string.

Java InputStreamReader

In Java, the InputStreamReader class is used to read bytes and then to decode them into characters by making use of a particular charset. So it is said that this class acts as a bridge between byte streams and the character streams. The character set that this class uses is either specified by the name or explicitly or maybe the default charset.

Constructor

The following are the constructors that are used in the InputStreamReader class:

  • InputStreamReader(InputStream in):

This constructor is used to create an InputStreamReader that makes use of the default charset.

  • InputStreamReader(InputStream in, Charset cs):

This constructor is used to create an InputStreamReader that makes use of the charset provided.

  • InputStreamReader(InputStream in, CharsetDecoder dec):

This constructor is used to create an InputStreamReader that makes use of the charset decoder provided.

  • InputStreamReader(InputStream in, String charsetName):

This constructor is used to create an InputStreamReader that makes use of the charset named.

Methods

The following are the constructors that are used in the InputStreamReader class:

  • void close():

This method is used to close a stream and to release system resources related to it.

  • string getEncoding():

This method is used to find out the name of the character encoding that the stream uses and return it.

  • int read():

This method is used to read a single character.

  • int read(char[] cbuf, int offset, int length):

This method is used to read characters into a part of an array.

  • boolean ready():

This method returns true if the stream is ready to be read otherwise returns false.

Java PushbackInputStream Class

In Java, the PushbackInputStream class is used to override the InputStream. This class increases the functionality of another input stream and is used to unread a byte that has already been read and is also used to push back one byte.

Class declaration

The following is the declaration of this class:

  • public class PushbackInputStream extends FilterInputStream

Class Methods

The following are the methods that are used by the PushbackInputStream class:

  • int available():

This method finds out the number of bytes that can be read from the input stream and returns it.

  • int read():

This method reads the following bytes of data from the input stream.

  • boolean markSupported():

This method returns true if the input stream supports the mark and the reset method otherwise returns false.

  • void mark(int readlimit):

This method marks the present position in the input stream.

  • long skip(long x):

This method skips over x bytes of data and then discards them.

  • void unread(int b):

This method copies the byte to the pushback buffer in order to push back the byte.

  • void unread(byte[] b):

This method copies an array of byte to the pushback buffer in order to push back the array.

  • void reset():

This method resets the input stream.

  • void close():

This method closes the input stream.

Java PushbackReader Class

In Java, the PushbackReader class pushes back a character into a stream. It is a character stream reader the class is also used to override the FilterReader class.

Class declaration

The following is the declaration of this class:

  • public class PushbackReader extends FilterReader

Class Methods

The following are the methods that are used in the PushbackReader class:

  • int read():

This method reads a single character.

  • void mark(int readAheadLimit):

This method marks the current position in the stream.

  • boolean ready():

This method returns true if the stream is ready to be read otherwise returns false.

  • boolean markSupported():

This method returns true if the stream supports the mark method otherwise returns false.

  • long skip(long n):

This method skips the character.

  • void unread (int c):

This method copies the character to the pushback buffer to push the character back.

  • void unread (char[] cbuf):

This method copies an array of character to the pushback buffer to push the array back.

  • void reset():

This method resets the stream.

  • void close():

This method closes the stream.

Java StringWriter Class

In Java, the StringWriter class is used to collect output from the string buffer that can be used to create a string. This class is a character stream and the writer class is inherited by it.

There is no need to close the StringWriter class as network sockets and files and other system resources like them are not used in the class.

Java StringWriter class declaration

The following is the declaration of this class:

  • public class StringWriter extends Writer

Methods of StringWriter class

The following are the methods that are used in the StringWriter class:

  • void write(int c):

This method writes a single character.

  • void write(String str):

This method writes a string.

  • void write(String str, int off, int len):

This method is used to write a part of the string.

  • void write(char[] cbuf, int off, int len):

This method writes a part of an array of characters.

  • String toString():

This method finds out the buffer current value as a string and returns it.

  • StringBuffer getBuffer():

This method finds out the string buffer and returns it.

  • StringWriter append(char c):

This method combines a particular character sequence to the writer.

  • StringWriter append(CharSequence csq):

This method combines a particular character sequence to the writer.

  • void flush():

This method flushes the stream.

  • void close():

This method closes the stream.

Java StringReader Class

In Java, the StringReader Class is a character stream that takes an input string and converts it into a character stream. The class has the string as a source and the reader class is inherited by it.

There is no need to close the StringReader class as network sockets and files and other system resources like they are not used in this class.

Java StringReader class declaration

The following is the declaration of this class:

  • public class StringReader extends Reader

Methods of StringReader class

The following are the methods that are used in the StringReader class:

  • int read():

This method reads a single character.

  • int read(char[] cbuf, int off, int len):

This method is used to read into a part of an array of characters.

  • boolean ready():

This method returns true if the stream is ready to be read otherwise returns false.

  • boolean markSupported():

This method returns true if the stream supports the mark method otherwise return false.

  • long skip(long ns):

This method skips a particular number of characters in the stream.

  • void mark(int readAheadLimit):

This method marks the current position in the stream.

  • void reset():

This method resets the stream.

  • void close():

This method closes the stream.

Java – PipedWriter

In Java, the PipedWriter class writes the Java pipe as a stream of characters. This class is normally used to write text and is associated with the PipedReader class and various threads use this class.

Constructors

The following are the constructors that are used by the PipedWriter class:

  • PipedWriter():

This constructor is used to create a piped write that has not been connected to a piped reader yet.

  • PipedWriter(PipedReader snk):

This constructor is used to create a piped writer that is connected to a particular piped reader.

Methods

The following are the constructors that are used by the PipedWriter class:

  • void close():

This method is used to close the piped output stream and to release any system resources that are connected to this stream.

  • void connect(PipedReader snk):

This method is used to attach the piped writer with a receiver.

  • void flush():

This method is used to flush the output stream and to force any buffered output characters to be written out.

  • void write(char[] cbuf, int off, int len):

This method is used to write len characters from a particular character array string at offset off to the piped output stream.

  • void write(int c):

This method is used to write a particular character to the piped output stream.

Java – PipedReader

In Java, the PipedReader class is normally used to read a text. It reads the contents of a pipe as a stream of characters. This class must be associated with the same PipedWriter class but both the classes are used by different threads.

Constructors

The following are the constructors that are used in the PipedReader class:

  • PipedReader(int pipeSize):

This constructor is used to create a PipedReader that it is not yet associated and makes the use of a particular pipe size for the pipe’s buffer.

  • PipedReader(PipedWriter src):

This constructor is used to create a PipedReader that is not associated with the piped writer src.

  • PipedReader(PipedWriter src, int pipeSize):

This constructor is used to create a PipedReader that is not associated with the piped writer src and makes the use of a particular pipe size for the pipe’s buffer.

  • PipedReader():

This constructor is used to create a PipedReader that is not yet associated.

Methods

The following are the methods that are used in the PipedReader class:

  • void close():

This method is used to close the piped stream and to release any system resources related to the stream.

  • void connect(PipedWriter src):

This method is used to connect the piped reader with the piped writer src.

  • int read():

This method is used to read the following character of data from the piped stream.

  • int read(char[] cbuf, int off, int len):

This method is used to read up to len characters of data from this piped stream into an array of characters.

  • boolean ready():

This method returns true if the stream is ready to be read otherwise returns false.

Java FilterWriter

In Java, the FilterWriter class writes the filtered character stream. It is an abstract class and its sub class overrides a few of its methods. This class adds methods and fields in the program.

Fields

  • protected writer out:

This filed includes the underlying character-output stream

Constructors

  • protected FilterWriter(Writer out):

This constructor is used to create an InputStream class object.

Methods

The following are the methods that are used in the FilterWriter class:

  • void close():

This method is used to close the stream after flushing it in the beginning.

  • void flush():

This method is used to flush the stream.

  • void write(char[] cbuf, int off, int len):

This method is used to write a part of an array of char.

  • void write(int c):

This method is used to write a single char.

  • void write(String str, int off, int len):

This method is used to write a part of the string.

Java FilterReader

In Java, the FilterReader reads the filtered character streams. It is an abstract class that performs filtering operations on the reader stream. The default method provided by this class passes all requests to the stream that is contained. The sub classes of this class override a few of its methods and add new methods and fields.

Field

  • protected Reader in:

This field includes the underlying character-input stream.

Constructor

  • protected FilterReader(Reader in):

This constructor is used to create a new filtered reader.

Methods

The following are the methods that are used in the FilterReader class:

  • void close():

This method is used to close the stream and to release any system resources related to it.

  • void mark(int readAheadLimit):

This method is used to mark the current position in the stream.

  • boolean markSupported():

This method returns true if the stream supports the mark method otherwise returns false.

  • boolean ready():

This method returns true if the stream is ready to be read otherwise returns false.

  • int read():

This method is used to read a single character.

  • int read(char[] cbuf, int off, int len):

This method is used to read char  of an array to a particular part.

  • void reset():

This method is used to reset the stream.

  • long skip(long n):

This method is used to skip the characters.

Java File Class

In Java, the File class is used to represent file and directory pathname. Here, the pathname can be both relative and absolute and the File class is an abstract class. Creating new directories or files, listing the contents of a directory, and deleting and renaming directories or files are a few of the methods of this class that works with files and directories.

Fields

The following are the fields of the File class:

  • static string pathSeparator:

This filed includes a path-separator character that is dependent on the system and is represented as a string for the convenience of the programmer.

  • static char pathSeparatorChar:

This field includes a path-separator character that is dependent on the system.

  • static string separator:

This filed includes a default name-separator character that is dependent on the system and is represented as a string for the convenience of the programmer.

  • static char separatorChar:

This filed includes a default name-separator character that is dependent on the system.

Constructors

The following are the constructors that are used in the File class:

  • File(File parent, String child):

This constructor is used to create a new file instance by using a parent abstract pathname and a child pathname string.

  • File(String pathname):

This constructor is used to create a new file instance by changing the pathname string provided to an abstract pathname.

  • File(String parent, String child):

This constructor is used to create a new file instance by using a parent pathname string and a child pathname string.

  • File(URI uri):

This constructor is used to create a new file instance by changing the file: URI provided to an abstract pathname.

Methods used

The following are the methods that are used in the File Class are:

  • static file createTempFile(String prefix, String suffix):

This method is used to create an empty file by making the use of the prefix and the suffix provided in order to generate its name. The file is created in the default temporary file directory

  • boolean createNewFile():

This method is used to create a new and empty file automatically which is named by the abstract pathname in the situation in which the name has not come into existence yet.

  • boolean canWrite():

This method returns true if the file denoted by this abstract pathname can be modified by the application otherwise returns false.

  • boolean canExecute():

This method returns true if the file denoted by this abstract pathname can be executed by the application otherwise returns false.

  • boolean canRead():

This method returns true if the file denoted by this abstract pathname can be read by the application otherwise returns false.

  • boolean isAbsolute():

This method is used to find out whether the abstract pathname is absolute or not.

  • boolean isDirectory():

This method returns true if the file denoted by the abstract pathname is a directory otherwise returns false.

  • boolean isFile():

This method returns true if the file denoted by the abstract pathname is a normal file otherwise returns false.

  • string getName():

This method is used to find out the name of the file or directory that is denoted by this abstract pathname and to return it.

  • string getParent():

This method is used to find out the pathname string of this abstract pathname’s parent and to return it. If the pathname does not name a parent directory, this method returns null.

  • path toPath():

This method is used to find out the path object that is constructed from the abstract path and to return it.

  • URI toURI():

This method is used to construct a URI file which represents the abstract pathname.

  • File[] listFiles():

This method is used to find out an array of abstract pathnames that denotes the file in the directory that is denoted by the abstract pathname and to return it.

  • long getFreeSpace():

This method is used to find out the number of unallocated bytes in the partition that is named by the abstract pathname and to return it.

  • String[] list(FilenameFilter filter):

This method is used to find out an array of strings and to return it. The array names the files and directories in the directory and is denoted by the abstract pathname. It satisfies a particular filter.

  • boolean mkdir():

This method is used to create a directory named by this abstract pathname.

Java FileDescriptor

In Java, the FileDescriptor class is used as a handle to the underlying machine-specific structure. The handle can be in, err, or out and the structure may represent an open file, another source, an open socket, or sink of bytes. The FileInputStream or FileOutputStream classes are created by this class in order to contain it.

Fields:

The following are the fields of the FileDescriptor class:

  • static FileDescriptor in:

This filed handles the input stream.

  • static FileDescriptor err:

This filed handles the error stream.

  • static FileDescriptor out:

This filed handles the output stream.

Constructors

  • FileDescriptor():

This constructor is used to construct a FileDescriptor object that may be invalid.

Methods

The following are the methods that are used in the FileDescriptor class:

  • Void sync():

This method is used to force all system buffers to synchronize with the underlying device.

  • Boolean valid():

This method returns true if the file descriptor object is valid otherwise returns false.

Java – RandomAccessFile

In Java, the RandomAccessFile class reads and writes the random access files. Here, the random access files are those file that behaves like a large array of bytes. The File pointer is a cursor that is moved to perform read and write operations and that is implied to the array. A type of IOException called EOFException is thrown in the situation in which the end-of-file is reached before the desired number of the byte has been read.

Constructors

The following are the constructors that are used in the RandomAccessFile class:

  • RandomAccessFile(File file, String mode):

This constructor is used to create a random access file stream that can be used to read and write the file that is specified by the File argument.

  • RandomAccessFile(String name, String mode):

This constructor is used to create a random access file stream that can be used to read and write a file with a particular name.

Methods

The following are the constructors that are used in the RandomAccessFile class:

  • void close():

This method is used to close the random access file stream and to release any system resources related to the stream.

  • FileChannel getChannel():

This method is used to find out the FileChannel object related to this file that is unique and to return it.

  • int readInt():

This method is used to read a signed 32-bit integer from the file.

  • string readUTF():

This method is used to read a string from the file.

  • void seek(long pos):

This method is used to set a file-pointer offset from which the following read and write occurs and that is measured from the start of the file.

  • void writeDouble(double v):

This method is used to change a double argument to a long. It is done by making the use of the doubleToLongBits method in the Double class and then by writing the long value to a file as an eight-byte quantity and high byte first.

  • void writeFloat(float v):

This method changes a float argument to an int. It is done by making the use of floatToIntBits method in the Float class and then by writing the int value to a file as a four-byte quantity and high byte first.

  • void write(int b):

This method is used to write a particular byte to the file.

  • int read():

This method is used to read a byte of data from the file.

  • long length():

This method is used to find out the length of the file and to return it.

  • void seek(long pos):

This method is used to set a file-pointer offset at which the following read and write occurs and that is measured from the start of the file.

Java Scanner class

Java has different methods to read input from the keyword and the Scanner class in one of those methods. It is a part of the java.util.package and is used to break the input into tokens. This class provides various ways to read and parse different primitive values and uses the delimeter which is whitespace by default to carry out its function. The main function of this class is to parse text for string and primitive types by making the use of a regular expression. The object class is extended and the Iterator and Closeable interfaces are implemented by this class.

Java Scanner Class Declaration

The following is the declaration of this class:

  • public final class Scanner extends Object   implements Iterator<String>

Java Scanner Class Constructors

The following are the constructors that are used in the Java Scanner class:

  • Scanner(File source):

This constructor is used to create a new scanner that scans a particular file and create values.

  • Scanner(File source, String charsetName):

This constructor is also used to create a new scanner that scans a particular file and create values.

  • Scanner(InputStream source):

This constructor is used to create a new scanner that scans a particular input stream and create values.

  • Scanner(InputStream source, String charsetName):

This constructor is also used to create a new scanner that scans a particular input stream and create values.

  • Scanner(Readable source):

This constructor is used to create a new scanner that scans a particular source and creates values.

  • Scanner(String source):

This constructor is used to create a new scanner that scans a particular string and creates values.

  • Scanner(ReadableByteChannel source):

This constructor is used to create a new scanner that scans a particular channel and creates values.

  • Scanner(ReadableByteChannel source, String charsetName):

This constructor is also used to create a new scanner that scans a particular channel and creates values.

  • Scanner(Path source):

This constructor is used to create a new scanner that scans a particular file and creates values.

  • Scanner(Path source, String charsetName):

This constructor is also used to create a new scanner that scans a particular file and creates values.

Java Scanner Class Methods

The following are the methods that are used in the Java Scanner class:

  • void close():

This method closes the scanner.

  • pattern delimiter():

This method figures out the pattern that is presently being used by the scanner class in order to match the delimiters.

  • Stream<MatchResult> findAll():

This method is used to figure out the stream of results that match the given pattern string.

  • string findInLine():

This method figures out the following occurrence of a pattern that is constructed from a particular string by ignoring the delimiters.

  • string findWithinHorizon():

This method is also used to figure out the following occurrence of a pattern that is constructed from a particular string by ignoring the delimiters.

  • boolean hasNext():

This method is used to check whether the scanner has another token in its input or not.

  • boolean hasNextBigDecimal():

This method is used to figure out whether the following token in the scanner’s input can be interpreted as a BigDecimal through the nextBigDecimal operation or not.

  • boolean hasNextBigInteger():

This method returns true in the case in which the following token in the scanner’s input can be interpreted as a BigInteger through the nextBigInteger operation otherwise returns false.

  • boolean hasNextBoolean():

This method returns true in the case in which the following token in the scanner’s input can be interpreted as a Boolean through the nextBoolean operation otherwise returns false.

  • boolean hasNextByte():

This method returns true in the case in which the following token in the scanner’s input can be interpreted as a Byte through the nextByte operation otherwise returns false.

  • boolean hasNextDouble():

This method returns true in the case in which the following token in the scanner’s input can be interpreted as a Double through the nextDouble operation otherwise returns false.

  • boolean hasNextFloat():

This method returns true in the case in which the following token in the scanner’s input can be interpreted as a Float through the nextFloat operation otherwise returns false.

  • boolean hasNextInt():

This method returns true in the case in which the following token in the scanner’s input can be interpreted as an integer through the nextInt operation otherwise returns false.

  • boolean hasNextLine():

This method returns true if the scanner has another line in the input otherwise returns false.

  • boolean hasNextLong():

This method returns true in the case in which the following token in the scanner’s input can be interpreted as a Long through the nextLong operation otherwise returns false.

  • boolean hasNextShort():

This method returns true in the case in which the following token in the scanner’s input can be interpreted as a Short through the nextShort operation otherwise returns false.

  • IOException ioException():

This method finds out the last thrown IOException by the readable of the scanner.

  • Locale locale():

This method finds out the locale of this scanner class.

  • MatchResult match():

This method finds out the match result of the last scanning operation that the scanner performed.

  • String next():

This method finds out the following complete token from the scanner that is currently being used.

  • BigDecimal nextBigDecimal():

This method is used to scan the following token of the input as a BigDecimal and to return it.

  • BigInteger nextBigInteger():

This method is used to scan the following token of the input as a BigInteger and to return it.

  • boolean nextBoolean():

This method is used to scan the following token of the input as a Boolean value.

  • byte nextByte():

This method is used to scan the following token of the input as a byte and to return it.

  • double nextDouble():

This method is used to scan the following token of the input as a double and to return it.

  • float nextFloat():

This method is used to scan the following token of the input as a float and to return it.

  • int nextInt():

This method is used to scan the following token of the input as an integer and to return it.

  • string nextLine():

This method finds out the input string that the scanner object had skipped and returns it.

  • long nextLong():

This method is used to scan the following token of the input as a long and to return it.

  • short nextShort():

This method is used to scan the following token of the input as a short and to return it.

  • int radix():

This method finds out the default radix of the currently used scanner.

  • void remove():

This method is used in the situation in which the implementation of Iterator does not support the remove method.

  • scanner reset():

This method resets the currently used scanner.

  • scanner skip():

This method is used to skip input that matches a particular pattern by ignoring the delimiters.

  • Stream<String> tokens():

This method finds out a stream of delimiter-separated tokens from the currently used scanner object and returns it.

  • string toString():

This method finds out the string representation of the currently used scanner and returns it.

  • scanner useDelimiter():

This method sets the delimiting pattern of the scanner that is in use to a particular pattern.

  • scanner useLocal():

This method sets the locale object of the scanner to a particular locale.

  • scanner useRadix():

This method sets the currently used scanners default radix to a particular radix.

Java Serialization

Serialization and Deserialization in Java

In Java, serialization is the process that is used to write the state of an object into a byte stream. EJB, RMI, JMS, and RMI are some of the technologies that use serialization. Deserialization does exactly the opposite of what serialization does.

The benefit of serialization in Java

The main function of serialization in Java is to travel the state of an object on the network. This process is also called marshaling.

Java.io.Serializable interface

In Java, the serializable interface does not have any data member and method. It is also called a marker interface because it marks the classes of Java in order to provide a specific capability to the objects of the classes. Other marker interfaces include the Cloneable and the Remote interfaces. The classes whose objects the programmer want to persist implement the serializable class. It is implemented by default in all the wrapper classes and the string classes.

ObjectOutputStream class

In Java, the ObjectOutputStream class writes the primitive data types and the objects to an output stream. Such objects that support the serializable interface can only be written to the stream.

Constructor

  • public ObjectOutputStream(OutputStream out) throws IOException {}

This constructor is used to construct an ObjectOutputStream which writes to a particular output stream.

Methods used

The following are the methods that are used in the ObjectOutputStream class:

  • public final void writeObject(Object obj) throws IOException {}

This method is used to write a particular object to the ObjectOutputStream.

  • public void flush() throws IOException {}

This method is used to flush the present output stream.

  • public void close() throws IOException {}

This method is used to close the present output stream.

Deserialization in java

In Java, deserialization is the mechanism that reconstructs the object from a serialized state. It does exactly the opposite of what serialization does.

ObjectInputStream class

In Java, the main function of the ObjectInputStream class is to deserialize objects and primitive data written through the ObjectOutputStream.

Constructor

  • public ObjectInputStream(InputStream in) throws IOException {}

This constructor is used to construct an ObjectInputStream which reads from a particular input stream.

Methods used

The following are the methods that are used in the ObjectInputStream class:

  • public final Object readObject():

This method is used to read an object from the input stream.

  • public void close() throws IOException {}

This method is used to close the ObjectInputStream.

Java Serialization with Inheritance (IS-A Relationship)

The sub classes of a class that has implemented the serializable interface are all serializable.

Java Serialization with Aggregation (HAS-A Relationship)

The serialization process is not possible in the situation in which a class has a reference to another class and the references have not been serialized.

Java Serialization with the static data member

The class which has a static data member in it cannot be serialized. This is because static is not a part of an object but it is a part of a class.

Java Serialization with array or collection

The serialization process is not possible in the situation in which an array or collection has not been serialized.

Externalizable in java

In Java, the Externalizable interface is not a market interface and the main function of this interface is to write the state of an object into a byte stream in a compressed format.

The following are the methods that are used in the Externalizable interface:

  • public void writeExternal(ObjectOutput out) throws IOException
  • public void readExternal(ObjectInput in) throws IOException

Java Transient Keyword

When a data member of a class is marked as transient, it cannot be serialized in the future. It is used in serialization.

To be continued….

Leave a Reply

Your email address will not be published. Required fields are marked *