Ad
Ad
Ad
Tag

java

Browsing

 

Access Specifiers in Java
Access Specifiers in Java

Access Specifiers in Java:

Access specification is the mechanism by which we can control the use of the objects,its members and methods.
Below are the access specifier available in Java:

  1. public
  2. private
  3. protected
  4. final
  5. private and protected
  6. abstract
  7. friendly/default

Java access control mechanism (JLS-6.6) determines the accessibility of classes, interfaces and members. The accessibility of an entity is determined by the location where it is declared and by which, if any access modifiers (private protected and public ) is present in the entities declaration.

By proper using of these, we can hide information from users. The rule of thumb is that we should make each class or member as inaccessible as possible.

For top level (non-nested) classes and interfaces there are only two possible access levels(Package –Private and public). If we declare a top level class or interface with the public Modifier, it will be public.Otherwise it will be package private.

If a package private top level class or interface is used only within a single class, we need to consider making it a private nested class( or interface) of the class in which it is used. This further reduces it’s accessibility,It is however not as important to do this as it is to make an unnecessary public class package private because a package private class is already part of the package’s implementation rather than APIs.

public Access Specifier:

public classes,methods can be accessed from any other classes,methods.The public access specifier is optional and automatic.Mostly customer facing methods of a class are public in nature so that they can accept calls from other classes.So an element with public access specifier has the widest possible visibility and accessibility.

private Access Specifier: 

Elements with private access specifiers are having highest degree of protection. private elements,methods can only be accessed from that class where it is defined.A private element or method is not visible to any other class or it’s subclass.Also a subclass can not override a non private method and make a new private method.This is useful when we want to exclude classes that should not have access to the classes being defined in other package.We need to provide public accessor or public mutator method(setter and getter) in order to access private variables from other class in different package.in a simple word, the private access modifier specifies that no member except that particular class(inside methods of that class). Other classes in the same package can not access private members. A protected element is same as final.
private allows developers to work on some data members without affecting the user’s code.It is also very important in terms of multi-threading coding. Any method for that class which acts as a ‘helper’can be made private to ensure that it is not used in the package or anywhere else thus prohibits us from changing or removing the method.Private methods are the helper function in java.
A class member declared as private will remain private to its class.It is not accessible by any class outside its class including its subclass.

Package private

The member is accessible from any class in the package where it is declared. Technically known as default access. This is the access level we get if no access modifier is specified.

protected Access Specifier:

protected elements are between public and default/friendly or Protected is sort of private.The protected elements are visible not only to all classes and subclasses in the same package but also the subclasses in other package.It deals with mainly inheritance which takes an existing class and adds new members to another class without touching the existing class(base class). We can change the methods of existing class. To inherit from an existing class we need to extend that class.protected elements can be used only inside the class or it’s subclass.An inherited class can access a protected members as well as public members.A subclass can override a protected method and variable.Non-subclasses in the other packages can not access the protected elements.


class ClassA extends ClassB{
 

That is if a class inherits another class of another package, the only members we have access are public members of the base class(if we are inheriting class of the same package-we will have access to friendly/default members) and all the protected members of the class.If the creator of the base class wants to give access to some of its members to the derived classes as but not to the whole world. then protected modifier is the best suitable.A protected method has friendly access within the same package.

public and protected can not be applied to a class.As they does not make any sense. A class can not be private as it would make it accessible to no one but the class itself.If we want not to have anyone access to the class,we can make all the constructor private, that prevents anyone but us,inside a static member of the class from creating an object of that class.

class ClassA{
private ClassA()
{
}
static ClassA makeObjectA()
{
return new ClassA();
}
}
public class MyClass{
public static void main(String args[])
{
ClassA ca=new ClassA();
//not possible to call the constructor as it is private
ClassA ca=ClassA.makeObjectA();
//returns the object of the class ClassA.This is how we create an object,preventing anyone from directly accessing a particular constructor or constructors.
}

}

final Access Specifier:

All final elements of a class can not be overridden by subclasses of that class. classes can also be declared as final which denotes that the same class can not be subclassed. Please refer final keyword here.

private protected Access Specifier:

A field can be declared with two keywords private and protected together like:


private protected int codeName;

This gives visibility level in between protected and private access. The specifier makes the field visible in all sub classes regardless of what package they are in. These fields are not accessible by other classes in the same package.

abstract Access Specifier:

if anybody wants to define the method in a subclass, he can choose to use abstract keyword to mark it. In case of method , the method has to be defined in subclass. In case of class it signifies that the class is not fully implemented and it should not be instantiated.

 

friendly/default Access Specifier:

In case no access specifier is specified,java by default mark an element as default/friendly.It is a special version of public specifier.It means all other classes in the same package have access to these friendly members but classes outside of the package , these elements becomes private.Since a compilation unit(a file) can only belong to a single package, all the classes within a single compilation units are automatically friendly with each other.It allows us to group related classes together in a package so that they can easily interact with each other.(granting mutual access to all the friendly elements of the package to each other).An inherited class can access friendly/default members if both the class belong to same package.

So the difference between public and default specifier is that the public makes elements visible in all classes regardless of their package but friendly makes an element visible only in the same package but not in other packages.


public class ClassA{
int x;
private String s;
public void getData()
{
}
final void deleteData()
{
}
private void printData()
{
}
}
class ClassB extends ClassA{
// ClassB can access public and protected methods or elements of ClassA . However it can not override deleteData().
}
final class ClassC{
}
class ClassD extends ClassC{
//compilation error as ClassC is final hence can not be subclasses or extended.
}
abstract ClassE{
...
...
abstract void myMethod();
}
public class classF{
public static vois main(String args[])
{
ClassE def=new ClassE();
//compilation error as ClassE is an abstract class hence can not be instanciated
}
}

Here is a shortcut table to remember :

NoSpecifierVisibilityComment
1fiendly/defaultclasses of the same package and that class
2publicAll
3privateonly that class
4protectedthat class, other class of the same package,child class
5finalthat class and subclassall final elements are constants so can not overridden.
6abstractthat class and child classabstract methods needs to be defined in childclass

Interface:

Access control is often referred to as implementation hiding.Wrapping data and methods within classes(combined with implementation hiding,this is often called encapsulation) produces a data type with characteristics and behaviors ,but access control puts boundaries within that data type for the below reason:

  • This is to establish what client programmer can and can’t use.We can build our internal mechanism into the structure without worrying that the client programmers will think it is part of the interface they should be using.
  • This separates the interface from implementation. If the structure is used in a set of programs ,but the users can’t do anything but send message to the public interface then we can change anything that is not public(example-default/friendly,protected or private) without requiring modification to their code.

Another view to remember :

Access Modifier—>
Access Location
|
|
/
publicprotectedfriendlyprivate protectedprivate
same classyesyesyesyesyes
sub class in
same package
yesyesyesyesNo
Other classes in
same package
yesyesyesNoNo
sub classes in
other package
yesyesNoyesNo
Non Subclass in
other package
yesNoNoNoNo

General rule of thumb while choosing Specifiers:

 

  1. use public if the element is to be visible everywhere.
  2. use protected if the element is to be visible everywhere in the current package and also sub classes in other package.
  3. use default or friendly if the element is to be visible everywhere in the current package only
  4. use private protected if the element is to be visible only in subclasses regardless of packages.
  5. use private if the element is not to be visible anywhere except in its own class.

After carefully design our class’s public APIs, our next step should be to make all other members private.If another class in the same package needs to access member, we must put default modifier for the member not private. It is always better to decouple the modules from one another. If not done, it may lead to ‘leak’ into exported API if the class implements serializable interface.

If a method overrides a superclass method, it is not permitted to have a lower access level in the subclass then it does in the superclass. This is necessary to ensure that an instance of the subclass is usable anywhere that an instance of the superclass is usable. If we violate this rule, the compiler will generate an error message when we try to compile the subclass.

A special case of this rule is that if a class implements an interface, all of the class methods that are also present in the interface must be declared public. This is because all methods in an interface are implicitly public.

Public classes should rarely have public field but surely have public methods. If a field is non final or is a final reference to a mutable object, we loose the ability to limit the values that may be stored in the fields by making it public.

We also loose the ability to take any actions when the field is modified. A simple consequence is that classes with public mutable fields are not thread safe. Even if the field is final and does not referred to a mutable object by making the field public, we loose the flexibility to switch to a new internal data representation in which the field does not exists .

However there is an exception to the rule that private classes should not have public fields,that is public class can contain a public field when they are constant via public static final fields. By convention names of these constants capital letters with words separated by underscore.They can contain either a primitive values or references to immutable objects. A final field containing a reference to mutable object has all the disadvantages of a normal field. While the reference cannot be modified, the referenced object can be modified.

This is one gateway of bug.

Note that a non-zero length array is always mutable,hence it is very wrong design approach to have public static final array field.

//-A potential security issue


public static final type[] my array={….};

If a class have such field, the user may change the contents of the array. This could be a security concern too. The public array should be replaced by a private array and a public immutable list:-


Private static final type []my array={….};
Public static final List myArrayValues= Collections.unmodifiableList (arrays.asList (my array));

Alternatively, if we need compile time type safe and little slow solution, we can replace the public array field with a public method that returns a copy of private array.


private static final Type[] myarray={…..};
public static final Type [] getMyArray(){
return (Type[]) my array.clone();
}
Points to Remember
  1. We must reduce accessibility as much as possible .
  2. we need to design the public API is such a way that APIs will not be part of any classes(stray) ,interface or members
  3. Public classes should have no public field except public final static fields .(constants)
  4. Object referenced by public static final fields are immutable.

Normally we create an object of the class using the new operator and access the methods and variables. Each instance of a class has its own copy of any member variables and methods.It is also possible to create member variables and methods that belongs to the class independent of any object of that class.So if we want to have one piece of storage for a particular piece of data, regardless of how many objects are created or even no objects are created Or a method that is not associated with any particular object of a class. We can call that method if no instance of the class has been created. In both the scenario we can achieve using static keyword.

A class contains two sections
1. Variable declaration(instance variables)
2. Method declaration(instance methods).When we declare variables(s) or method(s) is/are static, it means that the data or method is not associated with any particular object instance of that class. Thus even if we never create an object of that class, we can still call them or access the piece of static data.

For a non-static data member or method, we need to create an object of the class as they belong to the particular object they are working with. Since static methods/variables don’t need any objects to be created before they are used, they can not access non-static members and methods. This is because non-static members and methods first tied with an object.

To remember easily we can say anything with the static keyword (modifier) associated to it will be the property of the class but not the property of the object.These are common to all instances of a class. Since there will one class and many objects are created from it, we can say the static keyword associated things are created only once and shared among the objects of that class. This is somewhat a global variable or global function concept. The meaning of static varies from context to context.  Static things load first while we execute any program.Static elements gets executed only once at the beginning of the program.
Java libraries contain a huge set of static members.
Static keyword can be applied to

