0% found this document useful (0 votes)
26 views93 pages

Object Oriented Programming in Java

The document discusses Java arrays and constructors. It defines arrays as objects that can store multiple variables of the same type, including primitive types and object references. It describes key features of arrays such as being objects, holding references, being created at runtime, being dynamic and having a fixed length. The document then provides examples of declaring, initializing, and accessing array elements. It also discusses using arrays to store references to other objects. The summary then covers the definition of constructors in Java and the different types including default, no-argument, and parameterized constructors.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
26 views93 pages

Object Oriented Programming in Java

The document discusses Java arrays and constructors. It defines arrays as objects that can store multiple variables of the same type, including primitive types and object references. It describes key features of arrays such as being objects, holding references, being created at runtime, being dynamic and having a fixed length. The document then provides examples of declaring, initializing, and accessing array elements. It also discusses using arrays to store references to other objects. The summary then covers the definition of constructors in Java and the different types including default, no-argument, and parameterized constructors.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 93

OOP - Arrays

четврток, 25 март 2021 20:51

Java Arrays - Definition


Arrays are objects which store multiple variables of the same type. It can hold primitive
types as well as object references.

Features of Array
1. Arrays are objects.
2. They can eve hold the reference variables of other objects.
3. They are created during runtime.
4. They are dynamic , created on the heap.
5. The length of the Array is fixed.

Array Declaration
The type of the element that the array holds followed by the identifier and square braces which
indicates the identifier is array type.

Example: Declaring integer array


Int []aiMyArray;
Int aiMyArray[];

Int aiFirstArray[] = new int[6];


The above statement creates an array of size 6 on the heap. For the creation of the array the
compiler needs to know the size of the array, so the size is declared with the "new" keyword.
If we don't give values to the array then the arrays elements are automatically declared as 0. But if
we want to declare values to the elements we do the next thing:
Example: int aiFirstArray[] = {1,2,3,4,5,6};

Array Usage
The array elements can be accessed with the help of the index.
For example, aiFirstArray[0] refers to 1, aiFirstArray[1] refers to 2 and so on.

To get the size of the array we need the dot operator and length.
Example: aiFirstArray.length - returns the size of the array.

Array of References

Consider a class Employee which has a subclass Trainee.

Now, let consider the statement:

The above statement creates an array with 3 elements which holds 3 employee references emp[0],
emp[1] and emp[2]. The employee object are not yet created.

The following code initializes the employee objects.

Arrays Page 1
Since the parent class reference can also point to child class objects:

Consider an Interface Salary which is being implemented by Employee.

An Interface cannot be instantiated, but the reference can be used to point to the objects of the
classes that implements it.

Arrays Page 2
OOPs concepts in Java
четврток, 25 март 2021 21:17

What is an Object?
Object is a bundle of data and its behavior often known as methods.
Objects have two characteristics:
They have states.
They have behaviors.

Examples of states and behaviors


Example 1:
Object: House
State: Address, Color, Area
Behavior: Open door, close door

So if I had to write a class based on the given information, I will have a class House, attributes
Address, Color and Area. And I will have two methods, method Open door, and method Close door.

Example 2:
Let’s take another example.
Object: Car
State: Color, Brand, Weight, Model
Behavior: Break, Accelerate, Slow Down, Gear change.

Now I have to write a class Car, which has the attributes Color, Brand, Weight and Model. And
methods: Break, Accelerate, Slow down, Gear change.

Characteristics of Objects:
1. Abstraction
2. Encapsulation
3. Message passing

Abstraction: is a process where you show only "relevant" data and "hide" unnecessary details of an
object from the user.

Encapsulation: simply means binding object state and behavior together. If I am creating a class then
I am doing encapsulation.

Message passing: A application contains many objects. One object interacts with another object by

OOPs concepts in Java Page 3


Message passing: A application contains many objects. One object interacts with another object by
invoking methods on that object. It is also referred to as Method Invocation.

What is a Constructor?
The name of the Constructor must be the same name as the class.
Example: If I have a class named Animal, then the Constructors name will be Animal() {};
The Constructor doesn't have a return type.

On the right side of this statement, we are calling the default Constructor of the class MyClass to
create a new object.
A Constructor can be default or parameterized, if the constructor is empty then it is called the
default Constructor, else if the Constructor has parameters, it is called parameterized constructor.

Example:

Abstraction
Abstraction is hiding relevant and unnecessary data or details from the user. For example if you login
in your bank account, you type your name and password and press login, what happens when you
press login and how the servers sends the message is all hidden from you.

Encapsulation
Encapsulation means getting object states and behaviors (attributes, objects, methods) together. For
example if I make a class I am doing encapsulation.

Encapsulation example:

OOPs concepts in Java Page 4


Encapsulation example:

Inheritance
Inheritance means using the properties and functionalities of another class. Every sub class defines
only those properties that are unique for the sub class, the rest of the properties inherits from the
parent or super class.
1. Inheritance is a process of creating a new class that is based on an existing class, simply by
extending its common data members and methods.
2. With inheritance we can reuse code.
3. The class that is extends it is called super class or parent class, and the class that extends the
class it’s called child class or sub class.
One of the biggest advantages of Inheritance is when we reuse the code we don't have to type it
again in the sub class.
The variables (attributes) or methods in the parent class can be used in the child class.

To inherit a class we use the "extends" keyword. For example the class A, extends class B, where
class A is sub class, and class B is super class.

Example: We have a class Teacher that is a super class and a class MathTeacher that extends the
super class.

OOPs concepts in Java Page 5


Types of Inheritance
!!! Multi-level inheritance is allowed in Java but not multiple inheritance !!!

Single Inheritance: it's when one class extends another class. Child and parent class.
Multilevel Inheritance: It's when a class extends the child class. For example class A extends class B,
and class B extends class C.
Hierarchical Inheritance: it's when the super class is extended by more than one sub class. For
example, class B extends class A, and class C extends class A.
Multiple Inheritance: it's when a child class extends more than one parent class. For example, the
sub class C extends the super class B, and the super class A.

Polymorphism
Polymorphism allows us to perform a single action in different ways.
For example if we have a class Animal that has a method animalSound(), here we cannot give
implementation to this method because we don’t know which class would extend Animal class. So
we make the method AnimalSound() abstract by adding the "abstract" keyword before the methods
name.

Now, suppose we have two Animal sub classes Dog and Lion. We can provide the implementation
detail there.

OOPs concepts in Java Page 6


Method Overloading: is when we have more than one method with the same name but different
parameters.

Abstract Class and methods

Abstract method is a method that it's declared but not defined. It means that the abstract method
doesn't has body.
It is declared with the keyword "abstract".

The sub class that inherits must implement all the abstract methods from the super class or to be
declared as an abstract class.
Constructors, static methods, private methods and final methods cannot be abstract.
A abstract class cannot be instanced, that means than you cannot create an object of an abstract
class.

OOPs concepts in Java Page 7


Interfaces in Java
An interface is a blueprint of a class, which can be declared by using the "interface" keyword.
Interfaces can contain only constants and abstract methods. They cannot be instantiated, they can
be only implemented by classes or extended by other interfaces. With interface we achieve full
abstraction.
• A class can implement more than one interfaces.
• Interface it similar with abstract class but only contains abstract methods.
• They are created with the keyword "interface", and we use "implements" keyword to
implement an interface.

• All methods in the interface are public and abstract. It is optional to use the "abstract"
keyword before each method.
• A class can implement any number of interfaces.
• When a class implements an interface it has to give the definition of all the abstract methods
of interface or to be declared as abstract.
• An interface reference can point to objects of its implementing classes.

Access Specifiers
There are four types of access specifiers in Java:
Public: Accessible to all, inside and out of the class.
Private: Accessible only inside of the class.
Protected: Accessible for the class and the subclass.
Default: (Package Friendly).

OOPs concepts in Java Page 8


Constructors in Java
четврток, 25 март 2021 22:52

Constructor is a block of code that initializes the newly created object. Constructors don't have a
return type.
Constructor has the same name as the class, here is an example of a Constructor:

We have created an object obj of class Hello and then we displayed the instance variable name of
the object. When we created the object, the constructor got invoked. We used this keyword, which
refers to the current object, object obj.

Types of Constructors
There are three types of constructors: Default, No-arg constructor and Parameterized.

Default constructor
If the programmer does not write any constructor in the class, then the Java compiler creates a
default constructor automatically. The default constructor does not has parameters and his name
must be the same as the name of the class.

No-arg constructor
It is a constructor similar to the default constructor, the difference is that the no-arg constructor can
have body, unlike the default constructor where its body it is empty.

Constructors in Java Page 9


Parameterized constructor
Parameterized constructor it is a constructor that has arguments, or parameters.

What if you implement only parameterized constructor in class?

