OOPJ-Module1 Material
OOPJ-Module1 Material
OOPJ-Module1 Material
1.1 Introduction:
Java is a high-level programming language and a platform. it is an object-
oriented programming language. The principles for creating Java
programming are "Simple, Robust, Portable, Platform-independent, Secured,
High Performance, Multithreaded, Architecture Neutral, Object-Oriented,
Interpreted, and Dynamic".
Types of Java Applications – There are mainly 4 types of applications that can
be created using Java programming:
1) Standalone Application – Standalone applications are also known
as desktop applications or window-based applications. These are
traditional software that we need to install on every machine. Examples
of standalone application are Media player, antivirus, etc. AWT and
Swing are used in Java for creating standalone applications.
2) Web Application – An application that runs on the server side and
creates a dynamic page is called a web application. Currently, Servlet,
JSP, Struts, Spring, Hibernate, JSF, etc. technologies are used for
creating web applications in Java.
3) Enterprise Application – An application that is distributed in nature,
such as banking applications, etc. is called an enterprise application. It
has advantages like high-level security, load balancing, and clustering.
In Java, EJB is used for creating enterprise applications.
4) Mobile Application – An application which is created for mobile
devices is called a mobile application. Currently, Android and Java ME
are used for creating mobile applications.
Java Platforms / Editions – There are 4 platforms or editions of Java:
1) Java SE (Java Standard Edition) – It is a Java programming
platform. It includes Java programming APIs such as java.lang, java.io,
java.net, java.util, java.sql, java.math etc. It includes core topics like
OOPs, String, Regex, Exception, Inner classes, Multithreading, I/O
Stream, Networking, AWT, Swing, Reflection, Collection, etc.
2) Java EE (Java Enterprise Edition) – It is an enterprise platform that
is mainly used to develop web and enterprise applications. It is built on
top of the Java SE platform. It includes topics like Servlet, JSP, Web
Services, EJB, JPA, etc.
3) Java ME (Java Micro Edition) – It is a micro platform that is
dedicated to mobile applications.
4) JavaFX – It is used to develop rich internet applications. It uses a
lightweight user interface API.
object - Any entity that has state and behavior is known as an object.
For example, a chair, pen, table, keyboard, bike, etc. It can be physical
or logical. An Object can be defined as an instance of a class. An object
contains an address and takes up some space in memory. Objects can
communicate without knowing the details of each other's data or code.
The only necessary thing is the type of message accepted and the type
of response returned by the objects.
1.1.7 Variables
The variable is the basic unit of storage. A variable is defined by the
combination of an identifier, a type, and an optional initializer. In addition,
all variables have a scope, which defines their visibility, and a lifetime.
Syntax: type identifier [ = value][, identifier [= value] ...];
Example: int a=2,b=8;
1) Instance Variable
A variable declared inside the class but outside the body of the method,
is called an instance variable. It is not declared as static. It is called an
instance variable because its value is instance-specific and is not
shared among instances.
Example:
class Test
{
int i;
public static void main(String args[])
{
Test t=new Test();
System.out.println(t.i);
}
}
Output:
0
2) Static variable
A variable that is declared as static is called a static variable. It cannot
be local. You can create a single copy of the static variable and share it
among all the instances of the class. Memory allocation for static
variables happens only once when the class is loaded in the memory.
Example:
class Test
{
int i;
static int j;
public static void main(String args[])
{
Test t=new Test();
t.i=10;
Test.j=20;
System.out.println(“i=”+i);
System.out.println(“j=”+Test.j);
}
}
Output:
i=10
j=20
3) Local Variable
A variable declared inside the body of the method is called local variable.
You can use this variable only within that method and the other
methods in the class aren't even aware that the variable exists. A local
variable cannot be defined with "static" keyword.
Example:
class Test
{
public static void main(String args[])
{
int i;
i=10;
System.out.println(i);
}
}
Output:
10
Example:
1.1.9 Operators
Java provides a rich operator environment. Most of its operators can be
divided into the following four groups: arithmetic, bitwise, relational, and
logical.
Arithmetic Operators –
Arithmetic operators are used in mathematical expressions in the same
way that they are used in algebra. The following table lists the arithmetic
operators:
Symbol Operator Name Example
+ Addition A+B
- Subtraction A–B
* Multiplication A*C
/ Division A/B
% Modulus A%B
++ Increment A ++
-- Decrement A --
+= Addition assignment A += 2
Subtraction
-= A -= 2
assignment
Multiplication
*= A *= 2
assignment
/= Division Assignment A /= 2
%= Modulus assignment A %= 2
The operands of the arithmetic operators must be of a numeric type.
You cannot use them on boolean types, but you can use them on char types,
since the char type in Java is, essentially, a subset of int.
The Bitwise Operators –
Java defines several bitwise operators that can be applied to the integer
types, long, int, short, char, and byte. These operators act upon the individual
bits of their operands. They are summarized in the following table:
Symbol Operator Name Example
~ Bitwise unary NOT ~A
& Bitwise AND A&B
| Bitwise OR A|B
^ Bitwise exclusive OR A^B
>> Right shift A >> B
<< Left shift A << B
&= Bitwise AND assignment A &= 2
|= Bitwise OR assignment A |= 2
Bitwise exclusive OR
^= A ^= 2
assignment
>>= Right shift assignment A >>= 2
<<= Left shift assignment A <<= 2
Shift right zero fill
>>>= A >>>= 2
assignment
The following table shows the outcome of each operation
A B A&B A|B A^B ~A
1 0 0 1 1 0
1 1 1 1 0 0
0 0 0 0 0 1
0 1 0 1 1 1
Relational Operators –
The relational operators determine the relationship that one operand has
to the other. Specifically, they determine equality and ordering. The relational
operators are shown here:
1.1.12 Arrays
An array is a group of like-typed variables that are referred to by a
common name. Arrays of any type can be created and may have one or more
dimensions. A specific element in an array is accessed by its index. Arrays
offer a convenient means of grouping related information.
One-Dimensional Arrays –
A one-dimensional array is, essentially, a list of like-typed variables. To
create an array, you first must create an array variable of the desired type.
Syntax: type var-name[ ] = new type[size];
Example:
import java.lang.*;
import java.util.*;
class OnedArray
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
System.out.println(“enter size of array”);
int n;
n=sc.nextInt();
int a[]=new int[n];
System.out.println(“enter elements of an array”);
int i;
for(i=0;i<n;i++)
{
a[i]=sc.nextInt();
System.out.println(“Elements are”);
for(int j:a)
{
System.out.println(j+” “);
}
}
}
Output:
enter size of array 3
enter elements of an array 20 30 40
Elements are 20 30 40
Multidimensional Arrays –
In Java, multidimensional arrays are actually arrays of arrays. These,
as you might expect, look and act like regular multidimensional arrays.
However, as you will see, there are a couple of subtle differences. To declare
a multidimensional array variable, specify each additional index using
another set of square brackets.
Syntax: type var-name[][] = new type[r_size][c_size];
Example:
import java.lang.*;
import java.util.*;
class TwodArray
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
System.out.println(“enter row size & col size of array”);
int r,c;
r=sc.nextInt();
c=sc.nextInt();
int a[][]=new int[r][c];
System.out.println(“enter elements of an array”);
int i,j;
for(i=0;i<r;i++)
{
for(j=0;j<r;j++)
{
a[i][j]=sc.nextInt();
}
}
System.out.println(“Elements are”);
for(i=0;i<r;i++)
{
for(j=0;j<r;j++)
{
System.out.print(a[i][j]+” “);
}
System.out.println(” “);
}
}
}
Output:
enter row size & col size of array 2 2
enter elements of an array 20 30 40 50
Elements are
20 30
40 50
1.2.3 Constructors
A constructor initializes an object immediately upon creation. It has the
same name as the class in which it resides and is syntactically similar to a
method. Once defined, the constructor is automatically called immediately
after the object is created, before the new operator completes.
Constructors look a little strange because they have no return type, not
even void. This is because the implicit return type of a class constructor is the
class type itself. It is the constructor’s job to initialize the internal state of an
object so that the code creating an instance will have a fully initialized, usable
object immediately.
There are two rules defined for the constructor:
✓ Constructor name must be the same as its class name
✓ A Constructor must have no explicit return type
✓ A Java constructor cannot be abstract, static, final, and synchronized.
Default constructors:
A constructor is called "Default Constructor" when it doesn't have any
parameter. When there is no explicitly defined constructor for a class, then
Java creates a default constructor for the class. The default constructor
automatically initializes all instance variables to zero. Once the user defines
a constructor to the class, then the default constructor is no longer be used.
Example: Java program to demonstrate default constructor.
import java.io.*;
import java.util.*;
class Addition
{
int x,y;
Addition() //default constructor
{
x=10;
y=20;
}
void display()
{
System.out.println("Initialized values are x = "+x+", y= "+y);
}
}
class con
{
public static void main(String args[])
{
Addition b=new Addition();
b.display();
}
}
OUTPUT:
Initialized values are x = 10, y= 20
Parameterized Constructors:
Each object is initialized as specified in the parameters to its constructor. The
parameterized constructor is used to provide different values to distinct
objects. However, you can provide the same values also.
Example: Java program to demonstrate parameterized constructor.
import java.io.*;
import java.util.*;
class Addition
{
int x,y;
Addition(int a,int b) //parameterized constructor
{
x=a;
y=b;
}
void display()
{
System.out.println(“Initialized values are x = "+x+", y= "+y);
}
}
class con
{
public static void main(String args[])
{
Addition b=new Addition(10,20);
b.display();
}
}
OUTPUT:
Initialized values are x = 10, y= 20
1.2.4 Constructor overloading
In java constructors also can be overloaded like methods. Constructor
overloading in Java is a technique of having more than one constructor with
different parameter lists. They are arranged in a way that each constructor
performs a different task.
Example: Java program to demonstrate constructor overloading.
import java.io.*;
import java.util.*;
class Addition
{
int x,y,z;
Addition(int a)
{
x=a;
}
Addition(int a,int b)
{
x=a;
y=b;
}
Addition(int a,int b,int c)
{
x=a;
y=b;
z=c;
}
void sum()
{
System.out.println("sum is "+x+y+z);
}
}
class con
{
public static void main(String[] args)
{
Addition a=new Addition(10);
Addition b=new Addition(10,20);
Addition c=new Addition(10,20,30);
a.sum();
b.sum();
c.sum();
}
}
OUTPUT:
Sum is 10
Sum is 30
Sum is 60
OUTPUT:
Access.java:15: error: b has private access in Sample
System.out.println("a="+obj.a+"b = "+obj.b+"c = "+obj.c+"d = "+obj.d);
^
1 error
1.2.7 This keyword
In Java, this is a reference variable that refers to the current object.
Usage of Java this keyword:
✓ this can be used to refer current class instance variable.
✓ this can be used to invoke current class method (implicitly)
✓ this() can be used to invoke current class constructor.
✓ this can be passed as an argument in the method call.
✓ this can be passed as argument in the constructor call.
✓ this can be used to return the current class instance from the
method.
Example:
// displays address of class using this keyword
class A
{
void show()
{
System.out.println(this);
}
public static void main(String args[])
{
A obj=new A();
System.out.println(obj);
obj.show();
}
}
Output:
45632abcv98 //address of class holding by this keyword
45632abcv98 //address of class holding by object
//using this keyword for instance variable when both instance variable
and local variable has same variable.
class A
{
int a;
A(int a)
{
this.a=a;
}
void show()
{
System.out.println(this);
}
public static void main(String args[])
{
A obj=new A(100);
obj.show();
}
}
Output:
100
//using this keyword to call the default constructor of its own class
class A
{
A()
{
System.out.println(“learn coding”);
}
A(int a)
{
this();
System.out.println(a);
}
public static void main(String args[])
{
A obj=new A(100);
}
}
Output:
learn coding
100
//using this keyword to call the parameterized constructor of its own
class
class A
{
A()
{
this(10);
}
A(int a)
{
System.out.println(a);
}
public static void main(String args[])
{
A obj=new A();
}
}
Output:
10
1.2.8 Garbage collection
Since objects are dynamically allocated by using the new operator, such
objects has to be destroyed and their memory released for later reallocation.
In Java the deallocation of memory for the dynamically memory allocated
objects are called as garbage collection which can be achieved automatically.
During the garbage collection process, the collector scans different parts
of the heap, looking for objects that are no longer in use. If an object no longer
has any references to it from elsewhere in the application, the collector
removes the object, freeing up memory in the heap. This process continues
until all unused objects are successfully reclaimed.
Advantage of Garbage Collection:
✓ It makes java memory efficient because garbage collector removes the
unreferenced objects from heap memory.
✓ It is automatically done by the garbage collector (a part of JVM) so we
don't need to make extra efforts.
Phases of garbage collection:
✓ Mark – GC “paints” the objects which are active, leaving the dead
objects unmarked.
✓ Sweep – GC looks for unpainted objects and collects them for removal
from memory.
When the garbage collector chooses an object for garbage collection:
✓ Assigning null reference to the variable.
✓ Assigning another reference to the variable.
✓ Creating local variables: As soon as the method execution is complete
all the variables declared in the method will be eligible for garbage
collection.
✓ Anonymous objects.
✓ GC checks for this cyclic reference and removes the object groups that
are referencing each other without being referenced by any active
object.
Whenever the JVM finds out the heap space is getting occupied and will
soon run out of space, it runs the GC thread. Apart from automatic run, we
can also explicitly ask the GC to run at any point of the code using System.gc()
or Runtime.getRuntime().gc().
Example: Java program to demonstrate explicit garbage collection.
import java.io.*;
import java.util.*;
class Sample
{
public void finalize()
{
System.out.println("Objects Destroyed");
}
Scanner scan=new Scanner(System.in);
int a,b;
void read()
{
System.out.print("Enter a : ");
a=scan.nextInt();
System.out.print("Enter b: ");
b=scan.nextInt();
}
void display()
{
System.out.println("a = "+a+"b= "+b+"c = "+c);
}
}
class Garbage
{
public static void main(String args[]){
Sample s1=new Sample();
s1=null;
new Sample();
System.gc();
}
}
finalize() method in Java is a method of the Object class that is used to
perform cleanup activity before destroying any object. It is called by Garbage
collector before destroying the objects from memory. finalize() method is called
by default for every object before its deletion. This method helps Garbage
Collector to close all the resources used by the object and helps JVM in-
memory optimization.
Types of Garbage Collectors in Java: Four types of Garbage collector.
✓ Serial GC – This GC runs with a single thread, in other words, when
this GC runs it freezes all other threads and does its job.
✓ Parallel GC – This GC works in a multi-threaded manner. It runs
multiple threads to collect the garbage, but like the previous one, it also
stops other threads while running GC threads. It is the default GC of
the JVM, and the number of threads, pause time, etc can be controlled
through the command line argument. If not configured properly, this
may have an impact on the overall performance of the application.
✓ CMS GC – Concurrent Mark Sweep, known as CMS garbage collector,
this collector also works in multiple GC threads but this doesn’t stop
the application threads while itself is running. This collector is generally
used in an application with a large set of long-lived data, and the
hardware has two or more processors which will benefit in running GC
threads along with the application threads.
✓ G1 GC – Garbage First, known as G1 Garbage collector is also a multi-
threaded GC. This is the successor of CMS GC and is available after
Java 7. This is a more optimized and powerful GC and is preferably
used in multiprocessor machines that have large heap memory. This
works in two phases, first, it marks the liveness of objects in heap, and
when it collects all the information of empty spaces in heap, it performs
the cleanup activity.
Example:
import java.util.StringTokenizer;
public class Simple
{
public static void main(String args[])
{
StringTokenizer st = new StringTokenizer("my name is khan"," ");
System.out.println(“No. of Token is:”+st.countToken());
while (st.hasMoreTokens())
{
System.out.println(st.nextToken());
}
}
}
Output:
No. of Token is: 4
my
name
is
khan