  • Class
  • Methods
  • Block
  • Variable
  • Import 
Static Class:
Java, in general, does not allow normal classes to be static but it allows any number of classes created inside a non-static class. They are called Nested Inner class. Nested Inner classes can be static in nature.
Static Methods:
static methods are those methods that belong to a class.They don’t belong to the objects created from the class. It can access only static data but not any non-static data elements. A static method can call only a static method(s) but can not call any non-static methods. A static method can only be accessed directly without creating an object by using the <ClassName>.<MethodName()>. A static method can not refer to this or super keywords. So we can not call a non-static method from inside a static method. But we can call a static method from inside of a non-static method(by creating an instance of the class).


class myStaticTest{
static int i=10;
}
class staticIncrementTest{
public static void increment(){
//Accessing a static variable from a static method by creating Object
myStaticTest SI=new myStaticTest();
SI.i++;
//Accessing a static variable from a static method directly
myStaticTest.i++;
}
}

The main method is a static method hence can be called without creating an object and before any other thing runs.
An example to call a static method from inside of a static method:


public class MyStaticTestDemo {
static int sum(int x, int y) {
return x + y;
}
public static void main(String[] args) {
int ans = MyStaticTestDemo.sum(15, 13);
System.out.println(ans);
}
}

The output of the code: 28 In the above example if we remove the static modifier from sum subroutine, it will become non static method. In that case statioc main will try to access non static sum() method. This is not allowed in java.JVM will throw the below exception: Exception in thread “main” java.lang.Error: Unresolved compilation problem: Cannot make a static reference to the non-static method sum(int, int) from the type MyStaticTestDemo at com.myDigitalVoice.MyStaticTestDemo.main(MyStaticTestDemo.java:8) An example to call a non static method from inside of a static method:


public class MyStaticTestDemo {
int sum(int x, int y) {
return x + y;
}
public static void main(String[] args) {
MyStaticTestDemo mstd=new MyStaticTestDemo();
int ans=mstd.sum(12,13);
System.out.println(ans);
}
}

Output of the code: 25

Static Block:
A block that is loaded and executed as soon as JVM loads a java class. Even this happens before the execution of the main method.
There is a popular question asked to write a code to print Hello World without main. The same can be done through this.


public class myDemo{
static{
System.out.println("Hello World");
system.exit(0);
}
}

We need to terminate the code as after this the JVM will look for the main method which is not present and gives an error message.
$javac myDemo.java
$java -Xmx128M -Xms16M myDemo
Error: Main method not found in class myDemo, please define the main method as:
public static void main(String[] args)
or a JavaFX application class must extend JavaFX.application.Application

Static Variables:
Again static variables belong to the class and initialized at first during execution. A single copy of the static variable is shared by all instances of the class.A static variable can be accessed directly by using <ClassName>.<VariableName>


public Class myStaticTest{
static int i=10;
}

now if we write two lines of code:


myStaticTest t1=new myStaticTest();
myStaticTest t2=new myStaticTest();

at this point, t1.i and t2.i will share the same i and have the same value as 10.
There are two ways to access static data:

  1. by creating an object of that class like t1.i;
  2. directly through its class name like myStaticTest.i;
Remember that static variables are like normal variable and not constant hence we can do any operations on that variable like- t1.i=ti1.i+1; this will increase the i value by one and i becomes 11. Now all the places where this i is referred will get i=11

here is one example:


public class MyStaticTestDemo {

public static void main(String[] args) {
System.out.println(myStaticTest.i);
staticIncrementTest.increment();
System.out.println(myStaticTest.i);
}
}
class myStaticTest{
static int i=10;
}
class staticIncrementTest{
public static void increment(){
myStaticTest SI=new myStaticTest();
SI.i++;
myStaticTest.i++;
}
}

Output of the code: 10 12

Another example:


class MyOperations{
static int addition(int x,int y)
{
return x+y;
}
static int substract(int x,int y)
{
return x-y;
}
static int multiply(int x,int y)
{
return x*y;
}
}
public class TestMyOperations{
public static void main(String args[])
{
int a=MyOperations.addition(10,15);
int b=MyOperations.substract(15,10);
int c=MyOperations.multiply(10,15);
System.out.println("Addition of these two number "+a);
System.out.println("subtract of these two number "+b);
System.out.println("multiply of these two number "+c);
}
}

output of the code:
$javac TestMyOperations.java
$java -Xmx128M -Xms16M TestMyOperations
Addition of these two number 25
subtract of these two number 5
multiply of these two number 150
Another example for static and non static variables:


class Student{
int a; //non static initialized to zero
static int b;//static initaialized to zero when class is loaded
Student()
{
b++;
}
public void getData(){
System.out.println(a);
System.out.println(b);
}
// public static void increment()
// {
// a++;
// }
//The above code will throw an compilation error- non-static variable a cannot be referenced from a static context
// a++;
// ^
}
public class Demo{
public static void main(String []args){
Student s1=new Student();
Student s2=new Student();
s1.getData();
s2.getData();
Student.b++;
s1.getData();
}
}

the output of the code:
$javac Demo.java
$java -Xmx128M -Xms16M Demo
0
2
0
2
0
3

It is often told that static methods are not proper object oriented design as they have the semantics of a global function.And with static methods we do not send message to the objects as there is no this keyword support.However they are pragmatic and useful.

Static Imports:
Import directives or statements provides us to refer to a class. like javax.swing.JPanel for JPanel. If we see the directive is little complex and compound in nature.Every time we need to mention in order to use them .To refer the a static members we need to mention package name and variable name like-Math.Sqrt or System.out.
static imports are little different thing than class,methods and variables. The purpose of the static import eliminates the need of the qualifying a static member with the class name. The static import is similar like normal import. We can use the import statement to import classes from packages and use them without providing the qualifying the package name. Similarly,we can use the static import statement to import static members from a class and use them without providing the fully qualified class name.
The syntax is as follows:
import static <packageName>.<subPackageName>.<className>.staticMemberName;
or
import static <packageName>.<subPackageName>.<className>.*;
Before introducing the static import feature,we had to use the static member with the fully qualifying class name.
It is introduced in java in Java 5.0.
Example:


double areaOfCircle=Math.PI*radious*radious

PI is the static member of the Math class.
We can use the static member in the code without providing fully qualified class name. or interface name.static import feature eliminates the redundancy of using the qualified class name with the static member  name and increase the readability of the code.
Use of a Class:


import static java.lang.Math.*;
public class MyMathOperations{
public void circle(double r){
double area=PI*r*r;
System.out.println("The area of the circle is"+area);
}
public static void main(String args[])
{
MyMathOperations mathOps=new MyMathOperations();
mathOps.circle(2.3);
}
}

The output of the code:
$javac MyMathOperations.java
$java -Xmx128M -Xms16M MyMathOperations
The area of the circle is16.619025137490002

Use of a interface:


public interface Student_Grade
{
public static final double StudentsWithAGrade=.5;
public static final double StudentsWithBGrade=.25;
}

import static Student.Student_Deatils.Student_Grade;
Class StudentFinalGrade{
public static void main(String args[]){
double A_grade_Student=StudentsWithAGrade*StudentsWithCurrentGrade;
double B_grade_Student=StudentsWithBGrade*StudentsWithCurrentGrade;
}
}

Similarly if we import java.lang.System.out then we can directly use out.println() instead of System.out.println().

static import statements requires a (packageName) even for classes in the standard package like java.lang. So it is not possible to do a static import from a class which stays in the default package.

Another Example:


public class StaticTest{

public static void main(String []args){
int count=0;
StaticClass x,y;
//x.printCount();
//y.printCount();
// As we have not initialized the x,y jvm will throw an error stating that x,y might not have been initialized. At this point, as we have not called the constructor the increment operator will not get executed and will hold the default value as count=0; the output will be 0,0,0
StaticClass.printCount();
// prints default value of the count as 0
x=new StaticClass();
x.printCount();
//as the constructor is called , count value is increased by 1 so the output value is 1
y=new StaticClass();
y.printCount();
//as the constructor is called , count value is increased by 1 so the output value is 2
}
}
class StaticClass{
static int count;
StaticClass()
{
count++;
}
public static void printCount()
{
System.out.println(count);
}
}

Output of the code:
$javac StaticTest.java
$java -Xmx128M -Xms16M StaticTest
0
1
2


Random numbers are run time constants and are very important in coding. We use Random numbers for Security of the application,Gaming(gambling),Maths etc.
Below are two packages and classes that supports generation of Random numbers.

