Access Modifiers in Java
Access Modifiers in Java
There are two types of modifiers in Java: access modifiers and non-
access modifiers.
Skip Ad
Understanding Java Access Modifiers
Let's understand the access modifiers in Java by a simple table.
Private Y N N N
Default Y Y N N
Protected Y Y Y N
Public Y Y Y Y
1) Private
The private access modifier is accessible only within the class.
class A
{
int data=40;
void msg()
{
System.out.println("Hello java");
}
}
public class Simple
{
public static void main(String args[])
{
A obj=new A();
System.out.println(obj.data);//Compile Time Error
obj.msg();//Compile Time Error
}
}
If you make any class constructor private, you cannot create the
instance of that class from outside the class. For example:
1. class A{
2. private A(){}//private constructor
3. void msg(){System.out.println("Hello java");}
4. }
5. public class Simple{
6. public static void main(String args[]){
7. A obj=new A();//Compile Time Error
8. }
9. }
2) Default
If you don't use any modifier, it is treated as default by default. The
default modifier is accessible only within package. It cannot be
accessed from outside the package. It provides more accessibility than
private. But, it is more restrictive than protected, and public.
1. //save by A.java
2. package pack;
3. class A{
4. void msg(){System.out.println("Hello");}
5. }
1. //save by B.java
2. package mypack;
3.
4. import pack.*;
5. class B{
6. public static void main(String args[]){
7. A obj = new A();//Compile Time Error
8. obj.msg();//Compile Time Error
9. }
10. }
In the above example, the scope of class A and its method msg() is
default so it cannot be accessed from outside the package.
3) Protected
The protected access modifier is accessible within package and
outside the package but through inheritance only.
In this example, we have created the two packages pack and mypack.
The A class of pack package is public, so can be accessed from outside
the package. But msg method of this package is declared as protected,
so it can be accessed from outside the class only through inheritance.
1. //save by A.java
2. package pack;
3. public class A{
4. protected void msg(){System.out.println("Hello");}
5. }
1. //save by B.java
2. package mypack;
3. import pack.*;
4.
5. class B extends A{
6. public static void main(String args[]){
7. B obj = new B();
8. obj.msg();
9. }
10. }
Output:Hello
4) Public
The public access modifier is accessible everywhere. It has the
widest scope among all other modifiers.
1. //save by A.java
2.
3. package pack;
4. public class A{
5. public void msg(){System.out.println("Hello");}
6. }
1. //save by B.java
2.
3. package mypack;
4. import pack.*;
5.
6. class B{
7. public static void main(String args[]){
8. A obj = new A();
9. obj.msg();
10. }
11. }
Output:Hello
1. class A{
2. protected void msg(){System.out.println("Hello java");}
3. }
4.
5. public class Simple extends A{
6. void msg(){System.out.println("Hello java");}//C.T.Error
7. public static void main(String args[]){
8. Simple obj=new Simple();
9. obj.msg();
10. }
11. }
The Object class is beneficial if you want to refer any object whose type
you don't know. Notice that parent class reference variable can refer
the child class object, known as upcasting.
Method Description
public final Class getClass() returns the Class class object of this object. The
Class class can further be used to get the
metadata of this class.
public int hashCode() returns the hashcode number for this object.
public boolean equals(Object obj) compares the given object to this object.
protected Object clone() throws creates and returns the exact copy (clone) of
CloneNotSupportedException this object.
public final void notify() wakes up single thread, waiting on this object's
monitor.
public final void notifyAll() wakes up all the threads, waiting on this
object's monitor.
public final void wait(long causes the current thread to wait for the
timeout)throws InterruptedException specified milliseconds, until another thread
notifies (invokes notify() or notifyAll() method).
public final void wait(long timeout,int causes the current thread to wait for the
nanos)throws InterruptedException specified milliseconds and nanoseconds, until
another thread notifies (invokes notify() or
notifyAll() method).
public final void wait()throws causes the current thread to wait, until another
InterruptedException thread notifies (invokes notify() or notifyAll()
method).
The Object class provides some common behaviors to all the objects
such as object can be compared, object can be cloned, object can be
notified etc.
The Object class provides many methods. They are as follows:
Java String
In Java, string is basically an object that represents sequence of char
values. An array of characters works same as Java string. For example:
1. char[] ch={'j','a','v','a','t','p','o','i','n','t'};
2. String s=new String(ch);
is same as:
1. String s="javatpoint";
1. By string literal
2. By new keyword
1) String Literal
Java String literal is created by using double quotes. For Example:
1. String s="welcome";
Each time you create a string literal, the JVM checks the "string
constant pool" first. If the string already exists in the pool, a reference
to the pooled instance is returned. If the string doesn't exist in the
pool, a new string instance is created and placed in the pool. For
example:
1. String s1="Welcome";
2. String s2="Welcome";//It doesn't create a new instance
In the above example, only one object will be created. Firstly, JVM will
not find any string object with the value "Welcome" in string constant
pool that is why it will create a new object. After that it will find the
string with the value "Welcome" in the pool, it will not create a new
object but will return the reference to the same instance.
By new keyword
1. String s=new String("Welcome");//creates two objects and one referen
ce variable
In such case, JVM will create a new string object in normal (non-pool)
heap memory, and the literal "Welcome" will be placed in the string
constant pool. The variable s will refer to the object in a heap (non-
pool).
1.
2.
3.
4. public class StringExample{
5. public static void main(String args[]){
6. String s1="java";//creating string by Java string literal
7. char ch[]={'s','t','r','i','n','g','s'};
8. String s2=new String(ch);//converting char array to string
9. String s2=ch.toString();
10. String s3=new String("example");//creating Java string by new ke
yword
11. System.out.println(s1);
12. System.out.println(s2);
13. System.out.println(s3);
14. }}
StringBuffer In Java
StringBuffer is a class in java whose object represents the
mutable string. It is just like string class except that its object
can be modified. StringBuffer is synchronized, hence it is
thread-safe.
classA {
public static void main(String args[])
{
StringBuffer sb = new StringBuffer("Hello ");
sb.append("Java"); // now original string is changed
System.out.println(sb);
}
}
insert() method
The insert() method inserts the given string with this string at the given
position.
classA {
public static void main(String args[])
{
StringBuffersb = new StringBuffer("Hello ");
sb.insert(1, "Java");
// Now original string is changed
System.out.println(sb);
}
}
replace() method
The replace() method replaces the given string from the specified beginIndex
and endIndex-1.
classA{
publicstaticvoidmain(String args[]){
StringBuffer sb=new StringBuffer("Hello");
sb.replace(1,3,"Java");
System.out.println(sb);
}
}
delete() method
The delete() method of StringBuffer class deletes the string from
the specified beginIndex to endIndex-1.
Class A{
Public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello");
sb.delete(1,3);
System.out.println(sb);
}
}
Creating an Array of Objects
Before creating an array of objects, we must create an instance of the
class by using the new keyword. We can use any of the following
statements to create an array of objects.
Syntax:
Or
ClassName[] objArray;
Or
ClassName objeArray[];
1. Employee department1[20];
2. Employee department2[20];
3. Employee department3[20];
ArrayOfObjects.java
}
Constructor overloading in Java
In Java, we can overload constructors like methods. The constructor
overloading can be defined as the concept of having more than one
constructor with different parameters so that every constructor can
perform a different task.
Example
Student()
{
this. id=0;
this. name=null;
this. class=null
}
Student(int id, String name)
{
this.id=id;
this.name = name;
}
Student(int id, String name,String class){
this.id=id;
this.name = name;
this.class= class;
}
public static void main(String[] args) {
//object creation
Student s = new Student();
System.out.println("\nDefault Constructor values: \n");
System.out.println("Student Id : "+s.id + "\nStudent Name : "+s.name);
}
}
Output:
Student Id : 0
Student Name : null
Student Id : 10
Student Name : David
63.6M
1K
Hello Java Program for Beginners
Next
Here, we need to understand the purpose of constructor overloading.
Sometimes, we need to use multiple constructors to initialize the
different values of the class.
Consider the following example, which contains the error since the
Colleges object can't be created using the default constructor now
since it doesn't contain one.
Output:
Name: John
Id: 101
Contact No.: 9899234455
College Name: 9899234455
Passing Year: 2018
The static keyword in Java
is used for memory management mainly. We can apply static keyword with variables
. The static keyword belongs to the class than an instance of the class.
Suppose there are 500 students in my college, now all instance data
members will get memory each time when the object is created. All
students have its unique rollno and name, so instance data member is
good in such case. Here, "college" refers to the common property of
all objects
. If we make it static, this field will get the memory only once.
Program of the counter without static variable
In this example, we have created an instance variable named count which
is incremented in the constructor. Since instance variable gets the
memory at the time of object creation, each object will have the copy of
the instance variable. If it is incremented, it won't reflect other objects. So
each object will have the value 1 in the count variable.
Counter(){
count++;//incrementing value
System.out.println(count);
}
Output:
1
1
1
Output:
1
2
3
o A static method belongs to the class rather than the object of a class.
o A static method can be invoked without the need for creating an instance
of a class.
o A static method can access static data member and can change the value
of it.
1. //Java Program to get the cube of a given number using the static m
ethod
2.
3. class Calculate{
4. static int cube(int x){
5. return x*x*x;
6. }
7.
8. public static void main(String args[]){
9. int result=Calculate.cube(5);
10. System.out.println(result);
11. }
12.}
Output:125
There are two main restrictions for the static method. They are:
1. The static method can not use non static data member or call non-static
method directly.
2. this and super cannot be used in static context.
1. class A{
2. int a=40;//non static
3.
4. public static void main(String args[]){
5. System.out.println(a);
6. }
7. }
Output:Compile Time Error
class A2
{
Static
{
System.out.println("static block is invoked");
}
public static void main(String args[]){
System.out.println("Hello main");
}
}
Output:static block is invoked
Hello main
Ans) No, one of the ways was the static block, but it was possible till JDK
1.6. Since JDK 1.7, it is not possible to execute a Java class without
the main method.
1. class A3{
2. static{
3. System.out.println("static block is invoked");
4. System.exit(0);
5. }
6. }
Output:
Package in java can be categorized in two form, built-in package and user-
defined package.
There are many built-in packages such as java, lang, awt, javax, swing,
net, io, util, sql etc
62.2M
1.3K
1. //save as Simple.java
2. package mypack;
3. public class Simple{
4. public static void main(String args[]){
5. System.out.println("Welcome to package");
6. }
7. }
If you are not using any IDE, you need to follow the syntax given below:
For example
1. javac -d . Simple.java
The -d switch specifies the destination where to put the generated class
file. You can use any directory name like /home (in case of Linux), d:/abc
(in case of windows) etc. If you want to keep the package within the same
directory, you can use . (dot).
How to run java package program
You need to use fully qualified name e.g. mypack.Simpleetc to run the
class.
Output:Welcome to package
The -d is a switch that tells the compiler where to put the class file i.e. it
represents destination. The . represents the current folder.
1. import package.*;
2. import package.classname;
3. fully qualified name.
1) Using packagename.*
If you use package.* then all the classes and interfaces of this package
will be accessible but not subpackages.
The import keyword is used to make the classes and interface of another
package accessible to the current package.
1. //save by A.java
2. package pack;
3. public class A{
4. public void msg(){System.out.println("Hello");}
5. }
1. //save by B.java
2. package mypack;
3. import pack.*;
4.
5. class B{
6. public static void main(String args[]){
7. A obj = new A();
8. obj.msg();
9. }
10.}
Output:Hello
2) Using packagename.classname
If you import package.classname then only declared class of this package
will be accessible.
1. //save by A.java
2.
3. package pack;
4. public class A{
5. public void msg(){System.out.println("Hello");}
6. }
1. //save by B.java
2. package mypack;
3. import pack.A;
4.
5. class B{
6. public static void main(String args[]){
7. A obj = new A();
8. obj.msg();
9. }
10.}
Output:Hello
It is generally used when two packages have same class name e.g.
java.util and java.sql packages contain Date class.
1. //save by A.java
2. package pack;
3. public class A{
4. public void msg(){System.out.println("Hello");}
5. }
1. //save by B.java
2. package mypack;
3. class B{
4. public static void main(String args[]){
5. pack.A obj = new pack.A();//using fully qualified name
6. obj.msg();
7. }
8. }
Output:Hello
If you import a package, all the classes and interface of that package will
be imported excluding the classes and interfaces of the subpackages.
Hence, you need to import the subpackage as well.
Note: Sequence of the program must be package then import then class.
Subpackage in java
Package inside the package is called the subpackage. It should be
created to categorize the package further.
Example of Subpackage
1. package com.sun.core;
2. class Simple{
3. public static void main(String args[]){
4. System.out.println("Hello subpackage");
5. }
6. }
To Compile: javac -d . Simple.java
package Assignment2.SY;
import java.io.BufferedReader;
import java.io.*;
Q: Write a Java program to create a Package “SY” which has a class SYMarks (members –
ComputerTotal, MathsTotal, and ElectronicsTotal). Create another package TY which has a class
TYMarks (members – Theory, Practicals). Create n objects of Student class (having rollNumber,
name, SYMarks and TYMarks). Add the marks of SY and TY computer subjects and calculate the
Grade (‘A’ for >= 70, ‘B’ for >= 60 ‘C’ for >= 50 , Pass Class for > =40 else ‘FAIL’) and display the
result of the student in proper format.
package Assignment2.TY;
import java.io.*;
public class TYClass {
public int tm,pm;
public void get() throws IOException{
System.out.println("Enter the marks of the theory out of 400 and practicals out of
200: ");
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
tm=Integer.parseInt(br.readLine());
pm=Integer.parseInt(br.readLine());
}
package Assignment2;
import Assignment2.SY.*;
import Assignment2.TY.*;
import java.io.*;
class StudentInfo{
int rollno;
String name,grade;
public float gt,tyt,syt;
public float per;
public void get() throws IOException{
System.out.println("Enter roll number and name of the student: ");
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
rollno=Integer.parseInt(br.readLine());
name=br.readLine();
}
}
public class StudentMarks {
public static void main(String[] args) throws IOException{
si[i].get();
sy[i].get();
ty[i].get();
si[i].syt=sy[i].ct+sy[i].et+sy[i].mt;
si[i].tyt=ty[i].pm+ty[i].tm;
si[i].gt=si[i].syt+si[i].tyt;
si[i].per=(si[i].gt/1200)*100;
if(si[i].per>=70) si[i].grade="A";
else if(si[i].per>=60) si[i].grade="B";
else if(si[i].per>=50) si[i].grade="C";
else if(si[i].per>=40) si[i].grade="Pass";
else si[i].grade="Fail";
}
System.out.println("Roll No\tName\tSyTotal\tTyTotal\tGrandTotal\tPercentage\
tGrade");
for(int i=0;i<n;i++)
{
System.out.println(si[i].rollno+"\t"+si[i].name+"\t"+si[i].syt+"\t"+si[i].tyt+"\
t"+si[i].gt+"\t\t"+si[i].per+"\t\t"+si[i].grade);
}
}
Boolean Boolean
Char Character
Byte Byte
Short Short
Int Integer
Long Long
Float Float
Double Double
Autoboxing
The automatic conversion of primitive data type into its corresponding
wrapper class is known as autoboxing, for example, byte to Byte, char
to Character, int to Integer, long to Long, float to Float, boolean to
Boolean, double to Double, and short to Short.
Output:
20 20 20
Unboxing
The automatic conversion of wrapper type into its corresponding
primitive type is known as unboxing. It is the reverse process of
autoboxing. Since Java 5, we do not need to use the intValue() method
of wrapper classes to convert the wrapper type into primitives.
11. }}
Output:
3 3 3