The code above will show an error. Because we created an object Example3 myobj = new
Example3(); that invokes the default constructor, which we don't have. We only have one
parameterized constructor. When the user doesn't implement any kind of constructor in the class
the compiler creates one automatically, but when the user creates a constructor, for example
parameterized constructor, then the compiler doesn't create a default constructor.

Constructor Chaining
When a constructor calls another constructor of the same class, then this is called constructor
chaining.

Constructors in Java Page 10


Super()
When a sub class constructor gets invoked it invokes the constructor of the super class.

Constructor Overloading
Constructor overloading is when we have more than one constructor with different parameters.

Constructors in Java Page 11


The difference between Constructor and Method
1. A constructor initializes the object of the class, and a method performs a given task.
2. Constructor cannot be abstract, final, static while methods can be.
3. Constructors do not have a return type while methods do.

Constructors in Java Page 12


Inheritance in Java
четврток, 25 март 2021 23:19

Inheritance is when a class inherits properties and methods from another class. The purpose of
inheritance is to make one code of one class reusable.
Inheritance is a process of defining a new class based on an existing class by extending its properties,
common data, members and methods.
The code that it's in the super class doesn't has to be written in the sub classes.

Child class: is a class that extends the properties of another class, and it's called child class or sub
class.
Parent class: is a class whose properties are used by another class and it's called parent class or
super class.

We have a class XYZ that extends the class ABC. The class XYZ is sub class, and the class ABC is super
class.

Based on the example above we can say that PhysicsTeacher IS-A Teacher. This means that a child
class has IS-A relationship with the parent class. This inheritance is known as IS-A relationship
between child and parent class.

The sub class inherits all the methods and members that are declared public or protected in the
super class. If the members and methods are private, then the sub class cannot access them directly.
We have to use getters and setters so we can access the private members and methods.

Types of Inheritance
Single Inheritance: single inheritance it's when one class extends another class. Or we have
one super class and one sub class.
Multilevel Inheritance: multilevel inheritance is when a class extends a child class. For
example, class C extends class B, and class B extends class A.

Inheritance in Java Page 13


example, class C extends class B, and class B extends class A.
Hierarchical Inheritance: Hierarchical inheritance is when one class is extended by more than
one class. For example, we have class B that extends A, class C that extends A, and class D that
extends A.
Multiple Inheritance: Multiple inheritance is when one class extends more than one class. For
example, we have class C than extends classes A and B.

Constructors and Inheritance


Constructor of subclass is invoked when we create an object of the subclass, it by default invokes the
default constructor of superclass.
The superclass constructor can be called with the "super" keyword, and it should be first in the
statement.

Inheritance and Method Overriding


Method overriding is when we create the same method in subclass and in superclass. In this case
when we call the method from subclass object, the method from subclass is called. If we want to call
the superclass method, then we use the super keyword.

Inheritance in Java Page 14


Inheritance in Java Page 15
Aggregation and Association in Java
петок, 26 март 2021 10:38

Aggregation
For example, consider two classes Student class and Address class. Every student has an address so
the relationship between student and address is a Has-A relationship. But if you consider the other
way around it doesn't make any sense as an Address doesn't need to have a Student necessarily.

Why we need Aggregation?


To maintain code re-usability. Suppose we have two other classes College and Staff along with the
classes Student and Address. In order to maintain Student's address, College Address and Staff's
address we don't need to use the same code again and again. We just have to use the reference of
Address class while defining each of these classes.

We did not write the Address code in any of the classes, we simply created the HAS-A relationship
with the address class to use the Address code.

Aggregation and Association in Java Page 16


Association
Association is establishing a relationship between two separate classes through their objects.

Aggregation and Association in Java Page 17


Super Keyword
петок, 26 март 2021 10:53

The keyword "super" refers to the constructor of the parent class or superclass.

The use of super keyword


1. To access data of the members of the superclass when both parent and child class have the
same members.
2. To call the no arg and parameterized constructor of the parent class.
3. To access the method of parent class when child class has overridden that method.

How to use super keyword to access the variables of parent class


When we have a variable in the child class, and the parent class also has the same variable, we use
"super" keyword to access the variable of the parent class.

In the following program, we have a data member num declared in the child class. The member with
the same name is already present in the parent class. To access the num variable in parent class you
have to use "super" keyword.

Accessing the num variable of parent class


By calling a variable with the super keyword we can access the variable of the parent class. If both
the parent and the child classes have the same variable.

Now let's take the same example but this time we pass super.num in the print statement.

Super Keyword Page 18


Output: 100
We can see here by using super.num we accessed the num variable of the parent class and then
printed it.

Use of super keyword to invoke constructor of parent class


When we create the object of sub class, the new keyword invokes the constructor of child class,
which implicitly invokes the constructor of parent class. So the order of execution when we create
the object of child class is: parent class constructor is executed first then the constructor of the child
class.

Parameterized super() call to invoke parameterized constructor of parent class


When we have a constructor in the parent class that has parameters, then we can use the super
keyword in child class to invoke the parameterized constructor of parent class from the constructor
in the child class.

Super Keyword Page 19


There are few important points to note in this example:
1. Super with or without parameters mut be the first statement in the child class constructor
otherwise you will get an error.
2. When we explicitly places super in the constructor, the java compiler didn't call the default no-
arg constructor of parent class.

How to use super keyword in case of method overriding


When a child class declares a method, that is already present in the parent class then this is called
method overriding. When a child class overrides a method of parent class, then the call to the
method from child class object always calls the child class version of the method. But if we want to
call the method of the parent class we use super keyword.

Super Keyword Page 20


Output:

What if the child class is not overriding any method: No need of super
When child class doesn't override the parent class method then we don't need to use the super
keyword to call the parent class method. This is because in this case we have only one version of
each method and child class has access to the parent class methods so we can directly call the
methods of the parent class without using super.

Super Keyword Page 21


Output:

Super Keyword Page 22


Method Overloading in Java
петок, 26 март 2021 11:31

Method Overloading allows a class to have more than one method with the same name but
different arguments (parameters). It is similar to constructor overloading, that allows a class to have
more than one constructor with different parameters.

For example we have two methods, add(int a, int b) and add(int a, int b, int c). The two methods
although they have the same name they are different because the first one has only two parameters
and the second one has three parameters. This is called method overloading.

The ways to overload a method


In order to overload a method the argument lists of the method must differ in either of these:
1. Number of parameters.

2. Data type of parameters.

3. Sequence of Data type of parameters.

Invalid case of method overloading


When I say argument list, I am not talking about return type of the method. For example if two
methods have the same name, same parameters and have different return type, then this is not a
valid method overloading example. This will throw compilation error.

Valid/Invalid cases of method overloading

Result: Compile time error. Argument lists are exactly the same. Both methods are having same
number, data types and same sequence of data types.

Result: Valid case of overloading, the methods have different number of parameters and different
types of arguments.

Result: Valid case of overloading, the methods have different number of parameters.

Method Overloading in Java Page 23


Result: Valid case of overloading. Sequence of data types of parameters are different.

Result: Invalid case of overloading. Argument lists are exactly the same. The return type doesn't
matter in method overloading.

Guess the answers before checking it at the end of programs:


Question 1 - return type, method name and argument list same.

Result:

Question 2 - return type is different. Method name and argument list same.

Method Overloading in Java Page 24


Result:

Method Overloading in Java Page 25


Method Overriding in Java
петок, 26 март 2021 11:50

Declaring a method in sub class which is already present in the parent class is known as method
overriding.
Overriding is done so that a child class can give its own implementation to a method which is already
provided by the parent class. In this case the method in parent class is called overridden method
and the method in child class is called overriding method.

Method Overriding Example


We have two classes. A child class Boy and a parent class called Human. The Boy class extends the
Parent class. Both classes have a common method void eat(). Boy class is giving its own
implementation to the eat() method or in other words it's overriding the method eat().

The Output will be: Boy is eating.

Advantage of method overriding


The overriding method it's useful because the child class can implement its own implementations
without changing the code in the parent class.
This is helpful when we have more than one child class, and if a one of the child classes needs to use
the parent class method, it can do that with overriding it, and not changing the parent class code.

Rules of method overriding in Java


1. Argument list: The argument list of overriding method (method of child class) must match the
Overridden method (the method of parent class). The data types of the argument and their
sequence should exactly match.
2. Access Modifier of the overriding method (method of subclass) cannot be more restrictive
than the overridden method of the parent class.
Example: If the Access Modifier of the parent class method is public then the overriding
method (method of the child class) cannot have private, protected and default Access
modifier, because all of this Access Modifier are more restrictive than public.

Method Overriding in Java Page 26


