Objects in Java
Let us now look deep into what are objects. If we consider the real-world, we can
find many objects around us, cars, dogs, humans, etc. All these objects have a state
and a behavior.
If we consider a dog, then its state is - name, breed, color, and the behavior is -
barking, wagging the tail, running.
If you compare the software object with a real-world object, they have very similar
characteristics.
Software objects also have a state and a behavior. A software object's state is
stored in fields and behavior is shown via methods.
So in software development, methods operate on the internal state of an object and
the object-to-object communication is done via methods.
Classes in Java
A class is a blueprint from which individual objects are created.
Following is a sample of a class.
Example
public class Dog {
String breed;
int age;
String color;
void barking() {
}
void hungry() {
}
void sleeping() {
}
}
A class can contain any of the following variable types.
Local variables − Variables defined inside methods, constructors or blocks
are called local variables. The variable will be declared and initialized within
the method and the variable will be destroyed when the method has
completed.
Instance variables − Instance variables are variables within a class but
outside any method. These variables are initialized when the class is
instantiated. Instance variables can be accessed from inside any method,
constructor or blocks of that particular class.
Class variables − Class variables are variables declared within a class,
outside any method, with the static keyword.
A class can have any number of methods to access the value of various kinds of
methods. In the above example, barking(), hungry() and sleeping() are methods.
Following are some of the important topics that need to be discussed when looking
into classes of the Java Language.
Constructors
When discussing about classes, one of the most important sub topic would be
constructors. Every class has a constructor. If we do not explicitly write a
constructor for a class, the Java compiler builds a default constructor for that class.
Each time a new object is created, at least one constructor will be invoked. The
main rule of constructors is that they should have the same name as the class. A
class can have more than one constructor.
Following is an example of a constructor −
Example
public class Puppy {
public Puppy() {
}
public Puppy(String name) {
// This constructor has one parameter, name.
}
}
Java also supports Singleton Classes where you would be able to create only one
instance of a class.
Note − We have two different types of constructors. We are going to discuss
constructors in detail in the subsequent chapters.
Creating an Object
As mentioned previously, a class provides the blueprints for objects. So basically,
an object is created from a class. In Java, the new keyword is used to create new
objects.
There are three steps when creating an object from a class −
Declaration − A variable declaration with a variable name with an object
type.
Instantiation − The 'new' keyword is used to create the object.
Initialization − The 'new' keyword is followed by a call to a constructor.
This call initializes the new object.
Following is an example of creating an object −
Example
In this example, We've created a class named Puppy. In Puppy class constructor,
puppy name is printed so that when the object is created, its name is printed. In
main method, an object is created using new operator.
public class Puppy {
public Puppy(String name) {
// This constructor has one parameter, <i>name</i>.
System.out.println("Passed Name is :" + name );
}
public static void main(String []args) {
// Following statement would create an object myPuppy
Puppy myPuppy = new Puppy( "tommy" );
}
}
If we compile and run the above program, then it will produce the following result
−
Output
Passed Name is :tommy
Accessing Instance Variables and Methods
Instance variables and methods are accessed via created objects. To access an
instance variable, following is the fully qualified path −
/* First create an object */
ObjectReference = new Constructor();
/* Now call a variable as follows */
ObjectReference.variableName;
/* Now you can call a class method as follows */
ObjectReference.MethodName();
Example
In this example, We've created a class named Puppy. In Puppy class constructor,
puppy name is printed so that when the object is created, its name is printed. An
instance variable puppyAge is added and using getter/setter method, we can
manipulate the age. In main method, an object is created using new operator. Age
is updated using setAge() method and using getAge(), the age is printed.
public class Puppy {
int puppyAge;
public Puppy(String name) {
// This constructor has one parameter, <i>name</i>.
System.out.println("Name chosen is :" + name );
}
public void setAge( int age ) {
puppyAge = age;
}
public int getAge( ) {
System.out.println("Puppy's age is :" + puppyAge );
return puppyAge;
}
public static void main(String []args) {
/* Object creation */
Puppy myPuppy = new Puppy( "tommy" );
/* Call class method to set puppy's age */
myPuppy.setAge( 2 );
/* Call another class method to get puppy's age */
myPuppy.getAge( );
/* You can access instance variable as follows as well */
System.out.println("Variable Value :" + myPuppy.puppyAge );
}
}
If we compile and run the above program, then it will produce the following result
−
Output
Name chosen is :tommy
Puppy's age is :2
Variable Value :2
Assigning Object Reference Variables
Object reference variables act differently than you might expect when an
assignment takes
place. For example, what do you think the following fragment does?
Box b1 = new Box();
Box b2 = b1;
You might think that b2 is being assigned a reference to a copy of the object
referred to by b1. That is, you might think that b1 and b2 refer to separate
and distinct objects.
However,this would be wrong. Instead, after this fragment executes, b1 and b2 will
both refer to the same object. The assignment
of b1 to b2 did not allocate any memory or copy any part of the
original object. It simply makes b2 refer to the same object as does b1. Thus, any
changes made to the object through b2 will affect the object
to which b1 is referring, since they are the same object.
This situation is depicted here:
Although b1 and b2 both refer to the same object, they are not linked in
any other way.
For example, a subsequent assignment
to b1 will simply unhook b1 from the original object
without affecting the object or affecting b2. For example:
Box b1 = new Box();
Box b2 = b1;
// ...
b1 = null;
Here, b1 has been set to null, but b2 still points to the original object.
Method in Java
A method is a block of code or collection of statements or a set of code grouped
together to perform a certain task or operation. It is used to achieve
the reusability of code. We write a method once and use it many times. We do not
require to write code again and again. It also provides the easy
modification and readability of code, just by adding or removing a chunk of code.
The method is executed only when we call or invoke it.
The most important method in Java is the main() method. If you want to read more
about the main() method, go through the link https://www.javatpoint.com/java-
main-method.
Method Declaration
The method declaration provides information about method attributes, such as
visibility, return-type, name, and arguments. It has six components that are known
as method header, as we have shown in the following figure.
Method Signature: Every method has a method signature. It is a part of the
method declaration. It includes the method name and parameter list.
Access Specifier: Access specifier or modifier is the access type of the method. It
specifies the visibility of the method. Java provides four types of access specifier:
o Public: The method is accessible by all classes when we use public specifier
in our application.
o Private: When we use a private access specifier, the method is accessible
only in the classes in which it is defined.
o Protected: When we use protected access specifier, the method is accessible
within the same package or subclasses in a different package.
o Default: When we do not use any access specifier in the method declaration,
Java uses default access specifier by default. It is visible only from the same
package only.
Return Type: Return type is a data type that the method returns. It may have a
primitive data type, object, collection, void, etc. If the method does not return
anything, we use void keyword.
Method Name: It is a unique name that is used to define the name of a method. It
must be corresponding to the functionality of the method. Suppose, if we are
creating a method for subtraction of two numbers, the method name must
be subtraction(). A method is invoked by its name.
Parameter List: It is the list of parameters separated by a comma and enclosed in
the pair of parentheses. It contains the data type and variable name. If the method
has no parameter, left the parentheses blank.
Method Body: It is a part of the method declaration. It contains all the actions to
be performed. It is enclosed within the pair of curly braces.
Naming a Method
While defining a method, remember that the method name must be a verb and start
with a lowercase letter. If the method name has more than two words, the first
name must be a verb followed by adjective or noun. In the multi-word method
name, the first letter of each word must be in uppercase except the first word. For
example:
Single-word method name: sum(), area()
Multi-word method name: areaOfCircle(), stringComparision()
It is also possible that a method has the same name as another method name in the
same class, it is known as method overloading.
CONSTRUCTORS
Java constructors or constructors in Java is a terminology used to construct
something in our programs. A constructor in Java is a special method that is used
to initialize objects. The constructor is called when an object of a class is created. It
can be used to set initial values for object attributes.
What are Constructors in Java?
In Java, Constructor is a block of codes similar to the method. It is called when an
instance of the class is created. At the time of calling the constructor, memory for
the object is allocated in the memory. It is a special type of method that is used to
initialize the object. Every time an object is created using the new() keyword, at
least one constructor is called.
Example
// Java Program to demonstrate
// Constructor
import java.io.*;
class Geeks {
// Constructor
Geeks()
{
super();
System.out.println("Constructor Called");
// main function
public static void main(String[] args)
Geeks geek = new Geeks();
Output
Constructor Called
Note: It is not necessary to write a constructor for a class. It is because the java
compiler creates a default constructor (constructor with no arguments) if your class
doesn’t have any.
How Java Constructors are Different From Java Methods?
Constructors must have the same name as the class within which it is defined
it is not necessary for the method in Java.
Constructors do not return any type while method(s) have the return type or
void if does not return any value.
Constructors are called only once at the time of Object creation while
method(s) can be called any number of times.
Now let us come up with the syntax for the constructor being invoked at the time
of object or instance creation.
class Geek
.......
// A Constructor
Geek() {
.......
// We can create an object of the above class
// using the below statement. This statement
// calls above constructor.
Geek obj = new Geek();
The first line of a constructor is a call to super() or this(), (a call to a constructor of
a super-class or an overloaded constructor), if you don’t type in the call to super in
your constructor the compiler will provide you with a non-argument call to super at
the first line of your code, the super constructor must be called to create an object:
If you think your class is not a subclass it actually is, every class in Java is the
subclass of a class object even if you don’t say extends object in your class
definition.
Need of Constructors in Java
Think of a Box. If we talk about a box class then it will have some class variables
(say length, breadth, and height). But when it comes to creating its object(i.e Box
will now exist in the computer’s memory), then can a box be there with no value
defined for its dimensions? The answer is No.
So constructors are used to assign values to the class variables at the time of object
creation, either explicitly done by the programmer or by Java itself (default
constructor).
When Constructor is called?
Each time an object is created using a new() keyword, at least one constructor (it
could be the default constructor) is invoked to assign initial values to the data
members of the same class. Rules for writing constructors are as follows:
The constructor(s) of a class must have the same name as the class name in which
it resides.
A constructor in Java can not be abstract, final, static, or Synchronized.
Access modifiers can be used in constructor declaration to control its access i.e
which other class can call the constructor.
So by far, we have learned constructors are used to initialize the object’s state.
Like methods, a constructor also contains a collection of statements(i.e.
instructions) that are executed at the time of Object creation.
Types of Constructors in Java
Now is the correct time to discuss the types of the constructor, so primarily there
are three types of constructors in Java are mentioned below:
Default Constructor
Parameterized Constructor
Copy Constructor
1. Default Constructor in Java
A constructor that has no parameters is known as default the constructor. A default
constructor is invisible. And if we write a constructor with no arguments, the
compiler does not create a default constructor. It is taken out. It is being
overloaded and called a parameterized constructor. The default constructor
changed into the parameterized constructor. But Parameterized constructor can’t
change the default constructor.
Example:
// Java Program to demonstrate
// Default Constructor
import java.io.*;
// Driver class
class GFG {
// Default Constructor
GFG() { System.out.println("Default constructor"); }
// Driver function
public static void main(String[] args)
GFG hello = new GFG();
}
Output
Default constructor
Note: Default constructor provides the default values to the object like 0, null, etc.
depending on the type.
2. Parameterized Constructor in Java
A constructor that has parameters is known as parameterized constructor. If we
want to initialize fields of the class with our own values, then use a parameterized
constructor.
Example:
// Java Program for Parameterized Constructor
import java.io.*;
class Geek {
// data members of the class.
String name;
int id;
Geek(String name, int id)
this.name = name;
this.id = id;
class GFG {
public static void main(String[] args)
{
// This would invoke the parameterized constructor.
Geek geek1 = new Geek("avinash", 68);
System.out.println("GeekName :" + geek1.name
+ " and GeekId :" + geek1.id);
Output
GeekName :avinash and GeekId :68
Remember: Does constructor return any value?
There are no “return value” statements in the constructor, but the constructor
returns the current class instance. We can write ‘return’ inside a constructor.
Now the most important topic that comes into play is the strong incorporation of
OOPS with constructors known as constructor overloading. Just like methods, we
can overload constructors for creating objects in different ways. The compiler
differentiates constructors on the basis of the number of parameters, types of
parameters, and order of the parameters.
Example:
// Java Program to illustrate constructor overloading
// using same task (addition operation ) for different
// types of arguments.
import java.io.*;
class Geek {
// constructor with one argument
Geek(String name)
System.out.println("Constructor with one "
+ "argument - String : " + name);
// constructor with two arguments
Geek(String name, int age)
System.out.println(
"Constructor with two arguments : "
+ " String and Integer : " + name + " " + age);
// Constructor with one argument but with different
// type than previous..
Geek(long id)
System.out.println(
"Constructor with one argument : "
+ "Long : " + id);
}
class GFG {
public static void main(String[] args)
// Creating the objects of the class named 'Geek'
// by passing different arguments
// Invoke the constructor with one argument of
// type 'String'.
Geek geek2 = new Geek("Shikhar");
// Invoke the constructor with two arguments
Geek geek3 = new Geek("Dharmesh", 26);
// Invoke the constructor with one argument of
// type 'Long'.
Geek geek4 = new Geek(325614567);
Output
Constructor with one argument - String : Shikhar
Constructor with two arguments : String and Integer : Dharmesh 26
Constructor with one argument : Long : 325614567
3. Copy Constructor in Java
Unlike other constructors copy constructor is passed with another object which
copies the data available from the passed object to the newly created object.
Example:
// Java Program for Copy Constructor
import java.io.*;
class Geek {
// data members of the class.
String name;
int id;
// Parameterized Constructor
Geek(String name, int id)
this.name = name;
this.id = id;
// Copy Constructor
Geek(Geek obj2)
this.name = obj2.name;
this.id = obj2.id;
}
}
class GFG {
public static void main(String[] args)
// This would invoke the parameterized constructor.
System.out.println("First Object");
Geek geek1 = new Geek("avinash", 68);
System.out.println("GeekName :" + geek1.name
+ " and GeekId :" + geek1.id);
System.out.println();
// This would invoke the copy constructor.
Geek geek2 = new Geek(geek1);
System.out.println(
"Copy Constructor used Second Object");
System.out.println("GeekName :" + geek2.name
+ " and GeekId :" + geek2.id);
Output
First Object
GeekName :avinash and GeekId :68
Copy Constructor used Second Object
GeekName :avinash and GeekId :68
‘This’ keyword
There can be a lot of usage of Java this keyword. In Java, this is a reference
variable that refers to the current object.
Usage of Java this keyword
Here is given the 6 usage of java this keyword.
1. this can be used to refer current class instance variable.
2. this can be used to invoke current class method (implicitly)
3. this() can be used to invoke current class constructor.
4. this can be passed as an argument in the method call.
5. this can be passed as argument in the constructor call.
6. this can be used to return the current class instance from the method.
Suggestion: If you are beginner to java, lookup only three usages of this keyword.
Example: Using ‘this’ keyword to refer to current class instance variables
// Java code for using 'this' keyword to
// refer current class instance variables
class Test {
int a;
int b;
// Parameterized constructor
Test(int a, int b)
this.a = a;
this.b = b;
void display()
// Displaying value of variables a and b
System.out.println("a = " + a + " b = " + b);
public static void main(String[] args)
Test object = new Test(10, 20);
object.display();
}
}
Output
a = 10 b = 20
Garbage Collection
Garbage collection in Java is the process by which Java programs perform
automatic memory management. Java programs compile to bytecode that can be
run on a Java Virtual Machine, or JVM for short. When Java programs run on the
JVM, objects are created on the heap, which is a portion of memory dedicated to
the program. Eventually, some objects will no longer be needed. The garbage
collector finds these unused objects and deletes them to free up memory.
What is Garbage Collection?
In C/C++, a programmer is responsible for both the creation and destruction of
objects. Usually, programmer neglects the destruction of useless objects. Due to
this negligence, at a certain point, sufficient memory may not be available to create
new objects, and the entire program will terminate abnormally, causing
OutOfMemoryErrors.
But in Java, the programmer need not care for all those objects which are no longer
in use. Garbage collector destroys these objects. The main objective of Garbage
Collector is to free heap memory by destroying unreachable objects. The garbage
collector is the best example of the Daemon thread as it is always running in the
background.
How Does Garbage Collection in Java works?
Java garbage collection is an automatic process. Automatic garbage collection is
the process of looking at heap memory, identifying which objects are in use and
which are not, and deleting the unused objects. An in-use object, or a referenced
object, means that some part of your program still maintains a pointer to that
object. An unused or unreferenced object is no longer referenced by any part of
your program. So the memory used by an unreferenced object can be reclaimed.
The programmer does not need to mark objects to be deleted explicitly. The
garbage collection implementation lives in the JVM.
Using Finalize() method
Just before destroying an object, Garbage Collector calls finalize() method
on the object to perform cleanup activities. Once finalize() method
completes, Garbage Collector destroys that object.
finalize() method is present in Object class with the following prototype.
protected void finalize() throws Throwable
Based on our requirement, we can override finalize() method for performing our
cleanup activities like closing connection from the database.
1. The finalize() method is called by Garbage Collector, not JVM. However,
Garbage Collector is one of the modules of JVM.
2. Object class finalize() method has an empty implementation. Thus, it is
recommended to override the finalize() method to dispose of system
resources or perform other cleanups.
3. The finalize() method is never invoked more than once for any object.
4. If an uncaught exception is thrown by the finalize() method, the exception is
ignored, and the finalization of that object terminates.
Advantages of Garbage Collection in Java
It makes java memory-efficient because the 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 extra effort.
Method Overloading in Java
In Java, Method Overloading allows different methods to have the same name, but
different signatures where the signature can differ by the number of input
parameters or type of input parameters, or a mixture of both.
Method overloading in Java is also known as Compile-time Polymorphism, Static
Polymorphism, or Early binding. In Method overloading compared to the parent
argument, the child argument will get the highest priority.
Example of Method Overloading
// Java program to demonstrate working of method
// overloading in Java
public class Sum {
// Overloaded sum(). This sum takes two int parameters
public int sum(int x, int y) { return (x + y); }
// Overloaded sum(). This sum takes three int parameters
public int sum(int x, int y, int z)
return (x + y + z);
// Overloaded sum(). This sum takes two double
// parameters
public double sum(double x, double y)
return (x + y);
// Driver code
public static void main(String args[])
Sum s = new Sum();
System.out.println(s.sum(10, 20));
System.out.println(s.sum(10, 20, 30));
System.out.println(s.sum(10.5, 20.5));
Output
30
60
31.0
Different Ways of Method Overloading in Java
Changing the Number of Parameters.
Changing Data Types of the Arguments.
Changing the Order of the Parameters of Methods
Overloading constructors
Java supports Constructor Overloading in addition to overloading methods. In
Java, overloaded constructor is called based on the parameters specified when
a new is executed.
When do we need Constructor Overloading?
Sometimes there is a need of initializing an object in different ways. This can be
done using constructor overloading.
For example, the Thread class has 8 types of constructors. If we do not want to
specify anything about a thread then we can simply use the default constructor of
the Thread class, however, if we need to specify the thread name, then we may call
the parameterized constructor of the Thread class with a String args like this:
Thread t= new Thread (" MyThread ");
Example of Constructor Overloading
Below is the improved version of class Box with constructor overloading.
Java
// Java program to illustrate
// Constructor Overloading
class Box {
double width, height, depth;
// constructor used when all dimensions
// specified
Box(double w, double h, double d)
{
width = w;
height = h;
depth = d;
// constructor used when no dimensions
// specified
Box() { width = height = depth = 0; }
// constructor used when cube is created
Box(double len) { width = height = depth = len; }
// compute and return volume
double volume() { return width * height * depth; }
// Driver code
public class Test {
public static void main(String args[])
// create boxes using the various
// constructors
Box mybox1 = new Box(10, 20, 15);
Box mybox2 = new Box();
Box mycube = new Box(7);
double vol;
// get volume of first box
vol = mybox1.volume();
System.out.println("Volume of mybox1 is " + vol);
// get volume of second box
vol = mybox2.volume();
System.out.println("Volume of mybox2 is " + vol);
// get volume of cube
vol = mycube.volume();
System.out.println("Volume of mycube is " + vol);
Output
Volume of mybox1 is 3000.0
Volume of mybox2 is 0.0
Volume of mycube is 343.0
Objects as parameters in Java
Example
In the following Java example, we a have a class with two instance variables name
and age and a parameterized constructor initializing these variables.
We have a method coypObject() which accepts an object of the current class and
initializes the instance variables with the variables of this object and returns it.
In the main method we are instantiating the Student class and making a copy by
passing it as an argument to the coypObject() method.
import java.util.Scanner;
public class Student {
private String name;
private int age;
public Student(){
}
public Student(String name, int age){
this.name = name;
this.age = age;
}
public Student copyObject(Student std){
this.name = std.name;
this.age = std.age;
return std;
}
public void displayData(){
System.out.println("Name : "+this.name);
System.out.println("Age : "+this.age);
}
public static void main(String[] args) {
Scanner sc =new Scanner(System.in);
System.out.println("Enter your name ");
String name = sc.next();
System.out.println("Enter your age ");
int age = sc.nextInt();
Student std = new Student(name, age);
System.out.println("Contents of the original object");
std.displayData();
System.out.println("Contents of the copied object");
Student copyOfStd = new Student().copyObject(std);
copyOfStd.displayData();
}
}
Output
Enter your name
Krishna
Enter your age
20
Contents of the original object
Name : Krishna
Age : 20
Contents of the copied object
Name : Krishna
Age : 20
Argument Passing
In Java, there are two main ways of passing arguments to methods:
passing by value
passing by reference.
Passing by value is the default method in Java. When you pass an argument to a
method by value, a copy of the argument is created and passed to the method. The
original argument is not modified.
Passing by reference is not supported by Java directly, but it can be achieved by
passing a reference object to the method. The reference object will be passed by
value, but the object that it refers to will be modified by the method.
Here is an example of passing an argument to a method by value:
public class Main {
public static void main(String[] args) {
int x = 10;
System.out.println("x before the method: " + x);
changeValue(x);
System.out.println("x after the method: " + x);
}
public static void changeValue(int x) {
x = 20;
}
}
In this example, the changeValue() method is called with the argument 10. The
method then changes the value of the argument to 20, but this change does not
affect the original value of x. This is because x is passed to the method by value, so
a copy of the value is created and passed to the method. The original value is not
modified.
Here is an example of passing an argument to a method by reference:
public class Main {
public static void main(String[] args) {
int[] x = new int[1];
x[0] = 10;
System.out.println("x before the method: " + x[0]);
changeValue(x);
System.out.println("x after the method: " + x[0]);
}
public static void changeValue(int[] x) {
x[0] = 20;
}
}
In this example, the changeValue() method is called with the argument x. The
method then changes the value of the element at index 0 in the array to 20. This
change does affect the original value of x, because x is passed to the method by
reference, so the method is able to modify the object that x refers to.
Passing and Returning Objects in Java
As we know it is core concept that in Java there is always pass by value and not by
pass by reference.So in this post we will focus on that how this concept get
validated in case of passing primitive and passing reference to a method.
In case when a primitive type is passed to a method as argument then the value
assigned to this primitive is get passed to the method and that value becomes local
to that method,which means that any change to that value by the method would not
change the value of primitive that you have passed to the method.
While in case of passing reference to a method again Java follow the same rule of
pass by value now let understand how it happens.
As we know that a reference in Java holds the memory location of object created if
it is assigned to that reference otherwise it is initiated as null.Now the point to
remember here is that the value of the reference is the memory location of the
assigned object,so whenever we pass the reference to any method as argument then
we actually pass the memory location of that object which is assigned to that
particular reference.This technically means that the target method has memory
location of our created object and can access it to.So in case if target method
access our object and make changes to any of property of it than we would
encounter with the changed value in our original object.
Example
public class PassByValue {
static int k =10;
static void passPrimitive(int j) {
System.out.println("the value of passed primitive is " + j);
j = j + 1;
}
static void passReference(EmployeeTest emp) {
EmployeeTest reference = emp;
System.out.println("the value of name property of our object is "+
emp.getName());
reference.setName("Bond");
}
public static void main(String[] args) {
EmployeeTest ref = new EmployeeTest();
ref.setName("James");
passPrimitive(k);
System.out.println("Value of primitive after get passed to method is "+ k);
passReference(ref);
System.out.println("Value of property of object after reference get passed to
method is "+ ref.getName());
}
}
class EmployeeTest {
String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Output
the value of passed primitive is 10
Value of primitive after get passed to method is 10
the value of name property of our object is James
Value of property of object after reference get passed to method is Bond
Recursion in Java
Recursion in java is a process in which a method calls itself continuously. A
method in java that calls itself is called recursive method.
It makes the code compact but complex to understand.
Syntax:
returntype methodname(){
//code to be executed
methodname();//calling same method
}
Java Recursion Example 1: Infinite times
public class RecursionExample1 {
static void p(){
System.out.println("hello");
p();
}
public static void main(String[] args) {
p();
}
}
Output:
hello
hello
...
java.lang.StackOverflowError
Java Recursion Example 2: Finite times
public class RecursionExample2 {
static int count=0;
static void p(){
count++;
if(count<=5){
System.out.println("hello "+count);
p();
}
}
public static void main(String[] args) {
p();
}
}
Output:
hello 1
hello 2
hello 3
hello 4
hello 5
Java Recursion Example 3: Factorial Number
public class RecursionExample3 {
static int factorial(int n){
if (n == 1)
return 1;
else
return(n * factorial(n-1));
}
public static void main(String[] args) {
System.out.println("Factorial of 5 is: "+factorial(5));
}
}
Output:
Factorial of 5 is: 120
Working of above program:
factorial(5)
factorial(4)
factorial(3)
factorial(2)
factorial(1)
return 1
return 2*1 = 2
return 3*2 = 6
return 4*6 = 24
return 5*24 = 120
Java Recursion Example 4: Fibonacci Series
public class RecursionExample4 {
static int n1=0,n2=1,n3=0;
static void printFibo(int count){
if(count>0){
n3 = n1 + n2;
n1 = n2;
n2 = n3;
System.out.print(" "+n3);
printFibo(count-1);
}
}
public static void main(String[] args) {
int count=15;
System.out.print(n1+" "+n2);//printing 0 and 1
printFibo(count-2);//n-2 because 2 numbers are already printed
}
}
Output:
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377
Access Modifiers/Controls in Java
Java provides a number of access modifiers to set access levels for classes,
variables, methods, and constructors. The four access levels are −
Visible to the package, the default. No modifiers are needed.
Visible to the class only (private).
Visible to the world (public).
Visible to the package and all subclasses (protected).
Default Access Modifier - No Keyword
Default access modifier means we do not explicitly declare an access modifier for
a class, field, method, etc.
A variable or method declared without any access control modifier is available to
any other class in the same package. The fields in an interface are implicitly public
static final and the methods in an interface are by default public.
Example
Variables and methods can be declared without any modifiers, as in the following
examples −
String version = "1.5.1";
boolean processOrder() {
return true;
}
Private Access Modifier - Private
Methods, variables, and constructors that are declared private can only be accessed
within the declared class itself.
Private access modifier is the most restrictive access level. Class and interfaces
cannot be private.
Variables that are declared private can be accessed outside the class, if public
getter methods are present in the class.
Using the private modifier is the main way that an object encapsulates itself and
hides data from the outside world.
Example
The following class uses private access control −
public class Logger {
private String format;
public String getFormat() {
return this.format;
}
public void setFormat(String format) {
this.format = format;
}
}
Here, the format variable of the Logger class is private, so there's no way for other
classes to retrieve or set its value directly.
So, to make this variable available to the outside world, we defined two public
methods: getFormat(), which returns the value of format, and setFormat(String),
which sets its value.
Public Access Modifier - Public
A class, method, constructor, interface, etc. declared public can be accessed from
any other class. Therefore, fields, methods, blocks declared inside a public class
can be accessed from any class belonging to the Java Universe.
However, if the public class we are trying to access is in a different package, then
the public class still needs to be imported. Because of class inheritance, all public
methods and variables of a class are inherited by its subclasses.
Example
The following function uses public access control −
public static void main(String[] arguments) {
// ...
}
The main() method of an application has to be public. Otherwise, it could not be
called by a Java interpreter (such as java) to run the class.
Protected Access Modifier - Protected
Variables, methods, and constructors, which are declared protected in a superclass
can be accessed only by the subclasses in other package or any class within the
package of the protected members' class.
The protected access modifier cannot be applied to class and interfaces. Methods,
fields can be declared protected, however methods and fields in a interface cannot
be declared protected.
Protected access gives the subclass a chance to use the helper method or variable,
while preventing a nonrelated class from trying to use it.
Example
The following parent class uses protected access control, to allow its child class
override openSpeaker() method −
class AudioPlayer {
protected boolean openSpeaker(Speaker sp) {
// implementation details
}
}
class StreamingAudioPlayer extends AudioPlayer {
boolean openSpeaker(Speaker sp) {
// implementation details
}
}
Here, if we define openSpeaker() method as private, then it would not be
accessible from any other class other than AudioPlayer. If we define it as public,
then it would become accessible to all the outside world. But our intention is to
expose this method to its subclass only, that's why we have used protected
modifier.
Access Control and Inheritance
The following rules for inherited methods are enforced −
Methods declared public in a superclass also must be public in all
subclasses.
Methods declared protected in a superclass must either be protected or
public in subclasses; they cannot be private.
Methods declared private are not inherited at all, so there is no rule for them.
Example
In this example, we've created a class with a private variable age and a variable
with default scope as name. Using setter/getter method, we're updating age and
getting value and name is updated directly.
public class Puppy {
private int age;
String name;
public Puppy() {
}
public void setAge( int age ) {
this.age = age;
}
public int getAge( ) {
return age;
}
public static void main(String []args) {
Puppy myPuppy = new Puppy();
// update age variable using method call
myPuppy.setAge( 2 );
// update name directly
myPuppy.name = "Tommy";
System.out.println("Age: " + myPuppy.getAge() +", name: " + myPuppy.name
);
}
}
Output
Age: 2, name: Tommy
Static variables and methods
The static variable is a class level variable and it is common to all the class objects
i.e. a single copy of the static variable is shared among all the class objects.
A static method manipulates the static variables in a class. It belongs to the class
instead of the class objects and can be invoked without using a class object.
The static initialization blocks can only initialize the static instance variables.
These blocks are only executed once when the class is loaded.
A program that demonstrates this is given as follows:
Example
Live Demo
public class Demo {
static int x = 10;
static int y;
static void func(int z) {
System.out.println("x = " + x);
System.out.println("y = " + y);
System.out.println("z = " + z);
}
static {
System.out.println("Running static initialization block.");
y = x + 5;
}
public static void main(String args[]) {
func(8);
}
}
Output
Running static initialization block.
x = 10
y = 15
z=8
Now let us understand the above program.
The class Demo contains static variables x and y. The static method func() prints
the values of x, y and z. A code snippet which demonstrates this is as follows:
static int x = 10;
static int y;
static void func(int z) {
System.out.println("x = " + x);
System.out.println("y = " + y);
System.out.println("z = " + z);
}
The static initialization block initializes the static variable y. In the main() method,
the func() method is called. A code snippet which demonstrates this is as follows:
static {
System.out.println("Running static initialization block.");
y = x + 5;
}
public static void main(String args[]) {
func(8);
}
Final variables and methods
Final Variables
A final variable can be explicitly initialized only once. A reference variable
declared final can never be reassigned to refer to an different object.
However, the data within the object can be changed. So, the state of the object can
be changed but not the reference.
With variables, the final modifier often is used with static to make the constant a
class variable.
Example
public class Tester {
final int value = 10;
// The following are examples of declaring constants:
public static final int BOXWIDTH = 6;
static final String TITLE = "Manager";
public void changeValue() {
value = 12; // will give an error
}
public void displayValue(){
System.out.println(value);
}
public static void main(String[] args) {
Tester t = new Tester();
t.changeValue();
t.displayValue();
}
}
Output
Compiler will throw an error during compilation.
Tester.java:9: error: cannot assign a value to final variable value
value = 12; // will give an error
^
1 error
final method in Java
The final modifier for finalizing the implementations of classes, methods, and
variables.
We can declare a method as final, once you declare a method final it cannot be
overridden. So, you cannot modify a final method from a sub class.
The main intention of making a method final would be that the content of the
method should not be changed by any outsider.
Example
public class FinalMethodExample {
public final void display(){
System.out.println("Hello welcome to Tutorialspoint");
}
public static void main(String args[]){
new FinalMethodExample().display();
}
class Sample extends FinalMethodExample{
public void display(){
System.out.println("hi");
}
}
}
Output
FinalMethodExample.java:12: error: display() in FinalMethodExample.Sample
cannot override display() in FinalMethodExample
public void display(){
^
overridden method is final
1 error
Nested Class in Java
A nested class is a class inside a class in Java. It is of two types i.e. Static nested
class and Inner class. A static nested class is a nested class that is declared as static.
An inner class is a non-static nested class.
A program that demonstrates a static nested class is given as follows:
Example
Live Demo
public class Class1 {
static class Class2 {
public void func() {
System.out.println("This is a static nested class");
}
}
public static void main(String args[]) {
Class1.Class2 obj = new Class1.Class2();
obj.func();
}
}
Output
This is a static nested class
Now let us understand the above program.
The class Class1 is the outer class and the class Class2 is the static nested class.
The method func() in Class2 prints "This is a static nested class". A code snippet
which demonstrates this is as follows:
public class Class1 {
static class Class2 {
public void func() {
System.out.println("This is a static nested class");
}
}
}
An object obj is declared in the method main() in Class1. Then func() is called. A
code snippet which demonstrates this is as follows:
public static void main(String args[]) {
Class1.Class2 obj = new Class1.Class2();
obj.func();
}
Inner Class in Java
Nested Classes
In Java, just like methods, variables of a class too can have another class as its
member. Writing a class within another is allowed in Java. The class written within
is called the nested class, and the class that holds the inner class is called the outer
class.
Syntax
Following is the syntax to write a nested class. Here, the class Outer_Demo is the
outer class and the class Inner_Demo is the nested class.
class Outer_Demo {
class Inner_Demo {
}
}
Nested classes are divided into two types −
Non-static nested classes − These are the non-static members of a class.
Static nested classes − These are the static members of a class.
Inner Classes (Non-static Nested Classes)
Inner classes are a security mechanism in Java. We know a class cannot be
associated with the access modifier private, but if we have the class as a member
of other class, then the inner class can be made private. And this is also used to
access the private members of a class.
Inner classes are of three types depending on how and where you define them.
They are −
Inner Class
Method-local Inner Class
Anonymous Inner Class
Inner Class
Creating an inner class is quite simple. You just need to write a class within a
class. Unlike a class, an inner class can be private and once you declare an inner
class private, it cannot be accessed from an object outside the class.
Following is the program to create an inner class and access it. In the given
example, we make the inner class private and access the class through a method.
Example
class Outer_Demo {
int num;
// inner class
private class Inner_Demo {
public void print() {
System.out.println("This is an inner class");
}
}
// Accessing he inner class from the method within
void display_Inner() {
Inner_Demo inner = new Inner_Demo();
inner.print();
}
}
public class My_class {
public static void main(String args[]) {
// Instantiating the outer class
Outer_Demo outer = new Outer_Demo();
// Accessing the display_Inner() method.
outer.display_Inner();
}
}
Here you can observe that Outer_Demo is the outer class, Inner_Demo is the
inner class, display_Inner() is the method inside which we are instantiating the
inner class, and this method is invoked from the main method.
If you compile and execute the above program, you will get the following result −
Output
This is an inner class.
Accessing the Private Members
As mentioned earlier, inner classes are also used to access the private members of a
class. Suppose, a class is having private members to access them. Write an inner
class in it, return the private members from a method within the inner class,
say, getValue(), and finally from another class (from which you want to access the
private members) call the getValue() method of the inner class.
To instantiate the inner class, initially you have to instantiate the outer class.
Thereafter, using the object of the outer class, following is the way in which you
can instantiate the inner class.
Outer_Demo outer = new Outer_Demo();
Outer_Demo.Inner_Demo inner = outer.new Inner_Demo();
The following program shows how to access the private members of a class using
inner class.
Example
class Outer_Demo {
// private variable of the outer class
private int num = 175;
// inner class
public class Inner_Demo {
public int getNum() {
System.out.println("This is the getnum method of the inner class");
return num;
}
}
}
public class My_class2 {
public static void main(String args[]) {
// Instantiating the outer class
Outer_Demo outer = new Outer_Demo();
// Instantiating the inner class
Outer_Demo.Inner_Demo inner = outer.new Inner_Demo();
System.out.println(inner.getNum());
}
}
If you compile and execute the above program, you will get the following result −
Output
This is the getnum method of the inner class: 175
Method-local Inner Class
In Java, we can write a class within a method and this will be a local type. Like
local variables, the scope of the inner class is restricted within the method.
A method-local inner class can be instantiated only within the method where the
inner class is defined. The following program shows how to use a method-local
inner class.
Example
public class Outerclass {
// instance method of the outer class
void my_Method() {
int num = 23;
// method-local inner class
class MethodInner_Demo {
public void print() {
System.out.println("This is method inner class "+num);
}
} // end of inner class
// Accessing the inner class
MethodInner_Demo inner = new MethodInner_Demo();
inner.print();
}
public static void main(String args[]) {
Outerclass outer = new Outerclass();
outer.my_Method();
}
}
If you compile and execute the above program, you will get the following result −
Output
This is method inner class 23
Anonymous Inner Class
An inner class declared without a class name is known as an anonymous inner
class. In case of anonymous inner classes, we declare and instantiate them at the
same time. Generally, they are used whenever you need to override the method of
a class or an interface. The syntax of an anonymous inner class is as follows −
Syntax
AnonymousInner an_inner = new AnonymousInner() {
public void my_method() {
........
........
}
};
The following program shows how to override the method of a class using
anonymous inner class.
Example
abstract class AnonymousInner {
public abstract void mymethod();
}
public class Outer_class {
public static void main(String args[]) {
AnonymousInner inner = new AnonymousInner() {
public void mymethod() {
System.out.println("This is an example of anonymous inner class");
}
};
inner.mymethod();
}
}
If you compile and execute the above program, you will get the following result −
Output
This is an example of anonymous inner class
In the same way, you can override the methods of the concrete class as well as the
interface using an anonymous inner class.
Strings Class & String Handling Methods
Strings, which are widely used in Java programming, are a sequence of characters.
In Java programming language, strings are treated as objects.
The Java platform provides the String class to create and manipulate strings.
Creating Strings
The most direct way to create a string is to write −
String greeting = "Hello world!";
Whenever it encounters a string literal in your code, the compiler creates a String
object with its value in this case, "Hello world!'.
As with any other object, you can create String objects by using the new keyword
and a constructor. The String class has 11 constructors that allow you to provide
the initial value of the string using different sources, such as an array of characters.
Example
Live Demo
public class StringDemo {
public static void main(String args[]) {
char[] helloArray = { 'h', 'e', 'l', 'l', 'o', '.' };
String helloString = new String(helloArray);
System.out.println( helloString );
}
}
This will produce the following result −
Output
hello.
Note − The String class is immutable, so that once it is created a String object
cannot be changed. If there is a necessity to make a lot of modifications to Strings
of characters, then you should use String Buffer & String Builder Classes.
String Length
Methods used to obtain information about an object are known as accessor
methods. One accessor method that you can use with strings is the length()
method, which returns the number of characters contained in the string object.
The following program is an example of length(), method String class.
Example
public class StringDemo {
public static void main(String args[]) {
String palindrome = "Dot saw I was Tod";
int len = palindrome.length();
System.out.println( "String Length is : " + len );
}
}
This will produce the following result −
Output
String Length is : 17
Concatenating Strings
The String class includes a method for concatenating two strings −
string1.concat(string2);
This returns a new string that is string1 with string2 added to it at the end. You can
also use the concat() method with string literals, as in −
"My name is ".concat("Zara");
Strings are more commonly concatenated with the + operator, as in −
"Hello," + " world" + "!"
which results in −
"Hello, world!"
Let us look at the following example −
Example
public class StringDemo {
public static void main(String args[]) {
String string1 = "saw I was ";
System.out.println("Dot " + string1 + "Tod");
}
}
This will produce the following result −
Output
Dot saw I was Tod
Creating Format Strings
You have printf() and format() methods to print output with formatted numbers.
The String class has an equivalent class method, format(), that returns a String
object rather than a PrintStream object.
Using String's static format() method allows you to create a formatted string that
you can reuse, as opposed to a one-time print statement. For example, instead of −
Example
System.out.printf("The value of the float variable is " +
"%f, while the value of the integer " +
"variable is %d, and the string " +
"is %s", floatVar, intVar, stringVar);
You can write −
String fs;
fs = String.format("The value of the float variable is " +
"%f, while the value of the integer " +
"variable is %d, and the string " +
"is %s", floatVar, intVar, stringVar);
System.out.println(fs);
String Methods
Here is the list of methods supported by String class −
Sr.No. Method & Description
char charAt(int index)
1
Returns the character at the specified index.
int compareTo(Object o)
2
Compares this String to another Object.
int compareTo(String anotherString)
3
Compares two strings lexicographically.
int compareToIgnoreCase(String str)
4
Compares two strings lexicographically, ignoring case differences.
String concat(String str)
5
Concatenates the specified string to the end of this string.
boolean contentEquals(StringBuffer sb)
6
Returns true if and only if this String represents the same sequence of characters
as the specified StringBuffer.
7 static String copyValueOf(char[] data)
Returns a String that represents the character sequence in the array specified.
static String copyValueOf(char[] data, int offset, int count)
8
Returns a String that represents the character sequence in the array specified.
boolean endsWith(String suffix)
9
Tests if this string ends with the specified suffix.
boolean equals(Object anObject)
10
Compares this string to the specified object.
boolean equalsIgnoreCase(String anotherString)
11
Compares this String to another String, ignoring case considerations.
byte[] getBytes()
12
Encodes this String into a sequence of bytes using the platform's default charset,
storing the result into a new byte array.
byte[] getBytes(String charsetName)
13
Encodes this String into a sequence of bytes using the named charset, storing the
result into a new byte array.
void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)
14
Copies characters from this string into the destination character array.
int hashCode()
15
Returns a hash code for this string.
int indexOf(int ch)
16
Returns the index within this string of the first occurrence of the specified
character.
int indexOf(int ch, int fromIndex)
17
Returns the index within this string of the first occurrence of the specified
character, starting the search at the specified index.
int indexOf(String str)
18
Returns the index within this string of the first occurrence of the specified
substring.
int indexOf(String str, int fromIndex)
19
Returns the index within this string of the first occurrence of the specified
substring, starting at the specified index.
String intern()
20
Returns a canonical representation for the string object.
int lastIndexOf(int ch)
21
Returns the index within this string of the last occurrence of the specified
character.
int lastIndexOf(int ch, int fromIndex)
22
Returns the index within this string of the last occurrence of the specified
character, searching backward starting at the specified index.
int lastIndexOf(String str)
23
Returns the index within this string of the rightmost occurrence of the specified
substring.
int lastIndexOf(String str, int fromIndex)
24
Returns the index within this string of the last occurrence of the specified
substring, searching backward starting at the specified index.
int length()
25
Returns the length of this string.
boolean matches(String regex)
26
Tells whether or not this string matches the given regular expression.
boolean regionMatches(boolean ignoreCase, int toffset, String other, int
27 ooffset, int len)
Tests if two string regions are equal.
boolean regionMatches(int toffset, String other, int ooffset, int len)
28
Tests if two string regions are equal.
String replace(char oldChar, char newChar)
29
Returns a new string resulting from replacing all occurrences of oldChar in this
string with newChar.
String replaceAll(String regex, String replacement
30
Replaces each substring of this string that matches the given regular expression
with the given replacement.
String replaceFirst(String regex, String replacement)
31
Replaces the first substring of this string that matches the given regular
expression with the given replacement.
String[] split(String regex)
32
Splits this string around matches of the given regular expression.
String[] split(String regex, int limit)
33
Splits this string around matches of the given regular expression.
boolean startsWith(String prefix)
34
Tests if this string starts with the specified prefix.
boolean startsWith(String prefix, int toffset)
35
Tests if this string starts with the specified prefix beginning a specified index.
CharSequence subSequence(int beginIndex, int endIndex)
36
Returns a new character sequence that is a subsequence of this sequence.
String substring(int beginIndex)
37
Returns a new string that is a substring of this string.
String substring(int beginIndex, int endIndex)
38
Returns a new string that is a substring of this string.
char[] toCharArray()
39
Converts this string to a new character array.
String toLowerCase()
40
Converts all of the characters in this String to lower case using the rules of the
default locale.
String toLowerCase(Locale locale)
41
Converts all of the characters in this String to lower case using the rules of the
given Locale.
String toString()
42
This object (which is already a string!) is itself returned.
String toUpperCase()
43
Converts all of the characters in this String to upper case using the rules of the
default locale.
String toUpperCase(Locale locale)
44
Converts all of the characters in this String to upper case using the rules of the
given Locale.
String trim()
45
Returns a copy of the string, with leading and trailing whitespace omitted.
static String valueOf(primitive data type x)
46
Returns the string representation of the passed data type argument.
Command line arguments in Java
Sometimes you will want to pass some information on a program when you run it.
This is accomplished by passing command-line arguments to main( ).
A command-line argument is an information that directly follows the program's
name on the command line when it is executed. To access the command-line
arguments inside a Java program is quite easy. They are stored as strings in the
String array passed to main( ).
Example
The following program displays all of the command-line arguments that it is called
with -
public class CommandLine {
public static void main(String args[]) {
for(int i = 0; i<args.length; i++) {
System.out.println("args[" + i + "]: " + args[i]);
}
}
}
Try executing this program as shown here -
$java CommandLine this is a command line 200 -100
Output
This will produce the following result -
args[0]: this
args[1]: is
args[2]: a
args[3]: command
args[4]: line
args[5]: 200
args[6]: -100