  1. java.util.Random
  2. java.Math.Random

Using java.util.Random Class:


import java.util.Random
public class myRandomNumber{
public static void main(String[] Args)
{
Random rand=new Random();
for(int i=0;i<10;i++)
{
int randomNumber=rand.nextInt(100);
System.out.println(randomNumber);
}
}

Using java.Math.Random Class: This is useful when we need to generate in a range


public class myRandomNumber{
public static void main(String[] Args)
{
for(int i=0;i<10;i++)
{
int randomNumber=Math.random();
System.out.println(randomNumber);
}
}

Class Object in Java

Say our trainer has asked for a single pager resume. The trainer also has given a set of things in a document(Like -name, technology, experience, contact number, etc).In the real-world, this document is treated as a template or blueprint and each individual when created their resume follows the same rules with different data. In this example, we can say the class is a template of the document and each document created from this template is called an object. The objects will have their own set of data.

The Object class is the root of all classes available in Java. The Object class is the ultimate superclass of all other classes in Java. Because every other class is a subclass of Object,
all of the methods accessible from Object are inherited by every other class. In other words, all objects in Java, including arrays, have access to implementations of the methods in Object.

So it is the parent in the hierarchy. Every class has an Object as a superclass(parent). All objects implement methods of this class. All objects can invoke the public and protected methods of this class.

So, in general, the flow of the class and object creation is something like:
define a class–>create objects form the class—>send message to the objects

The methods of Object provide some basic object functionality.

equals() tests whether two objects have the same value (i.e., not whether two variables refer to the same object, but whether two distinct objects have byte-for-byte equivalence).

The hashCode() method returns a hashcode for an object.

For classes that implement the Cloneable interface, clone() makes a byte-for-byte copy of an Object.

getClass() returns the Class object associated with any Object, and the notify(), notifyAll(), and wait() methods are used for thread synchronization on a given Object.

A number of these Object methods should be overridden by subclasses of Object. Subclasses should provide their definition of the toString() method so that they can be used with the string concatenation operator and with the PrintWriter.println() methods. Defining the toString() method for all objects also helps with debugging.

Classes that contain references to other objects may want to override the equals() and clone() methods (for Cloneable objects) so that they recursively call the equals() and clone() methods of the objects referred to within the original object. Some classes, particularly those that override equals(), may also want to override the hashCode() method to provide an appropriate hashcode to be used when storing instances in a Hashtable data structure.

Classes that allocate system resources other than memory (such as file descriptors or windowing system graphic contexts) should override the finalize() method to release these resources when the object is no longer referred to and is about to be garbage collected.

Although it is possible to create an instance of the Object class, this is rarely done because it is more useful to create specialized objects. However, it is often useful to declare a variable that contains a reference to an Object because such a variable can contain a reference to an object of any other class.

Aristotle was first to begin a study of the concept of type. He spoke about “the class of fishes and the class birds”.The concept that all objects while being unique, are also part of the set of objects that have characteristics and behaviors in common was directly used in the first object-oriented language(Simula-67).

Its fundamental keyword class that introduces a new type into a program(class and type are often used synonymously).

A class is describing “a class of objects”.If we create a class of birds, any object belonging t this class will share these characteristics and behaviors.

The structure of the original Object class is as follows:

public class java.lang.Object{
//Conctuctor
public Object();
// creates a new instance of the Class Object and allocates memory for it.
/Methods:
protected native Object clone() throws CloneNotSupportedException;
protected void finalize() throws Throwable;
public boolean equals(Object obj);
public final native Class getClass();
public native int hasCode();
public final native void notify();
public final native void notifyAll();
public String toString();
public final void wait()throws InterruptedException;;
public final native void wait(long timeOut)throws InterruptedException;
public final void wait(long timeOut,int nanos)throws InterruptedException;
} 

The details of the class structure are given as follows:

public Object();

public Object() constructor creates an instance of the Object class.

public boolean equals(Object obj);

public boolean equals(Object obj) method returns true if the obj parameter refers to the same object as the object this method is associated with. This is equivalent to using the == operator to compare two objects.

Some classes, such as String, override the equals() method to provide a comparison based on the contents of the two objects, rather than on the strict equality of the references. Any subclass can override the equals() method to implement an appropriate comparison, as long as the overriding method satisfies the following rules for an equivalence relation:

  • The method is reflexive : given a reference x, x.equals(x) returns true.
  • The method is symmetric: given references x and y, x.equals(y) returns true if and only if
    y.equals(x) returns true.
  • The method is transitive: given references x, y, and z, if x.equals(y) returns true and y.equals(z) returns true, then x.equals(z) returns true.
  • The method is consistent: given references x and y, multiple invocations of x.equals(y) consistently return true or consistently return false, provided that no information contained by the objects referenced by x or y changes.
  • A comparison with null returns false: given a reference x that is non-null, x.equals(null) returns false.

This method returns true if the objects are equal; false if they are not.

Parameter
obj – The object to be compared with this object.

public final native Class getClass();

public final native Class getClass() method returns the Class object that describes the class of this object. This method is final, so it cannot be overridden by subclasses.

This method returns a reference to the Class object that describes the class of this object.

public native int hashCode();

public native int hashCode() method calculates a hashcode value for this object. The method returns an integer value that should be relatively unique to the object. If the equals() method for the object bases its result on the contents of the object, the hashcode() method should also base its result on the contents.

The hashCode() method is provided for the benefit of hashtables, which store and retrieve elements using key values called hashcodes. The internal placement of a particular piece of data is determined by its hashcode; hashtables are designed to use hashcodes to provide efficient retrieval.

The java.util.Hashtable class provides an implementation of a hashtable that stores values of type Object. Each object is stored in the hashtable based on the hash code of its key objectives. Each object must have the most unique hash code possible. If two objects have the same hash code but they are not equal (as determined by equals()), a Hashtable that stores these two objects may need to spend additional time searching when it is trying to retrieve objects.

The implementation of hashCode() in Object tries to make sure that every object has a
distinct hash code by basing its result on the internal representation of a reference to the object.

Some classes, such as String, override the hashCode() method to produce values based on the contents of individual objects, instead of the objects themselves. In other words, two String objects that contain the same strings have the same hash code. If String did not override the hashCode() method inherited from Object, these two String objects would have different hash code values and it would be impossible to use String objects as keys for hashtables.

Any subclass can override the hashCode() method to implement an appropriate way of producing hash code values, as long as the overriding method satisfies the following rules:

  • If the hashCode() method is called on the same object more than once during the execution of a Java application, it must consistently return the same integer value. The integer does not, however, need to be consistent between Java applications, or from one execution of an application to another execution of the same application.
  • If two objects compare as equal according to their equals() methods, calls to the hashCode() methods for the objects must produce the same result.
  • If two objects compare as not equal according to their equals() methods, calls to the hashCode() methods for the two objects are not required to produce distinct results. However, implementations of hashCode() that produce distinct results for unequal objects may improve the performance of hashtables.

In general, if a subclass overrides the equals() method of Object, it should also override the hashCode() method.

This method returns a relatively unique value that should be the same for all objects that are considered equal.

public final native void notify();

public final native void notifies () method wakes up a thread that is waiting to return from a call to this object’s wait() method. The awakened thread can resume executing as soon as it regains this object’s lock. If more than one thread is waiting, the notify() method arbitrarily awakens just one of the threads.

The notify() method can be called only by a thread that is the current owner of this object’s lock. A thread holds the lock on this object while it is executing a synchronized instance method of the object or executing the body of a synchronized statement that synchronizes on the object.

A thread can also hold the lock for a Class object if it is executing a synchronized static method of that class. This method is final, so it cannot be overridden by subclasses.

public final native void notifyAll();

public final native void notifyAll() method wakes up all the threads that are waiting to return from a call to this object’s wait() method. Each awakened thread can resume executing as soon as it regains this object’s lock.

The notifyAll() method can be called only by a thread that is the current owner of this object’s lock. A thread holds the lock on this object while it is executing a synchronized instance method of the object or executing the body of a synchronized statement that synchronizes on the object.

A thread can also hold the lock for a Class object if it is executing a synchronized static method of that class. This method is final, so it cannot be overridden by subclasses.

public String toString();

public String toString() method returns a generic string representation of this object. The method returns a String that consists of the object’s class name, an “at” sign and the unsigned hexadecimal representation of the value returned by the object’s hashCode() method.

Many classes override the toString() method to provide a string representation that is specific to that type of object. Any subclass can override the toString() method; the overriding method should simply return a String that represents the contents of the object with which it is associated.

This method returns the string representation of this object.

public final native void wait();

public final native void wait() method causes a thread to wait until it is notified by another thread to stop waiting. When wait() is called, the thread releases its lock on this object and waits until another thread notifies it to wake up through a call to either notify() or notifyAll(). After the thread is awakened, it has to regain the lock on this object before it can resume executing.

The wait() method can be called only by a thread that is the current owner of this object’s lock.

A thread holds the lock on this object while it is executing a synchronized instance method of the object or executing the body of a synchronized statement that synchronizes on the object. A thread can also hold the lock for a Class object if it is executing a synchronized static method of that class.

This method is final, so it cannot be overridden by subclasses.

public final native void wait(long millis);

public final native void wait(long millis) method causes a thread to wait until it is notified by another thread to stop waiting or until the specified amount of time has elapsed, whichever comes first. When wait() is called, the thread releases its lock on this object and waits until another thread notifies it to wake up through a call to either notify() or notifyAll().

If the thread is not notified within the specified timeout period, it is automatically awakened when that amount of time has elapsed. If millis is zero, the thread waits indefinitely, just as if wait() had been called without a timeout argument. After the thread is awakened, it has to regain the lock on this object before it can resume executing.

The wait() method can be called only by a thread that is the current owner of this object’s lock. A thread holds the lock on this object while it is executing a synchronized instance method of the object or executing the body of a synchronized statement that synchronizes on the object. A thread can also hold the lock for a Class object if it is executing a synchronized static method of that class.

This method is final, so it cannot be overridden by subclasses.

Parameter
millis – The maximum number of milliseconds to wait.

public final native void wait(long millis, int nanos);

public final native void wait(long millis, int Nanos) method causes a thread to wait until it is notified by another thread to stop waiting or until the specified amount of time has elapsed, whichever comes first.

When wait for () is called, the thread releases its lock on this object and waits until another thread notifies it to wake up through a call to either notify() or notifyAll(). If the thread is not notified within the specified period, it is automatically awakened when that amount of time has elapsed. If millis and Nanos are zero, the thread waits indefinitely, just as if wait() had been called without any arguments. After the thread is awakened, it has to regain the lock on this object before it can resume executing.

The wait() method can be called only by a thread that is the current owner of this object’s lock. A thread holds the lock on this object while it is executing a synchronized instance method of the object or executing the body of a synchronized statement that synchronizes on the object. A thread can also hold the lock for a Class object if it is executing a synchronized static method of that class.

Note that Sun’s reference implementation of Java does not attempt to implement the precision implied by this method. Instead, it rounds to the nearest millisecond (unless millis is 0, in which case it rounds up to 1 millisecond) and calls wait(long).

This method is final, so it cannot be overridden by subclasses.
Parameter
millis – The maximum number of milliseconds to wait.
Nanos – An additional number of nanoseconds to wait.

protected native Object clone();

protected native Object clone() method clones an object. A clone of an object is another object of the same type that has all of its instance variables set to the same values as
the object being cloned. In other words, a clone is an exact copy of the original object.
The clone() method of Object creates a new object that is a clone of this object. No constructor is used in creating the clone. The clone() method only clones an object if the class of that object indicates that its instances can be cloned.

A class indicates that its objects can be cloned by implementing the Cloneable interface.
Although array objects do not implement the Cloneable interface, the clone() method works for arrays. The clone of an array is an array that has the same number of elements as the original array, and each element in the cloned array has the same value as the corresponding element in the original array. Note that if an array element contains an object reference, the cloned array contains a reference to the same object, not a copy of the object.

A subclass of Object can override the clone() method in Object to provide any additional functionality that is needed. For example, if an object contains references to other objects, the clone() method should recursively call the clone() methods of all the referenced objects. An overriding clone() method can throw a CloneNotSupportedException to indicate that particular objects cannot be cloned.

This method returns a clone of this object.

protected void finalize();

protected void finalize() method is called by the garbage collector when it decides that an object can never be referenced again. The method gives an object a chance to perform any cleanup operations that are necessary before it is destroyed by the garbage collector.

The finalize() method of Object does nothing. A subclass overrides the finalize() method to perform any necessary cleanup operations. The overriding method should call super.finalize() as the very last thing it does so that any finalize() method in the superclass is called.
When the garbage collector calls objects to finalize() method, the garbage collector does not immediately destroy the object because the finalize() method might do something that results in a reference to the object.

Thus the garbage collector waits to destroy the object until it can again prove it is safe to do so. The next time the garbage collector decides it is safe to destroy the object, it does so without calling finalize() again.

In other words, the garbage collector never calls the finalize() method more than once for a particular object.

Remember, declaring a variable to hold an object does not create the object. The variable just holds the reference to the object.

A finalize() method can throw any kind of exception. An exception causes the finalize() method to stop running. The garbage collector then catches and ignores the exception, so it has no further effect on a program.

How to create Objects

To create an object, we need to use the new keyword followed by the object’s class or type with optional argument lists in the parenthesis. These arguments are passed to the constructor of the class.

ComplexNumber c=new ComplexNumber(3.0,1.414);

Other ways to create objects

  • We can create a String object by enclosing the characters in a double quote. like-
    String myStr="I love Java";
    // This is the shortcut for String Objects only
    
  • By calling the newInstance() method of a class object. We use them generally in the dynamic loading of classes.
  • Objects can also be created by deserializing them. That is recreating an object that had its state saved via serialization.

An Object:
An instance of a class is called an object. An object in java essentially means a block of memory that contains space to store all the instance variables. Thus, Objects and instances are interchangeable in java.

So creating an object is referred to as the instantiation of an object. In an object-oriented programming language, Objects can communicate between themselves using message. They know which message is for which object and how to interact with it. The message is sent to the object to performing some operation.

The object is having data and behaviors. The linking and bonding between data and operations on these data are known as encapsulation. (so an object is an amalgam of data and code). These data can only be manipulated using these operations. In other words, object’s data values are not directly accessed from outside, instead, they are accessed via the object’s behaviors.

So an object is having some private data values and public behaviors to manipulate the data. Calling a specific method in an object is referred to as sending a message. Objects can be created using the new operator. The new operator creates an object of the specified class and returns the reference of that object.

Construction of an Object


MyClass mc=new MyClass();
//or
MyClass mc;//declare the object
mc=new MyClass();//instantiate the object
 

where My class- is the provider class,
mc is the object reference of the MyClass,
new creates the instance of the provider class,
MyClass() is the constructor of the provider class. This is the default constructor or can be an overloaded constructor. We can create n numbers of objects by using this syntax:

MyClass mc1=new MyClass();
MyClass mc2=new MyClass();
MyClass mc3=new MyClass();
.....
MyClass mcn=new MyClass(); 

Each object holds some amount of memory space and has its copy of the instance variables of its class. It also signifies that any change to the variable of its one object does not affect the variables of another.

We can create two or more references to the same object.

MyClass mc1=new MyClass();
MyClass mc2;
mc2=mc1; 

The user class or object is only bothered as the methods exposed by the provider class. It does not know anything about the implementation of the method. So an object of a provider class implements the details of what a method does. The provider class only knows how the method is implemented. Now to call a method to provide by the provider class, we need to use the dot operator to gain access to the provider class’s field if they are public.
like

mc.setFirstName("Joghn");
//or
String name=mc.getFirstName(); 

All variables of an object must be assigned some value before they are used. From outside of the class we can not assign/access the variables directly as most of the cases they are private. To do this we need to account object and a dot (.) operator.

objectName.variableName=value;
objectName.methodName(paramlist) 

if the instance variables are public then we can follow this approach:

class MyClass{
public int x;
public int y;
}
class Test{
MyClass mc1=new MyClass();
mc1.x=10;
mc1.y=15;
}

if the instance variables are private then we can follow this approach:


class MyClass{
private int x;
private int y;
//we can define an argumented constructor
public MyClass(int x,int y)
this.x=x;
this.y=y;
}
//or we can define some  getter or setter method
public void setValues(int x,int y)
this.x=x;
this.y=y;
}
class Test{
MyClass mc1=new MyClass(10,15);
//or 
MyClass mc1=new MyClass();
mc1.setValues(10,15);
}
 

for function with a payload or argument to understand the process better, let’s start from right to left. we pass an argument called Joghn(string) to the method setFirstName.And call this method on the instance of the provider class -MyClass using a. (dot) operator to identify the specific object (stored in the memory) for this method call. This is how we use an object of the provider class. What happens internally:

once we created an object using a new operator, the required arguments need to be passed to the constructor. The JRE allocates sufficient memory to store the fields of the object and initializes its state. When initialization is done, the JRE returns a reference to the new object. So we can say the constructor returns an object reference to the object stored in memory. The default constructor takes no arguments and contains no code. It is provided automatically by the compiler if the developer has not provided any constructor in the class.

But this is theoretical, how to execute the object?
Well, we will execute the object of a provider class by inserting them into a container class and use the main method to trigger the execution.
Most Java applications may have any number of classes but they will surely have a single main that should trigger the execution.
An Example


public class MyContainerClass{
public static void main(String args[])
{
MyClass myObj=new MyClass();
myObj.setFirstName("Xavior");
}
}
 

To create an instance of class MyClass, We need to create a container class, then we can create the instance. The main is the starting function to kick of execution.

Guidelines for object creation:

  • An object by convention starts with a small letter like obj.
  • The object must be able to perform that method call.

The data member of an object
Each object keeps its storage for its data members, the data members are not shared among objects. We may have any number of classes, but they will have no impact on our program until and unless we create an object from that class.


class Myclass{
int i;
float f;
boolean b;
}
//this class does not anything unless we create an object using new operator
Myclass mc=new Myclass();
 

We can assign values to the data members by the object name(handle) by a dot(.) operator
like-


mc.i=10;
mc.f=1.0f;
mc.b=false;
 

our object may also contain other objects which we would like to call a function like-
System.out.println(“Hello Java”);
It means that select out from class System and call println() method.
Scope of Objects
Java objects do not have the same lifetimes as primitives. When we create a java object using new, it hangs around past the end of the scope.


{
String myStr=new String("java");
}
//end of the scope of myStr
 

The handle myStr vanishes at the end of the scope. However, the string object myStr was pointing to, is still occupying memory. In the above code, there is no way to access the object because it is out of scope post this code line.

Its turns out that because objects created with new operator stay around, as long as we want them. In Java, it makes sure the objects are available when they are needed. Once objects created they fill up memory that halts the program.

Java has a garbage collector, which is a process running in the background(low priority execution and does not interfere with program execution). The garbage collector looks at all the objects created by new and figures out which ones are not being referenced any further. Then it releases the memory for those objects.

This memory can be used by new objects. Thus a java coder never has to worry about reclaiming memory. This eliminates the problem of memory leakage where the programmer forgets to release memory.

How to Access the Objects?

Java objects are always accessed by their references. Java internally performs any necessary dereferencing.  A dot (.) operator provides a mechanism to gain access to the object.

double magnitude=e.magnitude();

Let’s see how Object is used and how the assignment happens:

public class MyValue {
int x,y;
void getValue(int a, int b)
{
x=a;
y=b;
}
}

Lets us create our test class to check how the object invocation happens


public class MyTestClass {
	static double distance;
	public static void main(String[] args) {
		// TODO Auto-generated method stub
	MyValue p1=new MyValue();
	MyValue p2 = p1;
	MyValue p3 =new MyValue();
	MyValue p4 =new MyValue();
	
	p1.getValue(5,10);
	p2.getValue(15,20);
	p3.getValue(20,30);
	p4.getValue(30,40);
	
	System.out.println(p1.x);
	System.out.println(p1.y);
	
	p1=null;
	
	System.out.println(p2.x);
	System.out.println(p2.y);
	
    p2=null;
    
    int dx=p3.x-p4.x;
    int dy=p3.y-p4.y;
    
    distance=Math.sqrt(dx*dx+dy*dy);
    System.out.println(distance);
	}
}

 

codeObjectsHeap values
MyValue p1=new MyValue();One new object is createdthe initial values 0,0
MyValue p2 = p1;another object p2 gets created but both p1 and p2 are pointing to same objectthe initial values 0,0
p1.getValue(5,10);since p1 and p2 are referring same object, the x=5 and y=10
both p1.x=p2.x=5
and p2.y=p2.y=10
p2.getValue(15,20);Now, p2 is updating the value of the object. Since p2 and p1
are pointing to the same object, p1 also gets updated.
both p1.x=p2.x=15
and p2.y=p2.y=20
MyValue p3 =new MyValue();
MyValue p4 =new MyValue();
p3 and p4 objects are created but they are different.
p3.getValue(20,30);p3.x=20
and p3.y=30
p4.getValue(30,40);p4.x=30
and p4.y=40
System.out.println(p1.x);
System.out.println(p1.y);
Prints the values they are containing
p1=null;p1 becomes null hence it is ready for garbage collected
System.out.println(p2.x);
System.out.println(p2.y);
Prints the values they are containing
p2=null;p2 becomes null hence it is ready for garbage collected

Abstract Class Number in Java

The Abstract class Number is the superclass for all numerical primitive types (for all of the classes that provide
object wrappers for primitive numeric values)like- Byte, Short, Integer, Long, Float, Double.

Wrapping a primitive value is useful when you need to treat such a value as an object. For example, there are a number of utility methods that take a reference to an Object as one of their arguments. We cannot specify a primitive value for one of these arguments, but we can provide a reference to an object that encapsulates the primitive value.

This class defines the conversion functions that these classes implement. The Number class defines six methods that must be implemented by its subclasses: byteValue(), shortValue(), intValue(), longValue(), floatValue(), and doubleValue(). This means that a Number object can be fetched as a byte, short, int, long, float, or double value,
without regard to its actual class.

The structure of Number class is as follows:


public abstract Class java.lang.Number extends java.lang.Object implements java.io.Serializable{
//Constructor
public Number();
//Methods:
public abstract byte byteValue();
public abstract double doubleValue();
public abstract float floatValue();
public abstract int intValue();
public abstract long longValue();
public abstract short shortValue();
}
 

The details of the class structure are given as follows:

public abstract byte byteValue();

public abstract byte byteValue() method returns the value of this object as a byte. If the data type of the value is not a byte, rounding may occur.

This method returns the value of this object as a byte.

public abstract double doubleValue();

public abstract double doubleValue() method returns the value of this object as a double. If the data type of the value is not double, rounding may occur.

This method returns the value of this object as a double.

public abstract float floatValue();

public abstract float floatValue() method returns the value of this object as a float. If the data type of the value is not float, rounding may occur.

This method returns the value of this object as a float.

public abstract int intValue();

public abstract int intValue() method returns the value of this object as an int. If the type of value is not an int, rounding may occur.

This method returns the value of this object as an int.

public abstract long longValue();

public abstract long longValue() method returns the value of this object as a long. If the type of value is not a long, rounding may occur.

This method returns the value of this object as a long.

public abstract short shortValue();

public abstract short shortValue() method returns the value of this object as a short. If the type of value is not a short, rounding may occur.

This method returns the value of this object as a short.
Apart from these methods the Number class also has inherited methods from class- Object. They are as follows:

  • clone()
  • finalize()
  • hashCode()
  • notifyAll()
  • wait()
  • wait(long, int)
  • equals(Object)
  • getClass()
  • notify()
  • toString()
  • wait(long)

Class “Class” in Java

Say we want to design a beautiful city. For that, we need to chalk out a plan for roads, houses, shops, etc in a paper. Then we will design each of these individually, say a house. The blueprint of the house will say how many doors will be there, how many windows, how many floors, etc.

Each of these houses will have its owner details when they are built and distributed. So in the sense, the houses will look alike but the details of each house like the owner, how many occupants will be there in the house, will vary. Even the interior may vary from one house to another. But the base of creating a house will be the same.

This is the same for roads, the design will be the same but the name, locality, and length will be different. It is similar to create a beautiful application using java. As a pure object-oriented language, everything in Java should be inside a class.Java classes are the blueprint or master plan just like a master plan of a house.we can create any number of houses from this master plan. The master plan is called class and the individual houses created from this master plan is called an object.

This is a very interesting Class called Class in java. An instance of the Class Class only represents classes and interfaces in the java applications. There are no member elements and public constructors available for Class Class.

Instances of the Class class are used as run-time descriptions of all Java data types, both reference types, and primitive types. It also supports the Reflection API.

Class objects are constructed automatically by JVM when Classes are loaded into JVM and by the help of the method defineClass()[it stays in ClassLoader Class]

This class represents a Java class or interface, or any Java type. There is one Class object for each class that is loaded into the Java Virtual Machine, there are special Class objects that represent the Java primitive types.

The TYPE constants defined by Boolean, Integer, and the other primitive “wrapper classes” hold these special Class objects. Array types are also represented by Class objects.

There is no constructor for this class. We can obtain a Class object by calling the getClass() method of any instance of the desired class. A Class object may also be referred to by appending .class to the name of a class.

A class can be dynamically loaded bypassing its fully-qualified name (i.e., package name plus class name) to the static Class.forName() method. This method loads the named class, if it is not already loaded, into the Java interpreter, and returns a Class object for it.

The newInstance() method creates an instance of a given class–this allows you to create instances of dynamically loaded classes for which we cannot use the new keyword.

Classes provide a convenient method for packing together a group of logically related data items and functions that work with them. A class is given a name(called Identifier) to distinguish from other classes of the application.

The class includes physical components called member elements and several methods for operations. It is a datatype where the class creator will define how the new type of objects looks like. The linking and bonding between data and operations on these data are known as encapsulation. In the context of behavior, in approach, parameters to the behavior and return type should be primitive data type or a class object.

A class is a user-defined data type with a template that defines the properties. Once the class type has been defined, we can create variables of that type using-declaration that is similar to the basic type declarations that are similar to the basic type declaration. These variables are called an instance of the class. (They are objects of that class)

Note This method only works when the target class has a no-argument constructor. See newInstance() in java.lang.reflect.Constructor for a more powerful way to instantiate dynamically loaded classes.