The code above will show error, because the overridden method has Access Modifier public
and the overriding method (method of the subclass) is protected.
But if we change the public super class method to protected and the protected subclass from
the child class to public, then the program will work, because public is less restrictive.
3. Private, static and final methods cannot be overridden as they are local to the class.
4. Overriding method can throw unchecked exceptions.
5. Binding of overridden methods happen at runtime which is known as dynamic binding.
6. If a class is extending an abstract class or implementing an interface then it has to override all
the abstract methods unless the class itself is an abstract class.

Super keyword in Method Overriding


The super keyword is used for calling the parent class method or constructor. super.myMethod()
calls the myMethod() method of the parent class, while super() calls the constructor of the parent
class.

Method Overriding in Java Page 27


Polymorphism in Java
петок, 26 март 2021 14:35

Polymorphism allows us to perform a single action in different ways.


For example: We have a class Animal that has a method sound(). Since this is a generic class so we
can't give it a implementation like: Roar, Meow, Oink etc.

Now we have two subclasses of Animal class: Horse and Cat that extends Animal class.

And

Although we had the common action for all subclasses sound() but there were different ways to do
the same action. This is perfect example of polymorphism. It would not make any sense to just call
the generic sound() method as each Animal has a different sound.

Polymorphism in Java Page 28


Abstract Class in Java
петок, 26 март 2021 14:50

A class that is declared using "abstract" keyword is known as abstract class. It can have abstract
methods (methods without body) or concrete methods (regular methods with body). A normal class
cannot have abstract methods.

An abstract class cannot be instantiated, which means you are not allowed to create an object of an
abstract class.

Why we need an abstract class?


Let’s say we have a superclass Animal, that has a method sound() and the subclasses Dog, Lion,
Horse, Cat etc. Since the animal sound differs from one animal to another, there is not point to
implement this method in parent class. That is because every child class must override this method
to give its own implementation details, like Lion class will say "Roar", the Dog class will say "Woof".
So we know that every subclass should override this method, then there is no point to implement
this method to the parent class. So making this method abstract is a good choice, because it will
make all the subclasses to override it.
Since the Animal class has an abstract method, we need to declare the class as abstract.

Abstract class declaration


An abstract class outlines the methods but not necessarily implements all the methods.

Rules
1. There are cases when it is difficult or often unnecessary to implement all the methods in the
parent class. In these cases, we can declare the parent class as abstract, which makes it a
special class which is not complete on its own.
A subclass of a superclass must override all the abstract methods that are declared in
superclass.
2. Abstract class cannot be instantiated which means you cannot create the object of it. To use
the abstract class, you need to create an object of the subclass and then call the non-abstract
methods of parent class as well as implemented methods (those that are abstract in parent
but implemented in child class).
3. If the child class doesn't implement all the abstract methods from the parent class, then it
need to be declared as abstract class.

Abstract class vs Concrete class

Abstract Class in Java Page 29


Abstract class vs Concrete class
A class that is not abstract is referred as concrete or regular class. In the example above, the Animal
class is abstract, and the classes Cat, Dog and Lion are concrete classes.

Key Points:
1. An abstract class has no use until its extended by some other class.
2. If you declare an abstract method in the class, then you must declare the class as abstract.
Also a class can be declared abstract, even if the class doesn't have an abstract method.
3. An abstract class can have a non-abstract (concrete) methods.

Main basics:
1. Abstract method has no body.
2. Always end the declaration with a semicolon (;).
3. Abstract method must be overridden. An abstract class must be extended and in a same way
abstract method must be overridden.
4. A class has to be declared as abstract in order to have abstract methods.

Abstract Class in Java Page 30


Interface in Java
петок, 26 март 2021 16:19

Abstraction is a process where you show only relevant data and hide unnecessary details of an
object from the user.

What is an interface in Java?


Interface looks like a class but it is not a class. An interface can have methods are variables, the
methods don't have bodies because they are abstract by default, and the variables are public static
and final by default.

What is the use of interface in Java?


Since methods in interfaces do not have body, they have to be implemented by the class before we
can access them. The class that implements interface must implement all the methods of the
interface. Also you can implement more than one interfaces in your class.
Interfaces are declared with the keyword "interface".

Example of an Interface in Java


The code bellow shows how an interface can be implemented. The class where the interface is
implemented to, has to provide the body of all the methods that are declared in the interface, or in
other words, a class has to implements all the methods from the interface.

Interface in Java Page 31


Interface and Inheritance
An interface cannot implement another interface. It has to extend the other interface. In the
example below, we have one interface Inf2 that extends another interface Inf1. If a class implements
Inf2, then it has to provide implementation for all the methods from int2 as well as int1.

Tag or Marker interface in Java


An empty interface is known as tag or marker interface. For example, Serializable, EventListener,
Remote are tag interfaces.

Nested interfaces
An interface that is declared in another interface is called nested interface. They are also known as
inner interfaces.

Key Points:
1. We can't instantiate an interface in Java. That means that we cannot create an object of an
interface.
2. An interface provides full abstraction as none of its methods have body.
3. To implement an interface we use "implements" keyword.
4. When we implement an interface it has to be public.

Interface in Java Page 32


4. When we implement an interface it has to be public.
5. The class that the interface is implemented to, must implement all the methods from the
interface, otherwise should be declared as abstract.
6. Interface cannot be declared as private, protected or transient.
7. All the interface methods are by default abstract and public.
8. Variables declared in interface are public final and static by default.
9. Interface variables must be initialized at the time of declaration otherwise the compiler will
throw an error.
10. A class can implement any number of interfaces.
11. If there are two or more methods in two interfaces that are the same, in the class that
implements the interfaces it's enough to have one implementation of the method.
12. A class cannot implements two interfaces that have methods with the same name but
different return type.
13. Variable names conflicts can be resolved by interface name.

Interface in Java Page 33


Encapsulation in Java
петок, 26 март 2021 17:50

Encapsulation means binding states in behaviors together. For example if you are creating a class,
you are doing encapsulation.

What is encapsulation?
The whole idea behind encapsulation is to hide the implementation details from users. If a data
member is private that means that it can be only accessed within the same class. No outside class
can access private data member (variable) of other class.
But, if we create public setter and getter method to update the data fields then the outside class can
access those private data fields via public methods.

Example of Encapsulation in Java


How to implement encapsulation in Java:
1. Make the instance variables private so they cannot be accessed directly from outside the class.
You can only set and get values of these variables through the methods of the class.
2. Have getter and setter methods in the class to set and get the values of the fields.

Encapsulation in Java Page 34


Encapsulation in Java Page 35
Packages in Java
сабота, 27 март 2021 12:24

A package is a pack (group) of classes, interfaces and other packages. In java we use packages to
organize our classes and interfaces. We have two types of packages in Java: built-in packages and
packages that we can create.
In Java we have several built-in packages, for example, when we need user input, we import a
package like this:

Here:
- Java is a top level package
- Util is a sub package
- And Scanner is a class which is present in the sub package util.

Advantages of using packages


- Reusability: While developing a project in Java, we often feel that there are few things that we
are writing over and over again in our code. So instead of doing that, we can use packages, we
can create the same things in form of classes inside a package and whenever we need to use
that, we can just import the package and use the class.
- Better Organization: In large Java projects, where we have several hundreds of classes, it is
always required to group the similar types of classes in a meaningful package name so that
you can organize your project better and when you need something you can quickly locate it
and use it, which improves the efficiency.
- Name Conflicts: We can define two classes with the same name but in different packages so to
avoid name collision, we can just use packages.

Type of packages in Java


1. User defined package: The package that the user creates is called user defined package.
2. Built-in package: The already defined package like java.io.*, java.lang.* etc., are known as
built-in packages.

Points to remember:
1. Sometimes class name conflict may occur. For example: Let's say we have two packages
abcpackage and xyzpackage and both the packages have a class with the same name, let it be
JavaExample.java. Now suppose a class import both these packages like this:

This will throw compilation error. To avoid such errors you need to use the fully qualifies name
method.

2. If we create a class inside a package while importing another package then the package
declaration should be the first statement, followed by the package import.

Packages in Java Page 36


3. A class can have only one package declaration, but it can have more than one package import
statements.

4. The wild card import like package.* should be used carefully when working with subclasses.
For example: Let's say we have a package abs and inside that package we have another
package foo, now foo is a sub package.
Classes inside abc are: Example1, Example2, Example3
Classes inside foo are: Demo1, Demo2
So if we import the package abs using wildcard like the one bellow, then it will import classes
Example1, Example2, Example3.

To import the classes of the sub package we need to import like this:

This will import Demo1, Demo2 but it will not import Example1, Example2 and Example3.
So to import all the classes present in the package and sub package, we need to use two
import statements like this:

Packages in Java Page 37


Access Modifiers in Java
сабота, 27 март 2021 12:48

An access modifiers restricts the access of a class, constructor, data member and method in another
class. In Java we have four modifiers:
1. Default
2. Private
3. Protected
4. Public

Default Access Modifier


When we do not mention any access modifier, it is called default access modifiers. The scope of this
modifier is limited to the package only. This means that if we have a class with the default access
modifier in a package, only those classes that are in this package can access this class.

Private Access Modifier


The scope of private modifier is limited to the class only.
1. Private Data members and methods are accessible only within the class.
2. Class and Interface cannot be declared as private.
3. If a class has a private constructor then you cannot create the object of that class from outside
of the class.

Protected Access Modifier


Protected data members and methods are only accessible by the classes of the same packages and
the subclasses present in any package. The protected access modifier is similar to default access
modifier with one exception that is has visibility in sub classes.

Access Modifiers in Java Page 38


modifier with one exception that is has visibility in sub classes.
Classes cannot be declared protected, this access modifier is generally used in a parent child
relationship.

Public Access Modifier


The members, methods and classes that are declared public can be accessed from anywhere. This
modifier doesn’t put any restriction on the access.

Access Modifiers in Java Page 39


Enum in Java
сабота, 27 март 2021 13:06

An Enum is a special type of data type which is basically a collection (set) of constants.

Declaring an Enum

Here, we have a variable Directions of enum type, which is collection of four constants, EAST, WEST,
NORTH, and SOUTH.

How to assign value to an enum type?

The variable dir is of type Directions (that is an enum type). This variable can take any value, out of
the possible four values. In this case it's set to North.

Use of Enum types in if-else statements


This is how we can use an Enum variable in an if-else statement.

Enum Fields and Methods

Enum in Java Page 40


We have a field shortCode for each of the constant, along with a method getDirectionCode() which is
basically a getter method for this field. When we define a constant like EAST("E"), it calls the Enum
constructor with the passed argument. This way we passed value is set as an value for the field of
the corresponding Enum's constant.

Important points to Note:


1. While defining Enums, the constants should be declared first, prior to any fields or methods.
2. When there are fields and methods declared inside Enum, the list of Enum constants must end
with a semicolon (;).

Enum in Java Page 41


Compile and Run from cmd
сабота, 27 март 2021 13:19

How to compile and run the above program


Step 1: Open a text editor, like Notepad. Copy the above program and paste it in the text editor.
Step 2: Save the file as FirstJavaProgram.java. You may be wondering why we have named the file as
FirstJavaProgram, the thing is that we should always name the file as the public class name.
Step 3: Open command prompt (cmd) on Windows. To compile the program, type the following
command and hit enter.

You may get this error when you try to compile the program "javac is not recognized as an internal
or external command, operable program or batch file." This occurs when the java path is not set in
your system.
If you get this error, then you first need to set the path before compilation.
Step 4: After compilation the .java file gets translated into the .class file (byte code). Now we can run
the program. To run the program, type the following command and hit enter.

Compile and Run from cmd Page 42


Exceptions in Java
сабота, 27 март 2021 13:36

Exception handling in Java


Exception handling is one of the most important feature of Java programming that allows us to
handle the runtime errors caused by exceptions.

What is an exception?
An Exception is an unwanted event that interrupts the normal flow of the program. When an
exception occurs program execution gets terminated. In such cases we get a system generated error
message. By handling the exceptions we can provide a meaningful message to the user about the
issue rather than a system generated message, which may not be understandable to a user.

Why an exception occurs?


There can be several reasons that can cause a program to throw exception. For example: Opening a
non-existing file in your program, Network connection problem, bad input data provided by user etc.

Exception Handling
If an exception occurs, which has not been handled by programmer then program execution get
terminated and a system generated error message is shown to the user.

This message is not user friendly so a user will not be able to understand what went wrong. In order
to let them know the reason in simple language, we handle exceptions.

Advantage of exception handling


Exception handling ensures that the flow of the program doesn't break when an exception occurs.
For example, if a program has bunch of statements and an exception occurs mid-way after executing
certain statements then the statements after the exception will not execute and the program will
terminate abruptly.
By handling we make sure that all the statements execute and the flow of program doesn't break.

Difference between errors and exceptions


Errors indicate that something severe enough has gone wrong, the application should crash rather
than try to handle the error.
Exceptions are events that occur in the code. A programmer can handle such conditions and take
necessary corrective actions.

Type of Exceptions
There are two types of exceptions in Java:
1. Checked Exceptions
2. Unchecked Exceptions

Check Exceptions
All exceptions other than Runtime Exceptions are known as Checked exceptions as the compiler
checks them during compilation to see whether the programmer has handled them or not.

Unchecked Exceptions
Runtime Exceptions are also known as Unchecked Exceptions. These exceptions are not checked at

Exceptions in Java Page 43


Runtime Exceptions are also known as Unchecked Exceptions. These exceptions are not checked at
compile-time so compiler does not check whether the programmer has handled them or not bit it’s
the responsibility of the programmer to handle these exceptions and provide a safe exit.

Try Catch in Java - Exception Handling

Try block
The try block contains set of statements where an exception can occur. A try block is always
followed by a catch block, which handles the exception that occurs in associated try block. A try
block must be followed by catch blocks or finally block or both.

Catch block
A catch block is where you handle the exceptions, this block must follow the try block. A single try
block can have one or several catch blocks associated with it. You can have different exceptions in
different catch blocks. When an exception occurs in the try block, the corresponding catch block that
handles the particular exception executes.

Example: try catch block

Exceptions in Java Page 44


Multiple catch blocks in Java
The example above has multiple catch blocks.
1. A single try block can have any number of catch blocks.
2. A generic catch block can handle all the exceptions.

3. If no exception occurs in try block then the catch block are completely ignored.
4. Corresponding catch block execute for that specific type of exception.
5. An exception can be thrown by a user.

Finally block
This block executes whether an exception occurs or not. You should place those statements in finally
blocks, that must execute whether exception occurs or not.

How to throw exception in Java


We can define our set of conditions or rules and throw an exception explicitly using throw keyword.
For example, we can throw ArithmeticException when we divide number by 5, or any other
numbers. Throw keyword can be also used for throwing custom exceptions.

Exceptions in Java Page 45


Throw clause in Java - Exception Handling
Throws keyword is used for handling checked exceptions. By using throws we can declare multiple
exceptions in one go.

Example of throws Keyword


The method myMethod() is throwing two checked exceptions so we can have declared these
exceptions in the method signature using throws keyword. If we do not declare these exceptions
then the program will throw a compilation error.

Exceptions in Java Page 46


Throw vs Throws
1. Throws clause is used to declare an exception, which means it works similar to the try catch
block. On the other hand throw keyword is used to throw an exception explicitly.
2. If we see syntax wise than throw is followed by an instance of Exception class and throws is
followed by exception class names.

3. Throw keyword is used in the method body to throw an exception, while throws is used in
method signature to declare the exceptions that can occur in the statements present in the
method.
4. You can throw one exception at a time but you can handle multiple exceptions by declaring
them using throws keyword.

User defined exception in Java


In Java we can create our own exception class and throw that exception using throw keyword. These
exceptions are known as user-defined or custom exceptions.

Exceptions in Java Page 47


Notes:
1. User-defined exception must extend Exception class.
2. The exception is thrown using throw keyword.

Exceptions in Java Page 48


Building GUI
сабота, 01 мај 2021 18:19

Java AWT

AWT stands for Abstract Windows Toolkit. It is a platform dependent API for creating Graphical User
Interface (GUI) for java programs.
Java AWT calls native platform (Operating systems) subroutine for creating components such as
textbox, checkbox, button etc. For example an AWT GUI having a button would have a different look
and feel across platforms like Windows, Mac OS & Unix.
An application build on AWT would look like a windows application when it runs on Windows, but
the same application would look like a Mac application when runs on Mac OS.

AWT hierarchy

Components and containers


All the elements like buttons, text fields, scrollbars etc., are known as components. In AWT we have
classes for each component as shown in the above diagram. To have everything placed on a screen
to a particular position, we have to add them to a container. A container is like a screen wherein we
are placing components like buttons, text fields, checkbox etc. In short a container contains and
controls the layout of components. A container itself is a component thus we can add a container
inside container.

Types of containers:
A container is a place where we add components like text field, button, checkbox etc. There are four
types of containers available in AWT: Window, Frame, Dialog and Panel. As shown in the hierarchy
diagram above, Frame and Dialog are subclasses of Window class.

Frame: A frame has tittle, border and menu bars. It can contain several components like buttons,
text fields, scrollbars etc. This is most widely used container while developing an application in AWT.

Flow Layout in AWT


Flow layout is the default layout, which means if you don't set any layout in your code then layout
would be set to Flow by default. Flow layouts puts components in a row, if horizontal space is not
enough to hold all the components then Flow layout adds them in a next row and so on.
All rows in Flow layout are center aligned by default. However we can set the alignment to left or
right. The default horizontal and vertical gap between components is 5 pixels.
By default the components Orientation is left to right, which means the components would be
added from left to right, however we can change it to from right to left as well.