  • getName() returns the name of the class.
  • getSuperclass() returns its superclass.
  • isInterface() tests whether the Class object represents an interface?
  • getInterfaces() returns an array of the interfaces that this class implements.
  • isPrimitive() method tests if the Class object describes a primitive type or not.
  • isArray() tests if the object is an array.

The various other get and is methods return other information about the represented class or interface type  with Java Reflection API ( java.lang.reflect, java.lang.reflect.Field, java.lang.reflect.Method, and java.lang.reflect.Constructor objects.)

Below is the structure of Class -Class

public final Class java.lang.Class extends java.lang.Object implements java.io.Serializable{
// No Constructor
// Class Methods
public static native Class forName(String className) throws ClassNotFoundException;
// Public Instance Methods
public native ClassLoader getClassLoader();
public Class[] getClasses();
public native Class getComponentType();
public Constructor getConstructor(Class[] parameterTypes) throws NoSuchMethodException, SecurityException;
public Constructor[] getConstructors() throws SecurityException;
public Class[] getDeclaredClasses() throws SecurityException;
public Constructor getDeclaredConstructor(Class[] parameterTypes) throws NoSuchMethodException, SecurityException;
public Constructor[] getDeclaredConstructors() throws SecurityException;
public Field getDeclaredField(String name) throws NoSuchFieldException,SecurityException;
public Field[] getDeclaredFields() throws SecurityException;
public Method getDeclaredMethod(String name, Class[] parameterTypes) throws NoSuchMethodException, SecurityException;
public Method[] getDeclaredMethods() throws SecurityException;
public Class getDeclaringClass();
public Field getField(String name) throws NoSuchFieldException,SecurityException;
public Field[] getFields() throws SecurityException;
public native Class[] getInterfaces();
public Method getMethod(String name, Class[] parameterTypes) throws NoSuchMethodException, SecurityException;
public Method[] getMethods() throws SecurityException;
public native int getModifiers();
public native String getName();
public URL getResource(String name);
public InputStream getResourceAsStream(String name);
public native Object[] getSigners();
public native Class getSuperclass();
public native boolean isArray();
public native boolean isAssignableFrom(Class cls);
public native boolean isInstance(Object obj);
public native boolean isInterface();
public native boolean isPrimitive();
public native Object newInstance() throws InstantiationException, IllegalAccessException;
public String toString(); // Overrides Object
} 

The details of the method described are as follows:

public static native Class forName(String className) throws ClassNotFoundException;

public static native Class forName(String className) throws ClassNotFoundException method dynamically loads a class if it has not already been loaded. The method returns a Class object that describes the named class.

The most common use of forName() is for loading classes on the fly when an application wants to use classes it wasn’t built with. For example, a web browser uses this technique. When a browser needs to load an applet, the browser calls Class.forName() for the applet.

The method loads the class if it has not already been loaded and returns the Class object that encapsulates the class. The browser then creates an instance of the applet by calling the class object’s newInstance() method.

When a class is loaded using a ClassLoader object, any classes loaded at the instigation of that class are also loaded using the same ClassLoader object. This method implements a security policy by trying to find a ClassLoader object to load the named class.

The method searches the stack for the most recently invoked method associated with a class that was loaded using a ClassLoader object. If such a class is found, the ClassLoader object associated with that class is used.

This method returns a Class object that describes the named class.
Parameter
className-Name of a class qualified by the name of its package. If the class is defined inside of another class, all dots(.) that separate the top-level class name from the class to load must be changed to dollar signs ($) for the name to be recognized.

public native ClassLoader getClassLoader();

public native ClassLoader getClassLoader() method returns the ClassLoader object that was used to load this class. If this class was not loaded with a ClassLoader, null is returned.

This method is useful for making sure that a class gets loaded with the same class loader as was used for loading
this Class object.
This method returns the ClassLoader object used to load this class or null if this class was not loaded with a ClassLoader.

public Class[] getClasses();

public Class[] getClasses() method returns an array of Class objects(If this Class object represents a reference type) that lists all of the public classes and interfaces that are members of this class or interface. The list includes public classes and interfaces that are inherited from superclasses and that are defined by this class or interface. If there are no public member classes or interfaces, or if this Class represents a primitive type, the method returns an array of length 0.

This method always returns an array of length 0, no matter how many public member classes this class or interface declares.

This method returns an array of Class objects that contains the public classes and interfaces that are members of this class.

public native Class getComponentType();

public native Class getComponentType() method returns a Class object(If this Class object represents an array type) that describes the component type of the array. If this Class does not represent an array type, the method returns null.

This method returns a  Class object that describes the component type of this class if it is an array type.

public Constructor getConstructor(Class[] parameterTypes) throws NoSuchMethodException, SecurityException;

public Constructor getConstructor(Class[] parameterTypes) throws NoSuchMethodException, SecurityException method returns a Constructor object(If this Class object represents a class) that reflects the specified public constructor of this class.

The constructor is located by searching all of the constructors of the class for a public constructor that has the same formal parameters as specified. If this Class does not represent a class, the method returns null.

This method returns a Constructor object that reflects the specified public constructor of this class.

Parameter
parameterTypes[]-An array of Class objects that describes the parameter types, in declared order, of the constructor.

public Constructor[] getConstructors() throws SecurityException;

public Constructor[] getConstructors() throws SecurityException method returns an array of Constructor objects(If this Class object represents a class,) that reflect the public constructors of this class. If there are no public constructors, or if this Class does not represent a class, the method returns an array of length 0.
This method returns an array of Constructor objects that reflect the public constructors of this class.

public Class[] getDeclaredClasses() throws SecurityException;

public Class[] getDeclaredClasses() throws SecurityException method returns an array of Class objects(If this Class object represents a class) that lists all of the classes and interfaces that are members of this class or interface. The list includes public, protected, default access, and private classes and interfaces that are defined by this class or interface, but it excludes classes and interfaces inherited from superclasses. If there are no such member classes or interfaces, or if this Class represents a primitive type, the method returns an array of length 0.

This method always returns an array of length 0, no matter how many member classes this class or interface declares.
This method returns an array of Class objects that contains all of the declared classes and interfaces that are members of this class.

public Constructor getDeclaredConstructor(Class[] parameterTypes) throws NoSuchMethodException, SecurityException;

public Constructor getDeclaredConstructor(Class[] parameterTypes) throws NoSuchMethodException, SecurityException method returns a Constructor object(If this Class object represents a class) that reflects the specified declared constructor of this class.

The constructor is located by searching all of the constructors of the class for public, protected, default access, or private constructor that has the same formal parameters as specified. If this Class does not represent a class, the method returns null.
This method returns a Constructor object that reflects the specified declared constructor of this class.

Parameter
parameterTypes[]-An array of Class objects that describes the parameter types, in declared order, of the constructor.

public Constructor[] getDeclaredConstructors() throws SecurityException;

public Constructor[] getDeclaredConstructors() throws SecurityException method returns an array of Constructor objects(If this Class object represents a class) that reflect the public, protected, default access, and private constructors of this class. If there are no declared constructors, or if this Class does not represent a class, the method returns an array of length 0.

This method returns an array of Constructor objects that reflect the declared constructors of this class.

public Field getDeclaredField(String name) throws NoSuchFieldException,SecurityException;

public Field getDeclaredField(String name) throws NoSuchFieldException, SecurityException method returns a Field object(If this Class object represents a class or interface) that reflects the specified declared field of this class. The field is located by searching all of the fields of the class (but not inherited fields) for public, protected, default access, or private field that has the specified simple name. If this Class does not represent a class or interface, the method returns null.

This method returns a Field object that reflects the specified declared field of this class.
Parameter
name-The simple name of the field.

public Field[] getDeclaredFields() throws SecurityException;

public Field[] getDeclaredFields() throws SecurityException method returns an array of Field objects(If this Class object represents a class or interface) that reflect the public, protected, default access, and private fields declared by this class, but excludes inherited fields.

If there are no declared fields, or if this Class does not represent a class or interface, the method returns an array of length 0.

This method does not reflect the implicit length field for array types. The methods of the class Array should be used to manipulate array types.

This method returns an array of Field objects that reflect the declared fields of this class.

public Method getDeclaredMethod(String name, Class[] parameterTypes) throws NoSuchMethodException, SecurityException;

public Method getDeclaredMethod(String name, Class[] parameterTypes) throws NoSuchMethodException, SecurityException method returns a Method object(If this Class object represents a class or interface) that reflects the specified declared method of this class.

The method is located by searching all of the methods of the class (but not inherited methods) for the public, protected, default access, or private method that has the specified simple name and the same formal parameters as specified. If this Class does not represent a class or interface, the method returns null.

This method returns an array of Class objects that describes the parameter types, in declared order, of the method.
Parameter
name-The simple name of the method.

public Method[] getDeclaredMethods() throws SecurityException;

public Method[] getDeclaredMethods() throws SecurityException method returns an array of Method objects(If this Class object represents a class or interface) that reflect the public, protected, default access, and private methods declared by this class but excludes inherited methods. If there are no declared methods, or if this Class does not represent a class or interface, the method returns an array of length 0.

This method returns an array of Method objects that reflect the declared methods of this class.

public Class getDeclaringClass();

public Class getDeclaringClass() method returns a Class object(If this Class object represents a class or interface that is a member of another class or interface) that describes the declaring class or interface. If this class or interface is not a member of another class or interface, or if it represents a primitive type, the method returns null.

This method returns a Class object that represents the declaring class if this class is a member of another class.

public Field getField(String name) throws NoSuchFieldException,SecurityException;

public Field getField(String name) throws NoSuchFieldException, SecurityException method returns a Field object(If this Class object represents a class or interface) that reflects the specified public field of this class. The field is located by searching all of the fields of the class, including any inherited fields, for a public field that has the specified simple name. If this Class does not represent a class or interface, the method returns null.

This method returns a Field object that reflects the specified public field of this class.
Parameter
name-The simple name of the field.

public Field[] getFields() throws SecurityException;

public Field[] getFields() throws SecurityException method returns an array of Field objects(If this Class object represents a class or interface) that reflect the public fields declared by this class and any inherited public fields. If there are no public fields, or if this Class does not represent a class or interface, the method returns an array of length 0.

This method does not reflect the implicit length field for array types. The methods of the class Array should be used to manipulate array types.

This method returns an array of Field objects that reflect the public fields of this class.

public native Class[] getInterfaces();

public native Class[] getInterfaces() method returns an array that refers to all of the interfaces that the class implements (If the Class object represents a class). The order of the interfaces referred to in the array is the same as the order in the class declaration’s implements clause. If the class does not implement any interfaces, the length of the returned array is 0.

If the object represents an interface, this method returns an array that refers to all of the interfaces that this interface extends. The interfaces occur in the order they appear in the interface declaration’s extends clause. If the interface does not extend any interfaces, the length of the returned array is 0.

If the object represents a primitive or array type, the method returns an array of length 0.

This method returns an array of the interfaces implemented by this class or extended by this interface.

public Method getMethod(String name, Class[] parameterTypes) throws NoSuchMethodException, SecurityException;

public Method getMethod(String name, Class[] parameterTypes) throws NoSuchMethodException, SecurityException method returns a Method object(If this Class object represents a class or interface) that reflects the specified public method of this class.

The method is located by searching all of the methods of the class, including any inherited methods, for a public method that has the specified simple name and the same formal parameters as specified. If this Class does not represent a class or interface, the method returns null.

This method returns a Method object that reflects the specified public method of this class.
Parameter
name-The simple name of the method.
a parameterTypes-An array of Class objects that describes the parameter types, in declared order, of the method

public Method[] getMethods() throws SecurityException;

public Method[] getMethods() throws SecurityException method returns an array of Method objects(If this Class object represents a class or interface) that reflect the public methods declared by this class and any inherited public methods. If there are no public methods or if this Class doesn’t represent a class or interface, the method returns an array of length 0.

This method returns an array of Method objects that reflect the public methods of this class.

public native int getModifiers();

public native int getModifiers() method returns an integer value that represents the modifiers used to declare the class or interface If this Class object represents a class or interface. The Modifier class should be used to decode the returned value.

This method returns an integer that represents the modifier keywords used to declare this class.

public native String getName();

public native String getName() method returns the fully qualified name of the type represented by this Class object.

If the object represents the class of an array, the method returns a String that contains as many left square brackets as there are dimensions in the array, followed by a code that indicates the type of element contained in the base array. Consider the following:

(new int [5][6][2]).getClass().getName()

This code returns “[[[I”. The codes used to indicate the element type are as follows:

CodeType
[array
Bbyte
Cchar
ddouble
Ffloat
Iint
Jlong
Lfully_qualified_class_name class or interface
Sshort
Zboolean

This method returns the fully qualified name of this class or interface.

public URL getResource(String name);

public URL getResource(String name) method finds a resource with the given name for this Class object and returns a URL object that is connected to the resource.

The rules for searching for a resource associated with a class are implemented by the ClassLoader for the class; this method simply calls the getResource() method of the ClassLoader.

If this class does not have a ClassLoader (i.e., it is a system class), the method calls the ClassLoader.getSystemResource() method.

This method returns a URL object that is connected to the specified resource or null if the resource cannot be found.
Parameter
name-A A resource name.

public InputStream getResourceAsStream(String name);

public InputStream getResourceAsStream(String name) method finds a resource with the given name for this Class object and returns an InputStream object that is connected to the resource. The rules for searching for a resource associated with a class are implemented by the ClassLoader for the class; this method simply calls the getResourceAsStream() method of the ClassLoader. If this class does not have a ClassLoader (i.e., it is a system class), the method calls the ClassLoader.getSystemResourceAsStream() method.

This method returns an InputStream object that is connected to the specified resource or null if the resource cannot be found.
Parameter
name-A A resource name.

public native Object[] getSigners();

public native Object[] designersgetSigners() method returns an array of objects that represents the digital signatures for this class.

This method returns an array of Objects that represents the signers of this class.

public native Class getSuperclass();

public native Class getSuperclass() method returns the Class object(If the Class object represents a class other than Object) that represents its superclass. If the object represents an interface, the Object class, or a primitive type, the method returns null.

This method returns the superclass of this class or null if there is no superclass.

public native boolean isArray();

public native boolean isArray() method checks if the object is an array.

This method returns true if this object describes an array type; otherwise false

public native boolean isAssignableFrom(Class cls);

public native boolean isAssignableFrom(Class cls) method determines whether or not the type represented by class is assignable to the type of this class. If this class represents a class, this class must be the same as class or a superclass of class. If this class represents an interface, this class must be the same as cls or a superinterface of class. If this class represents a  primitive type, this class must be the same as cls.

This method returns true if the type represented by class is assignable to the type of this class: otherwise false.

Parameter
cls-A Class object to be tested.

public native boolean isInstance(Object obj);

public native boolean is the Instance(Object obj) method determines whether or not the object represented by obj can be cast to the type of this class object without causing a ClassCastException. This method is the dynamic equivalent of the instanceof operator.

This method returns true if obj can be cast to the reference type specified by this class; otherwise false.
Parameter
obj-An Object to be tested.

public native boolean isInterface();

public native boolean isInterface() method checks if the given object is an interface.
This method returns true if this object describes an interface; otherwise false

public native boolean isPrimitive();

public native boolean isPrimitive() method checks if the given object is a primitive type.
This method returns true if this object describes a primitive type; otherwise false.

public native Object newInstance() throws InstantiationException, IllegalAccessException;

public native Object newInstance() throws InstantiationException, IllegalAccessException method creates a new instance of this class by performing these steps:

  • It creates a new object of the class represented by the Class object.
  • It calls the constructor for the class that takes no arguments.
  • It returns a reference to the initialized object.

The newInstance() method is useful for creating an instance of a class that has been dynamically loaded using the forName() method.

The reference returned by this method is usually cast to the type of object that is instantiated.

The newInstance() method can throw objects that are not instances of the classes it is declared to throw. If the constructor invoked by newInstance() throws an exception, the exception is thrown by newInstance() regardless of the class of the object.

This method returns a reference to a new instance of this class.
Parameter

public String toString(); // Overrides Object

public String toString(); method returns a string representation of the Class object.
This method returns a String that contains the name of the class with either ‘class’ or ‘interface’ prepended as appropriate.
Apart from these Compiler class also has inherited methods from class- Object. They are as follows:

  • clone()
  • finalize()
  • hashCode()
  • notifyAll()
  • wait()
  • wait(long, int)
  • equals(Object)
  • getClass()
  • notify()
  • toString()
  • wait(long)

The basic structure of the class is :

class className[extends superclass][implements someOtherclass]
{
[field declaration]
[methods declaration]
} 

Filed declaration
Data encapsulated in a class by placing data fields inside the body of the class definition. These variables are called instance variables as they are created whenever an object of the class is instantiated. The declaration is the same as local variables.


class Rectangle{
int length;
int width;
}
 

Once they are declared, there is no space allocated to them.
Design of a class
While designing qualifier “-” signifies private and “+” signifies public.
like
-firstName=>String but private
+setFirstName(firstName)=> String but public

Collectively the variables and methods of a class are often referred to as members or fields of a class.
The transformation from a conceptual class diagram to class code is depicted here:

Class DiagramClass Code
MyClass———————–>public class MyClass
-firstName:String———————–>private firstName
+setFirstName(firstName:String)———————–>public  void setFirstName(String firstName)
{
this.firstName=firstName;
}
+getFirstName():String———————–>public String getFirstName()
{
return firstName;
}
so on….

the constructor is omitted here, but in reality, we will have a constructor for a class.
Below is the general formula for a class:


<<Access specifier>> class className [extends SuperClass Name] implements interface1,interface2,....interfaceN{
//member elements mostly private
[Deceleration of member elements]
//methods mostly public
[Deceleration of methods]
}

Method declaration:
A class with only data fields has no life as there are no methods that operate on that data. The objects created by such a class can not respond to any message. So it is necessary to design methods. Methods are declared inside the body of the class but immediately after the declaration of the instance variables.


[access modifier][specifier][return type]methodname(parameterList)
{
//method body
}
 

The four basic parts of the valid method are as follows:

  1. The name of the method(method name)
  2. The return type of the method
  3. the list of parameters
  4. the body of the method.

We can pass an object and some primitive data type to a method in the form of an argument and can return an object or primitive data type.
like setValue(int xyz);
anything inside the first bracket is considered as payload to the function. It is a mechanism by which we either pass the value of data or reference to the object. Certainly, a class has a function with an empty payload. Like
setValue();


public class MyClass{
private String firstName();
public void setFirstName(String firstName)
{
this.firstName=firstName;
}
public String getFirstName(){
return firstName;
}
}
 

In the above statement, MyClass is an example of the structure of the class having one variable called firstName.If the constructor of the class MyClass() is called, the variable is set to the default value. In case, the constructor sets the value, it will be overridden.
Therefore every member variable will have a setter and a getter method so that the objects created from the class pass and change the values.
like setXXX(datatype value);//value passed
getXXX(){return datatype;}//method with no payload

The return type could be inbuilt data types or a class object. A method may not have any valid return value, in such cases, the return type will be void. The argument list is enclosed with parentheses. The list contains variables in a list separated by a comma. A method may also take no input in such case the argument list is empty parentheses.”()”.
like:
getValue();

Most of the time, when we use classes, we will have many methods and variables within the class. Instance variables and methods in classes are accessible by all methods in the class but a method can not access variables declared in another method.


class abc{
int x;
//legal
void method1()
{
x=10;
int y=x;
}
void method2()
{
int z;
x=5;
z=10;
//illegal as y is part of method1
y=1;
}

The data member of a class
The data member is the thing we want to communicate via its handle. It can be of any type(primitive) which is not handled. It can be a handle to an object(it must be initialized to connect it to an actual object using new in the constructor). If it is a primitive data type, we can initialize it directly at the point of definition in the class.

Guidelines for class creation:

    • By convention, a class name starts with a capital letter. like PrintStream
    • class is a keyword and declares that a new class definition as follows.
    • the class definition in Java starts with an opening brace (“{“)  and ends with a closing brace.(“}”).
    • the class contains two types of elements-Data members called fields and member functions called methods.
  • Methods in java can be created as a part of the Class. A method can only be called for an object. Except static methods can be called for the class without an object.

Java being a single-rooted language, all classes are a child of Object class.


public class MyClass{..}
//is equivalent to 
public class MyClass extends java.lang.Object{...}
 

Semantically java.lang.Object class is an abstract class but syntactically it is not declared as abstract. As it is a concrete class we can create an object of the Object class.
so


Object o=new Object() //is legal but not sure where to use its methods
a.methods();
 

Methods, arguments and return value:
Initially, a function is termed as a named subroutine. The method is described as “a way to do something”.Another way, methods in java determine the messages, an object can receive. the structure of the method is as follows:


returnType method Name(argumentList)
{
//method body
//return statement
}
 

returnType is the type of the value that pops out of the method after we call it. methodName is the meaningful name we can imagine and identifies the method. The argument list is the list of the type of arguments and names for the information we want to pass to the method. If we try to call the wrong method for an object, we will get a compile-time error. The generic syntax for calling a method:
objectName(handle).(dot).methodName() with argument or without any argument.
If the class on whose handle we call the method (), has the method written, we will be able to perform the method call.
The return value must compatible with the return value defined in the method signature.
The call of the method is commonly referred to as sending the message to the object.

How to get a Class object for a particular data type?

Below are the ways by which we can get a Class object for a particular datatype.

  • By calling the object’s getClass()method. Every class inherits this method from the Object class.
  • Using the new class literal syntax. A class literal is simply the name of a type (a class name or a primitive type name) followed by a period and the class keyword.
Class str = String.class;
Class intVal = int.class;
Class vectorVal = java.util.Vector.class;
  • Using the forName() class method of Class.
Class vectorVal = Class.forName("java.util.Vector");
  • Using newInstance() method of a Class object, if the class has a constructor that takes no arguments.

Class Boolean in Java

This class allows the coder to define primitive type Boolean for an object. An object of type boolean can contain a single field whose type is boolean. The Boolean class provides an immutable object wrapper for a boolean value. It is very useful when we need to treat the boolean value as an object. The Boolean class supports to implement Reflection API and class literals.

Note that TRUE and FALSE constants are Boolean objects; they are not the same as true and false boolean values.

booleanValue() returns the boolean value of a Boolean object.

The class method getBoolean() retrieves the boolean value of a named property from the system property list.

The class method valueOf() parses a string and returns the Boolean value it represents.

This is useful when we need to treat a boolean value as an object. For example, there are a number of utility methods that take a reference to an Object as one of their arguments. We cannot specify a boolean value for one of these arguments, but we can provide a reference to a Boolean object that encapsulates the boolean value. The Boolean class supports the Reflection API and class literals.

Below is the Structure of Boolean class:

public final class java.lang.Booean extends java.lang.Object implements java.io.Serializable
{
//Member elements of the Boolean class
public final static Boolean FALSE;
//A constant Boolean object whose's value is FALSE
public final static Boolean TRUE;
//A constant Boolean object whose's value is TRUE
public final static Class TYPE; 
//The Class object that represents the type boolean. It is always true if Boolean.TYPE==boolean.class.
//constructors:
public Boolean(boolean value);// creates a Boolean object initialized with the value provided as an argument. So converts a boolean value to the Boolean object. 
public Boolean(String Str);
//Creates a Boolean object initialize with the value TRUE if the String argument provided is not null and is equals to ignore case to the String //"True", Otherwise creates a boolean object initialized as false.
//Methods:
public boolean booleanValue();//This method returns the boolean value of an object contained.
public boolean equals(Object obj);//This method returns true if the obj is an instance of Boolean and it contains the same value as the object this method is associated with. it returns false if they do not contain the same value. 
public static boolean getBoolean(Sting str);//this method returns the boolean value of the named system property.
public int hashcode();//Returns the hashcode based on the boolean value of the object.
public String toString();//This method returns "true" if the value of the object is true. Otherwise, it returns false. Basically a string representation of the object.
public static Boolean valueOf(String s);//This method returns a Boolean object with the value TRUE if the String argument provided is not null and is equals to ignore case to the String //"True", Otherwise returns a boolean object whose value is false.
} 

Apart from these this class also has the below-inherited methods from Class Object :
From Object class

  • clone()
  • getClass()
  • equals(Object obj);
  • finalize()
  • notify()
  • notifyAll()
  • wait()
  • wait(long timeput)
  • wait(long timeout,int nanos)

Class Stack in Java

The Stack class extends the Vector class. In addition to inherited methods from vector class, the Stack class contains some more extra methods. The Stack class represents a container that implements Last In First Out (LIFO) or First In Last Out(FILO) structure of Objects in Java.

That is whenever we push some object to the stack, the last is the first item we can pop out. Like other containers, we can push and pop objects. So we must cast to the appropriate type when we pop an object from Stack.

push() puts an object on the top of the stack.pop() removes and returns the top object from the stack. peek() returns the top object without removing it.

The structure of the Stack class is given below:

public class java.util.Stack extends Java.util.Vector{
//constructor
public stack();
//creates a stack with no elements in it.
//Methods
public boolean empty();//returns true if the stack is empty.
public synchronized Object peek();//returns the element at the top of the stack.
public synchronized Object pop();//removes the top element of the Stack and returns the element that is removed.
public Object push(Object item);//adds the item to the top of the stack.
public synchronized int search(Object itemToSearch);  
}

The details of the class structure are given as follows:

public boolean empty();

public boolean empty() method returns a boolean value that indicates whether or not the Stack is empty.

This method returns true if there are no objects on the Stack; false otherwise.

public synchronized Object peek();

public synchronized Object peek() method returns a reference to the object on the top of this Stack without removing it.

This method returns a reference to the object that is returned by the next call to pop().

public synchronized Object pop();

public synchronized Object pop() method returns the object on top of this Stack.

This method returns the object on top of this Stack.

public Object push(Object item);

public Object push(Object item) method places the object on the top of this Stack.

This method returns the object just pushed.

Parameter
item – The object to be added to the top of the stack.

public synchronized int search(Object o);

public synchronized int search(Object o) method is used to determine if an object is on this Stack.

This method returns the object’s distance from the top of the stack or -1 if it cannot be found.

Parameter
o – The object to be found.

Apart from these Stack class also has inherited methods from class- Object. They are as follows:

  • finalize()
  • hashCode()
  • notifyAll()
  • wait()
  • wait(long, int)
  • equals()
  • getClass()
  • notify()
  • wait(long)

Stack class also has inherited methods from Vector. They are as follows:

  • addElement()
  • clone()
  • copyInto(Object[])
  • elements()
  • firstElement()
  • indexOf(Object, int)
  • isEmpty()
  • lastIndexOf(Object)
  • removeAllElements()
  • removeElementAt(int)
  • setSize()
  • toString()
  • capacity()
  • contains(Object)
  • elementAt(int)
  • ensureCapacity(int)
  • indexOf(Object)
  • insertElementAt(Object, int)
  • lastElement()
  • lastIndexOf(Object, int)
  • removeElement(Object)
  • setElementAt(Object, int)
  • size()
  • trimToSize()

Stack class also has inherited variables from Vector. They are as follows:

  • capacityIncrement
  • elementData
  • elementCount

An Example of stack implementation:

import java.util.*;
public class StackTest{
     public static void main(String []args){
        Stack st=new Stack();
        st.push("hello");
        st.push("hi");
        st.push("Good Morning");
        System.out.println("The elements of the Stack "+st);
        System.out.println("The element at the top of the Stack "+st.peek());
        System.out.println("The element popped out of the Stack "+st.pop());
        System.out.println("The elements of the Stack after pop "+st);
        System.out.println("The result of search from the Stack "+st.search("hi"));
        //search() will return -1 if not found
     }
}
 

The output of the code:
$javac StackTest.java
Note: StackTest.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint: unchecked for details.
$java -Xmx128M -Xms16M StackTest
The elements of the Stack [hello, hi, Good Morning]
The element at the top of the Stack Good Morning
The element popped out of the Stack Good Morning
The elements of the Stack after pop [hello, hi]
The result of a search from Stack 1

Another example:


import java.util.*;
public class StackTest{
     public static void main(String []args){
     String pathOfFile="C:Testabc.txt"
     BufferedReader in =new BufferedReader(new FileReader(pathOfFile))
//To read a line at a time from a Stream , we need to create a BufferedReader 
//object and to open a file we need to create FileReader object.
     Stack st=new Stack();
     String s;
//Once the BufferedReader object is created we can read file line by line by calling
//readLine() method.It breaks when end of file is reached.
     while((s=in.readLine())!=null)
pushing to stack
     st.push("n"+s);
//each line in the file is read and pushed to the stack.
     System.out.println("st="+st);
//treating stack as vector,it can be done without a cast.As stack is a Vector class
    Vector v=st;
//we can perform all the vector related operations here
    System.out.println("3rd element="+v.elementAt(2));
//poping from stack
    while((!st.empty())
    System.out.println("Poping="+st.pop());
}
 

How to Implement Stack in Java

Before we proceed further we need to understand what is Stack all about.
As per Wiki-One way of describing the stack is as a last-in, first-out (LIFO) abstract data type and linear data structure.

So our objective will be to
1.create a data structure to hold values
2.should be able to insert values in the current position
3.Should be able to remove values from last

For point#1 I will use array. This is easy to understand with Array. Later I will use some advanced concepts. So we need to create an array and a pointer that will provide me the current position of the array. let us initialize the pointer to -1. We need some control to restrict users for the pop without a push. and based on the size we can restrict the user to push beyond array capacity.
The starting of the code as follows:


int array_[];
int Stack_pointer_;
int Size_=0;
public void array_set(int Size)
{
array_=new int[Size];
Stack_pointer_=-1;
}

Well, now we need to implement the point-2 that It should be able to push values to the array…The Steps will be
1. Increment the pointer by one during the push.
2. Insert the value to the corresponding location.


public void push(int number) {
System.out.println("Stack pointer value"+Stack_pointer_);
array_[++Stack_pointer_]=number;
}
 

We will implement the point-3 that It should be able to pop values from the array. Here we need to decrease the pointer during the pop. So only we need to decrease the stack pointer value by one.


public long pop(){
//Stack_pointer_=Stack_pointer_-1;
System.out.println("Current Stack pointer value"+Stack_pointer_);
return array_[Stack_pointer_--];
}
 

Implementing the different Exception handling the code will look like-for Push


public void push(int number) {
    if (Stack_pointer_

Exception handling the code will look like-for POP


public long  pop(int j){
    //Stack_pointer_=Stack_pointer_-1;
    if(Stack_pointer_==-1)
    {
        System.out.println("You can not pop here");
        return array_[Stack_pointer_];
    }
    else
    {
       System.out.println("Poping "+j+array_[j]);
      return  array_[Stack_pointer_--];
}

}

The final code will look like—


import java.io.PrintStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.swing.JOptionPane;
public class Calculator {
int array_[];
int Stack_pointer_;
int Size_=0;
public void push(int number) {
if (Stack_pointer_=0;j--)
{
System.out.println("Poping"+j);
calc.pop(j);
}
}
}