Building GUI Page 49


added from left to right, however we can change it to from right to left as well.

Border Layout in AWT


In Border layout we can add components to the five specific regions. There regions are called
CENTER, EAST, WEST, NORTH and SOUTH.

Grid Layout in AWT


The Grid layout is used to arrange the components in rectangular grid. One component is displayed
in each rectangle.

Card Layout in AWT


The Card layout class manages the components in such a manner that only one component is visible
at a time. It treats each component as a card that is why it is known as Card layout.

Building GUI Page 50


GridBag Layout in AWT
The Java GridBag layout is used to align components vertically, horizontally or along their baseline.
The components may not be of same size.

Java JFrame
The javax.swing.JFrame class is a type of container which inherits the java.awt.Frame class. JFrame
works like the main window where components like labels, buttons, text fields are added to create a
GUI. Unlike Frame, JFrame has the option to hide or close the window with the help of
setDefaultCloseOperation(int) method.

Java Event classes and Listener interfaces


Changing the state of an object is known as an event. For example, click on button. Dragging mouse
etc. The java.awt.event package provides many event classes and Listener interfaces for event
handling.
We can put the event handling code into one of the following places:
• Within class

Building GUI Page 51


• Within class
• Other class
• Anonymous class
An object becomes an event listener when its class implements an event listener interface. For
example:
Public interface ActionListener extends EventListener {
Public void actionPerformed(ActionEvent e);
}
The event listener gets called when the event occurs if we register the event listener with the event
source.
You may select any object, as long as it implements ActionListener, to be the event listener.

XXXListener is an interface - a collection of methods that need to be implemented to respond on


XXXEvent. Each component that registers as a listener must implement everything from the
appropriate interface methods.
Adapters are an empty implementation of listeners. We often create a subclass of adapters for the
implementation of the listener and we only predefine individual methods.
Anonymous indoor classes are ideal for implementing listeners and adapters.

Semantic events
Are events at a higher level. They combine several low-level events. They are treated identically to
low events. For example: ActionEvent, ItemEvent.

Action Event
Button - mouse click on a button.
List - double click on the list element.
MenuItem - click on the choice element.
TextField - click on the button Return.

Item Event
CheckBox - marking or deleting (uncheck).
CheckBoxMenuItem - the selection element is highlighted or unchecked.
Choice - selected a new choice.
List - list item selected or deselected.

Building GUI Page 52


Collections in Java
понеделник, 03 мај 2021 17:27

The Collection in Java is a framework that provides an architecture to store and manipulate the
group of objects.
Java Collections can achieve all the operations that you perform on a data such as searching, sorting,
insertion, manipulation, and deletion.
Java Collection means a single unit of objects. Java Collection framework provides many interfaces
(Set, List, Queue, Deque) and classes (ArrayList, Vector, LinkedList, PriorityQueue, HashSet,
LinkedHashSet, TreeSet).

What is Collection in Java


A collection represents a single unit of objects, (a group).

What is a framework in Java


It provides readymade architecture.
It represents a set of classes and interfaces.
It is optional.

What is Collection framework


The collection framework represents a unified architecture for storing and manipulating a group of
objects. It has:
• Interfaces and its implementations, i.e., classes
• Algorithm.

Java ArrayList
Java ArrayList class uses a dynamic array for storing the elements. It is like an array, but there is no
size limit. We can add or remove elements anytime. So, it is much more flexible than the traditional
array. It is found in the java.util package.
The ArrayList in Java can have the duplicate elements also. It implements the List interface so we
can use all the methods of List interface here. The ArrayList maintains the insertion order internally.
The important points about Java ArrayList class are:
• Java ArrayList class can contain duplicate elements.
• Java ArrayList class maintains insertion order.
• Java ArrayList class is non synchronized.
• Java ArrayList allows random access because array works at the index basis.
• In ArrayList, manipulation is little bit slower than the LinkedList in Java because a lot of shifting
needs to occur if any element is removed from the array list.

ArrayList declaration
ArrayList<String> arrayList = new ArrayList<String>(); -/ creating new generic ArrayList.
ArrayList list = new ArrayList(); -/ creating non-generic ArrayList.

In a generic collection, we specify the type in angular braces. Now ArrayList is forced to have the
only specified type of objects in it. If you try to add another type of object, it gives compile time
error.

Collections in Java Page 53


Iterating ArrayList using Iterator

Iterating ArrayList using For-each loop

Collections in Java Page 54


How to Sort ArrayList
The java.util package provides a utility class Collections which has the static method sort(). Using the
Collections.sort() method, we can easily sort the ArrayList.

There are various ways to traverse the collection elements:


1. By Iterator interface.
2. By for-each loop.
3. By ListIterator interface.
4. By for loop.
5. By forEach() method.
6. By forEachRemaining() method.

Java Comparable interface


Java Comparable interface is used to order the objects of the user-defined class. The interface is
found in java.lang package and contains only one method name compareTo(Object). It provides a

Collections in Java Page 55


found in java.lang package and contains only one method name compareTo(Object). It provides a
single sorting sequence only i.e., you can sort the elements on the basis of single data member only.

CompareTo(Object obj) method


Public int compareTo(Object obj): It is used to compare the current object with the specified object.
It returns
• Positive integer, if the current object is greater than the specified object.
• Negative integer, if the current object is less than the specified object.
• Zero, if the current object is equal to the specified object.
We can sort the elements of:
1. String objects
2. Wrapper class objects
3. User-defined class objects

Collection class
Collections class provides static methods for sorting the elements of collections. If collection
elements are of Set or Map, we can use TreeSet or TreeMap. However, we cannot sort the elements
of List. Collections class provides methods for sorting the elements of List type elements.

Collections in Java Page 56


From the lessons.

Collection - there is no specific sequence, it allows duplicates.


List - tidiness or sequence, allows duplicates.
Set - no special sequence, no duplicates allowed.
Map - supports key search whose value is it must uniform.

Collections in Java Page 57


Collections in Java Page 58
Java Serialization
понеделник, 03 мај 2021 19:46

Serialization in Java is a mechanism of writing the state of an object into a byte-stream. It is mainly
used in Hibernate, RMI, JPA, EJB and JMS technologies.
The reverse operation of serialization is called deserialization where byte-stream in converted into
an object. The serialization and deserialization process is platform - independent, it means you can
serialize an object in a platform and deserialize in different platform.

For serializing the object, we call the writeObject() method ObjectOutputStream, and for
deserialization we call the readObject() method of ObjectInputStream class.

We have to implement the Serializable interface for serializing the object.

Advantages of Java Serialization


It is mainly used to travel object's state on the network (which is known as marshaling).

Java.io.Serializable interface
Serializable is a marker interface (has no data member and method). It is used to "mark" Java classes
so that the objects of these classes may get a certain capability.
It must be implemented by the class whose object you want to persist.

The String class and all the wrapper classes implement the java.io.Serializable interface by default.

In the above example, Student class implements Serializable interface. Now its objects can be
converted into stream.

Example of Java Serialization


In this example, we are going to serialize the object of Student class. The writeObject() method of
ObjectOutputStream class provides the functionality to serialize the object. We are saving the state
of the object in the file named f.txt.

Java Serialization Page 59


Java Transient Keyword
If you don't want serialize any data member of a class, you can mark it as transient.

Now, ID will not be serialized, so when you deserialize the object after serialization, you will not get
the value of ID. It will return default value always. In such case, it will return 0 because the data type
of ID is an integer.

Java Serialization Page 60


Java I/O
понеделник, 03 мај 2021 20:17

Java I/O (Input and Output) is used to process the input and produce the output.
Java uses the concept of a stream to make I/O operation fast. The java.io package contains all the classes required for input
and output operations.

Stream
A stream is a sequence of data. In Java, a stream is composed of bytes. It's called a stream because it is like a stream of water
that continues to flow.

OutputStream vs InputStream
1. OutputStream - Java application uses an output stream to write data to a destination. It may be a file, an array,
peripheral device or socket.
2. InputStream - Java application uses an input stream to read data from a source. It may be a file, an array, peripheral
device or socket.

OutputStream class
OutputStream class is an abstract class. It is the superclass of all classes representing an output stream of bytes. An output
stream accepts output bytes and sends them to some sink.

Useful methods of OutputStream


1. Write(int) - is used to write a byte to the current output stream.
2. Write(byte[]) - is used to write an array of byte to the current output stream.
3. Flush() - flushes the current output stream.
4. Close() - is used to close the current output stream.

InputStream class
InputStream class is an abstract class. It is the superclass of all classes representing an input stream of bytes.

Useful methods of InputStream


1. Read() - reads the next byte of data from the input stream. It returns -1 at the end of the file.
2. Available() - returns an estimate of the number of bytes that can be read from the current input stream.
3. Close() - is used to close the current input stream.

Java FileOutputStream Class


Java FileOutputStream is an output stream used for writing data to a file. If you have to write primitive values into a file, use
FileOutputStream class. You can write byte-oriented as well as character-oriented data through FileOutputStream class. But,
for character-oriented data, it is preferred to use FileWriter than FileOutputStream.

FileOutputStream class declaration


Declaration for Java.io.FileOutputStream class:

Java FileOutputStream : write byte

Java Input Output Page 61


Java FileOutputStream : write String

Java FileInputStream class


Java FileInputStream class obtains input bytes from a file. It is used for reading byte-oriented data (streams of raw bytes) such
as image data, audio, video etc. You can also read character - stream data. But, for reading streams or characters, it is
recommended to use FileReader class.

Java FileInputStream class declaration


Let's see the declaration for java.io.FileInputStream class:

Java FileInputStream class methods


1. Int available() - it is used to return the estimated number of bytes that can be read from the input stream.
2. Int read() - it is used to read the byte of data from the input stream.
3. Int read(byte[] b) - it is used to read up to b.length bytes of data from the input stream.
4. Void close() - it is used to close the stream.

Java FileInputStream : read single character

Java Input Output Page 62


Java FileInputStream : read all characters

Java Buffered OutputStream class


Java Buffered OutputStream class is used for buffering an output stream. In internally uses buffer to store data. It adds more
efficiency than to write data directly into a stream. So, it makes the performance fast.
For adding the buffer in an OutputStream, use the Buffered OutputStream class. Syntax:

Java Buffered OutputStream class declaration


Declaration for Java.io.BufferedOutputStream class:

Java Input Output Page 63


Java Buffered OutputStream class methods
1. Write() - it writes the specified byte to the buffered output stream.
2. Write(byte[] b, int off, int len) - it writes the bytes from the specified byte-input stream into a specified byte array,
starting with the given offset.
3. Flush() - it flushes the buffered output stream.

Example of Buffered OutputStream class:


In this example, we are writing the textual information in the Buffered OutputStream object which is connected to the
FileOutputStream object. The flush() flushes the data of one stream and send it into another. It is required if you have
connected the one stream with another.

Java Buffered InputStream Class


Java Buffered InputStream class is used to read information from stream. It internally uses buffer mechanism to make the
performance fast.
The important points about Buffered InputStream are:
• When the bytes from the stream are skipped or read, the internal buffer automatically refilled from the contained
input stream, many bytes at a time.
• When a Buffered InputStream is created, an internal buffer array is created.

Java Buffer InputStream class declaration


Declaration for Java.io.BufferedInputStream class:

Java BufferedInputStream class methods


• Int available() - it returns an estimate number of bytes that can be read from the input stream without blocking by the
next invocation method for the input stream.
• Int read() - it read the next byte of data from the input stream.
• Void close() - it closes the input stream and releases any of the system resources associated with the stream.
• Void reset() - it repositions the stream at a position the mark method was last called on this input stream.
• Void mark(int readlimit) - it sees the general contract of the mark method for the input stream.

Example of Java Buffered InputStream


Example to read data of file using Buffered InputStream

Java Input Output Page 64


Java Writer
It is an abstract class for writing to character streams. The methods that a subclass must implement are write(char[], int, int),
flush(), and close(). Most subclasses will override some of the methods defined here to provide higher efficiency functionality
or both.

Java Writer Methods


• Append(char c) - it appends the specified character to this writer.
• Close() - it closes the stream, flushing it first.
• Flush() it flushes the stream.
• Write(int c) - it writes a single character.
• Write(string str) - it writes a string.

Java Writer Example

Java Input Output Page 65


Java Reader
Java Reader is an abstract class for reading character streams. The only methods that a subclass must implement are
read(char[], int int) and close(). Most subclasses, however, will override some of the methods to provide higher efficiency,
additional functionality, or both.

Java Reader methods


• Close() - it closes the stream and releases any system resources associated with it.
• Mark(int readAheadLimit) - it marks the present position in the stream.
• Read() - it reads a single character.
• Ready() - it tells whether this stream is ready to be read.
• Reset() - it resets the stream.
• Skip(long n) - it skips characters.

Java Reader Example

Java Input Output Page 66


Java FileWriter Class
Java FileWriter class is used to write character-oriented data to a file. It is character - oriented class which is used for file
handling in Java.

Java FileWriter class declaration


Declaration for Java.io.FileWriter class:

Method of FileWriter class


• Void write(String text) - it is used to write the string into FileWriter.
• Void write(char c) - it is used to write the char into FileWriter.
• Void write(char[] c) - it is used to write char array into FileWriter.
• Void flush() - it is used to flush the data of FileWriter.
• Void close() - it is used to close the FileWriter.

Java FileWriter Example

Java Input Output Page 67


Java FileReader class
Java FileReader class is used to read data from the file. It returns data in byte format like FileInputStream class. It is character-
oriented class which is used for file handling in Java.

Java FileReader class declaration


Declaration for Java.io.FileReader class:

Methods of FileReader class


• Int read() - it is used to return a character in ASCII form. It returns -1 at the end of file.
• Void close() - it is used to close the FileReader class.

Java FileReader Example

Java BufferedWriter class


Java BufferedWriter class is used to provide buffering for Writer instances. It makes the performance fast. It inherits Writer
class. The buffering characters are used for providing the efficient writing of single array, characters and strings.

Java BufferedWriter class declaration


Declaration for Java.io.BufferedWriter class:

Java Input Output Page 68


Declaration for Java.io.BufferedWriter class:

Java BufferedWriter class methods


• Void newLine() - it is used to add a new line by writing a line separator.
• Void write(int c) - it is used to write a single character.
• Void flush() - it is used to flush the input stream.
• Void close() - it is used to close the input stream.

Example of Java BufferedWriter

Java BufferedReader class


Java BufferedReader class is used to read the text from a character-based input stream. It can be used to read data line by
line with readLine() method. It makes the performance fast. It inherits Reader class.

Java BufferedReader class declaration


Declaration for Java.io.BufferedReader class:

Java BufferedReader class methods


• Int read() - it is used for reading a single character.
• String readLine() - it is used for reading a line of text.
• Boolean ready() - it is used to test whether the input stream is ready to be read.
• Void reset() - it repositions the stream at a position the mark method was last called on this input stream.
• Void close() - it closes the input stream and releases any of the system resources associated with the stream.

Java BufferedReader Example

Java Input Output Page 69


Java PrintStream Class
The PrintStream class provides methods wo write data to another stream. The PrintStream class automatically flushes the
data so there is no need to call flush() method. Moreover, its methods don't throw IOException.

Class declaration
Declaration for Java.io.PrintStream class:

Example of Java PrintStream class

Java Input Output Page 70


Java PrintWriter class
Java PrintWriter class is the implementation of Writer class. It is used to print the formatted representation of object to the
text-output stream.

Class declaration
Declaration for Java.io.PrintWriter class:

Java PrintWriter class example

Java Input Output Page 71


Java - RandomAccessFile
This class is used for reading and writing to random access file. A random access file behaves like a large array of bytes. There
is a cursor implied into the array called file pointer, by moving the cursor we do the read write operations. If end of file is
reached before the desired number of byte has been read than EOFException is thrown.

Java - RandomAccessFile Methods

Java Input Output Page 72


Java - RandomAccessFile Example

Java Input Output Page 73


Java Input Output Page 74
Java Threads
вторник, 04 мај 2021 09:16

Multithreading in Java
Multithreading in Java is a process of executing multiple threads simultaneously. A thread is a
lightweight sub - process, the smallest unit of processing. Multiprocessing and multithreading, both
are used to achieve multitasking.
However, we use multithreading than multiprocessing because threads use a shared memory area.
They don’t allocate separate memory area so saves memory, and context-switching between the
threads takes less time than process.
Java Multithreading is mostly used in games, animation, etc.

Advantages of Java Multithreading


1) It doesn't block the user because threads are independent and you can perform multiple
operations at the same time.
2) You can perform many operations together, so it saves time.
3) Threads are independent, so it doesn't affect other threads if an exception occurs in a single
thread.

Multitasking
Multitasking is a process of executing multiple tasks simultaneously. We use multitasking to utilize
the CPU. Multitasking can be achieved in two ways:
• Process-based Multitasking (Multiprocessing)
• Thread-based Multitasking (Multithreading)

Process-based Multitasking (Multiprocessing)


Each process has an address in memory. In other words, each process allocates a separate memory
area.
A process is heavyweight.
Cost of communication between the process is high.
Switching from one process to another requires some time for saving and loading registers, memory
maps, updating lists, etc.

Thread - based Multitasking (Multithreading)


Threads share the same address space.
A thread is lightweight.
Cost of communication between the thread is low.

Threads
Threads allow a program to operate more efficiently by doing multiple things at the same time.
Threads can be used to perform complicated tasks in the background without interrupting the main
program.

Life cycle of a Thread (Thread States)


A thread can be in one of the five states. According to sun there is only 4 states in thread life cycle in
Java, new, runnable, non-runnable and terminated. There is no running state.
But for better understanding the threads, we are explaining it in the 5 states.
The life cycle of the thread in Java is controlled by JVM. The Java thread states are as follows:
1) New
2) Runnable
3) Running
4) Non-runnable (Blocked)
5) Terminated

New - The thread is in new state if you create an instance of Thread class but before the invocation

Java Threads Page 75


New - The thread is in new state if you create an instance of Thread class but before the invocation
of start() method.
Runnable - The thread is in runnable state after invocation of start() method, but the thread
scheduler has not selected it to be the running thread.
Running - The thread is in running state if the thread scheduler has selected it.
Non-Runnable (Blocked) - This is the state when the thread is still alive, but is currently not eligible
to run.
Terminated - A thread is in terminated or dead state when its run() method exits.

How to create thread


There are two ways to create a thread:
1. By extending Thread class
2. By implementing Runnable interface.

Thread class
Thread class provide constructors and methods to create and perform operations on a thread.
Thread class extends Object class and implements Runnable interface.

Runnable Interface
The Runnable interface should be implemented by any class whose instances are intended to be
executed by a thread. Runnable interface have only one method named run().

Public void run(): is used to perform action for a thread.

Starting a thread
Start() method of Thread class is used to start a newly created thread. It performs following tasks:
• A new thread starts
• The thread moves from New state to the Runnable state.
• When the thread gets a chance to execute, its target run() method will run.

Java Thread Example by extending Thread class

Java Thread Example by implementing Runnable interface

Java Threads Page 76


If you are not extending the Thread class, your class object would not be treated as a thread object.
So you need to explicitly create Thread class object. We are passing the object of your class that
implements Runnable so that your class run() method may execute.

Thread Scheduler in Java


Thread Scheduler in Java is the part of the JVM that decides which thread should run. There is no
guarantee that which runnable thread will be chosen to run by the thread scheduler.
Only one thread at a time can run in a single process.
The thread scheduler mainly uses preemptive or time slicing scheduling to schedule the threads.

Difference between preemptive scheduling and time slicing


Under preemptive scheduling, the highest priority task executes until it enters the waiting or dead
states or a higher priority task comes into existence. Under time slicing, a task executes for a
predefined slice of time and then reenters the pool of ready tasks. The scheduler then determines
which task should execute next, based on priority and other factors.

Sleep method in Java


The sleep() method of Thread class is used to sleep a thread for the specified amount of time.

Syntax of sleep() method in Java


The Thread class provides two methods for sleeping a thread:
• Public static void sleep(long milliseconds) throws InterruptedException.
• Public static void sleep(long milliseconds, int nanos) throws InterruptedException.

Java Threads Page 77


As you know well that at a time only one thread is executed. If you sleep a thread for the specified
time, the thread schedular picks up another thread and so on.

Can we start a thread twice?


No. After starting a thread, it can never be started again. If you do so, a IllegalThreadStateException
is thrown. In such case, thread will run once but for second time, it will throw exception.

What if we call run() method directly instead of start() method?


Each thread starts in a separate call stack.
Invoking the run() method from main thread, the run() method goes onto the current call stack
rather than at the beginning of a new call stack.

Java Threads Page 78


As you can see in the above program that there is no context - switching because here t1 and t2 will

Java Threads Page 79


As you can see in the above program that there is no context - switching because here t1 and t2 will
be treated as normal object not thread object.

Naming Thread and Current Thread


The thread class provides methods to change and get the name of a thread. By default, each thread
has a name i.e., thread-0, thread-1 and so on. We can change the name of the thread by using
setName() method.
• Public String getName(): is used to return the name of the thread.
• Public void setName(String name): is used to change the name of a thread.
The currentThread() method returns a reference of currently executing thread.
• Public static Thread currentThread()

Priority of a Thread (Thread Priority)


Each thread has a priority. Priorities are represented by a number between 1 and 10. In most cases,
thread schedular schedules the threads according to their priority. But it is not guaranteed because
it depends on JVM specification that which scheduling it chooses.

3 constants defined in Thread class


1. public static int MIN_PRIORITY
2. public static int NORM_PRIORITY
3. public static int MAX_PRIORITY

Default priority of a thread is 5 (NORM_PRIORITY). The value of MIN_PRIORITY is 1 and the value of
MAX_PRIORITY is 10.

Daemon Thread in Java


Daemon thread in Java is a service provider thread that provides services to the user thread. Its life
depend on the mercy of user threads i.e., when all the user threads die, JVM terminates this thread
automatically.
There are many java daemon threads running automatically e.g., gc, finalizer etc.

Points to remember for Daemon Thread in Java


• It provides services to user threads for background supporting tasks. It has no rule in life than
to serve user threads.
• Its life depends on user threads.
• It is a low priority thread.

Why JVM terminates the daemon thread if there is no user thread?


The sole purpose of the daemon thread is that it provides services to user thread for background
supporting task. If there is no user thread, why should JVM keep running this thread. That is why
JVM terminates the daemon thread if there is no user thread.

ThreadGroup in Java
Java provides a convenient way to group multiple threads in a single object. In such way, we can
suspends, resume or interrupt group of threads by a single method call.
Java thread group is implemented by java.lang.ThreadGroup class.
A ThreadGroup represents a set of threads. A thread group can also include the other thread group.
The thread group creates a tree in which every thread group except the initial thread group has a
parent.
A thread is allowed to access information about its own thread group, but I cannot access the
information about its thread group's parent thread group or any other thread groups.

Java Shutdown Hook


The shutdown hook can be used to perform cleanup resource or save the state when JVM shuts
down normally or abruptly. Performing clean resource means closing log file, sending some alerts or
something else. So if you want to execute some code before JVM shuts down, use shutdown hook.

When does the JVM shut down?

Java Threads Page 80


When does the JVM shut down?
The JVM shuts down when:
• User presses ctrl + c on the command prompt
• System.exit(int) method is invoked
• User logoff
• User shutdown etc.

The addShutdownHook(Thread hook) method


The addShutdownHook() method of Runtime class is used to register the thread with the Virtual
Machine. Syntax:
Public void addShutdownHook(Thread hook){}
The object of Runtime class can be obtained by calling the static factory method getRuntime(). For
example:
Runtime r = Runtime.getRuntime();

Factory method
The method that returns the instances of a class is known as factory method.

Java Threads Page 81


Synchronization in Java
вторник, 04 мај 2021 11:49

Synchronization in Java is the capability the control the access of multiple threads to any shared
resource.
Java Synchronization is better option where we want to allow only one thread to access the shared
resource.

Why use Synchronization?


The synchronization is mainly used to
1. To prevent thread interference.
2. To prevent consistency problem.

Types of Synchronization
There are two types of synchronization
1. Process Synchronization.
2. Thread Synchronization.

Thread Synchronization
There are two types of thread synchronization mutual exclusive and inter-thread communication.
1. Mutual Exclusive
1. Synchronized method.
2. Synchronized block.
3. Static synchronization.
2. Cooperation (Inter-thread communication in Java)

Mutual Exclusive
Mutual Exclusive helps keep threads from interfering with one another while sharing data. This can
be done by three ways in Java:
1. By synchronized method.
2. By synchronized block
3. By static synchronization.

Concept of Lock in Java


Synchronization is built around an internal entity known as the lock or monitor. Every object has a
lock associated with it. By convention, a thread that needs consistent access to an object's fields has
to acquire the object's lock before accessing them, and then release the lock when it's done with
them.

Java synchronized method


If you declare any method as synchronized, it is known as synchronized method. Synchronized
method is used to lock an object for any shared resource.
When a thread invokes a synchronized method, it automatically acquires the lock for that object and
releases it when the thread completes its task.

Synchronization in Java Page 82


Synchronized Block in Java
Synchronized block can be used to perform synchronization on any specific resource of the method.
Suppose you have 50 lines of code in your method, but you want to synchronize only 5 lines, you can
use synchronized block.

Points to remember for Synchronized block


Synchronized block is used to lock an object for any shared resource.
Scope of synchronized block is smaller than the method.

Inter - thread communication in Java


Inter - thread communication or Co - operation is all about allowing synchronized threads to
communicate with each other.

Synchronization in Java Page 83


communicate with each other.
Cooperation is a mechanism in which a thread is paused running in its critical section and another
thread is allowed to enter (or lock) in the same critical section to be executed. It is implemented by
following methods of Object class:
• Wait()
• Notify()
• notifyAll()

1. Wait() method
Causes current thread to release the lock and wait until either another thread invokes the notify()
method or the notifyAll() method for this object, or a specified amount of time has elapsed.
The current thread must own this object's monitor, so it must be called from the synchronized
method only otherwise it will throw exception.
2. Notify() method
Wakes up a single thread that is waiting on this object's monitor. If any threads are waiting on this
object, one of them is chosen to be awakened. The choice is arbitrary and occurs at the discretion of
the implementation. Syntax:
Public final void notify()
3. notifyAll() method
Wakes up all threads that are waiting on this object's monitor. Syntax:
Public final void notifyAll()

Understanding the process of inter-thread communication

The point to point explanation of the above diagram is as follows:


1. Threads enter to acquire lock.
2. Lock is acquired by on thread.
3. Now thread goes to waiting state if you call wait() method on the object. Otherwise it releases
the lock and exits.
4. If you call notify() or notifyAll() method, thread moves to the notified state (runnable state).
5. Now thread is available to acquire lock.
6. After completion of the task, thread releases the lock and exits the monitor state of the object.

Synchronization in Java Page 84


Java Networking
вторник, 04 мај 2021 18:10

Java Networking is a concept of connecting two or more computing devices together so that we can
share resources.
Java socket programming provides facility to share data between different computing devices.

Advantage of Java Networking


1. Sharing resources.
2. Centralize software management.

Java Networking Terminology


The widely used java networking terminologies are given below:
1. IP Address
2. Protocol
3. Port Number
4. MAC Address
5. Connection - oriented and connection - less protocol
6. Socket

IP Address
IP address is a unique number assigned to a node of a network e.g. 192.168.0.1. It is composed of
octets that range from 0 to 255.
It is a logical address that can be changed.

Protocol
A protocol is a set of rules basically that is followed for communication. For example:
• TCP
• FTP
• Telnet
• SMTP
• POP etc.

Port Number
The port number is used to uniquely identify different applications. It acts as a communication
endpoint between applications.
The port number is associated with the IP address for communication between two applications.

MAC Address
MAC (Media Access Control) Address is a unique identifier of NIC (Network Interface Controller). A
network node can have multiple NIC but each with unique MAC.

Connection-oriented and connection-loss protocol


In connection-oriented protocol, acknowledgement is sent by the receiver. So it is reliable but slow.
The example of connection-oriented protocol is TCP.
But, in connection-less protocol, acknowledgement is not sent by the receiver. So it is not reliable
but fast. The example of connection-less protocol in UDP.

Socket
A socket is an endpoint between two way communication.

Java Socket Programming


Java Socket Programming is used for communication between the applications running on different
JRE.
Java Socket programming can be connection-oriented or connection-less.

Java Networking Page 85


Java Socket programming can be connection-oriented or connection-less.
Socket and ServerSocket classes are used for connection-oriented socket programming and
DatagramSocket and DatagramPacket classes are used for connection-less socket programming.
The client in socket programming must know two information:
1. IP Address of Server, and
2. Port Number.

Socket class
A socket is simply an endpoint for communications between the machines. The Socket class can be
used to create a socket.

ServerSocket class
The ServerSocket class can be used to create a server socket. This object is used to establish
communication with the clients.

Example of Java Socket Programming


Creating server:
To create the server application, we need to create the instance of ServerSocket class. Here we are
using 6666 port number for the communication between the client and server. You may also choose
any other port number. The accept() method waits for the client. If clients connects with the given
port number, it returns an instance of Socket.

Creating Client:
To create the client application, we need to create the instance of Socket class. Here, we need to
pass the IP address or hostname of the Server and a port number. Here, we are using localhost
because our server is running on same system.

Example of Java socket programming where client sends a text and server receives and prints it.
File: MyServer.java

Java Networking Page 86


File: MyClient.java

To run the program open command prompt and type javac MyServer.java.

Java URL
The Java URL class represents an URL. URL is an acronym for Uniform Resource Locator. It points to a
resource on the World Wide Web. For example:

Java Networking Page 87


A URL contains many information:
1. Protocol: In this case http is the protocol.
2. Server name or IP Address: In this case, www.javapoint.com is the servers name.
3. Port Number: It is an optional attribute. If we write
http//www.javapoint.com:80/sonoojaiswal/, 80 is the port number. If port number is not
mentioned in the URL, it returns -1.
4. File Name or directory name: In this case index.jsp is the file name.

Java URLConnection class


The Java URLConnection class represents a communication link between the URL and the
application. This class can be used to read and write data to the specified resource referred by the
URL.

How to get the object of URLConnection class


The openConnection() method of URL class returns the object of URLConnection class. Syntax:

Displaying source code of a webpage by URLConnection class


The URLConnection class provides many methods, we can display all the data of a webpage by using
the getInputStream() method. The getInputStream() method returns all the data of the specified URL
in the stream that can be read and displayed.

Java Networking Page 88


Java InetAddress class
Java InetAddress class represents an IP address. The java.net.InetAddress class provides methods to
get the IP of any host name for example www.javapoint.com, www.google.com,,
www.facebook.com, etc.
An IP address is represented by 32-bit or 128-bit unsigned number. An instance of InetAddress
represents the IP address with its corresponding host name. There are two types of address types:
Unicast and Multicast. The Unicast is an identifier for a single interface whereas Multicast is an
identifier for a set of interfaces.

Commonly used methods of InetAddress class


• getByName(String host) - it returns the instance of InetAddress containing LocalHost IP and
name.
• getLocalHost() - it returns the instance of InetAddress containing local host name and address.
• getHostName() - it returns the host name of the IP address.
• getHostAddress() - it returns the IP address in string format.

Java Networking Page 89


StringTokenizer in Java
The java.util.StringTokenizer class allows you to break a string into tokens. It is simple way to break
string. It doesn't provide the facility to differentiate numbers, quoted strings, identifiers etc., like
StreamTokenizer class.

StreamTokenizer - works with characters (java.io)


StringTokenizer - works with strings (java.util)

Methods of StringTokenizer class


Boolean hasMoreTokens() - checks if there is more tokens available.
String nextToken() - returns the next token from the StringTokenizer object.
String nextToken(String delim) - returns the next token based on the delimiter.
Boolean hasMoreElements() - same as hasMoreTokens() method.
Object nextElement() - same as nextToken() but its return type is Object.
Int countTokens() - returns the total number of tokens.

SOAP Web Services


SOAP stands for Simple Object Access Protocol. It is a XML-based protocol for accessing web
services.
SOAP is a W3C recommendation for communication between two applications.
SOAP is XML based protocol. It is platform independent and language independent. By using SOAP,
you will be able to interact with other programming language applications.

Java Networking Page 90


you will be able to interact with other programming language applications.

Advantages of SOAP Web Services


WS Security: SOAP defines its own security known as WS Security.
Language and Platform independent: SOAP web services can be written in any programming
language and executed in any platform.

RESTful Web Services


REST stands for Representational State Transfer.
REST is an architectural style not a protocol.

Advantages of RESTful Web Services


Fast: RESTful Web Services are fast because there is no strict specification like SOAP.
Language and Platform independent: RESTful web services can be written in any programming
language and executed in any platform.
Can use SOAP: RESTful web services can use SOAP web services as the implementation.
Permits different data format: RESTful web service permits different data format such as Plain Text,
HTML, XML and JSON.

Java Networking Page 91


Java Beans
вторник, 04 мај 2021 20:10

A Java Bean is a Java class that should follow the following conventions:
• It should have a no-arg constructor.
• It should be Serializable.
• It should provide methods to set and get the values of the properties, known as getter and
setter methods.

Why use Java Bean?


According to Java white paper, it is reusable software component. A bean encapsulates many
objects into one object so that we can access this object from multiple places. Moreover, it provides
easy maintenance.

How to access the Java Bean class?


To access the Java Bean class, we should use getter and setter methods.

Java Bean Properties


A Java Bean property is a named feature that can be accessed by the user of the object. The feature
can be of any Java data type, containing the classes that you define.
A Java Bean property may be read, write, read-only, or write-only. Java Bean features are accessed
through two methods in the Java Bean's implementation class:

Java Beans Page 92


1. getPropertyName()
For example, if the property name is firstName, the method name would be getFirstName() to read
that property. This method is called the accessor.
2. setPropertyName()
For example, if the property name is firstName, the method name would be setFirstName() to write
that property. This method is called the mutator.

Advantages of Java Bean


• The Java Bean properties and methods can be exposed to another application.
• It provides an easiness to reuse the software components.

Disadvantages of Java Bean


• Java Beans are mutable. So, it can't take advantages of immutable objects.
• Creating the setter and getter method for each property separately may lead the boilerplate
code.

Java Beans Page 93

You might also like