0% found this document useful (0 votes)
33 views45 pages

Access Modifiers in Java

Uploaded by

aishwaryaade126
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
33 views45 pages

Access Modifiers in Java

Uploaded by

aishwaryaade126
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Access Modifiers in Java

There are two types of modifiers in Java: access modifiers and non-
access modifiers.

The access modifiers in Java specifies the accessibility or scope of a


field, method, constructor, or class. We can change the access level of
fields, constructors, methods, and class by applying the access
modifier on it.

There are four types of Java access modifiers:

1. Private: The access level of a private modifier is only within the


class. It cannot be accessed from outside the class.
2. Default: The access level of a default modifier is only within the
package. It cannot be accessed from outside the package. If you
do not specify any access level, it will be the default.
3. Protected: The access level of a protected modifier is within the
package and outside the package through child class. If you do
not make the child class, it cannot be accessed from outside the
package.
4. Public: The access level of a public modifier is everywhere. It can
be accessed from within the class, outside the class, within the
package and outside the package.

There are many non-access modifiers, such as static, abstract,


synchronized, native, volatile, transient, etc.

Skip Ad
Understanding Java Access Modifiers
Let's understand the access modifiers in Java by a simple table.

Access within within outside package by subclass outside


Modifier class package only package

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.

Simple example of private access modifier

In this example, we have created two classes A and Simple. A class


contains private data member and private method. We are accessing
these private members from outside the class, so there is a compile-
time error.

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
}
}

Role of Private Constructor

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. }

Note: A class cannot be private or protected except nested class.

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.

Example of default access modifier

In this example, we have created two packages pack and mypack. We


are accessing the A class from outside its package, since A class is not
public, so it cannot be accessed from outside the package.

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.

The protected access modifier can be applied on the data member,


method and constructor. It can't be applied on the class.

It provides more accessibility than the default modifer.

Example of protected access modifier

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.

Example of public access modifier

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

Java Access Modifiers with Method Overriding


If you are overriding any method, overridden method (i.e. declared in
subclass) must not be more restrictive.

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 default modifier is more restrictive than protected. That is why,


there is a compile-time error.

Object class in Java


The Object class is the parent class of all the classes in java by
default. In other words, it is the topmost class of java.

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.

Let's take an example, there is getObject() method that returns an


object but it can be of any type like Employee,Student etc, we can use
Object class reference to refer that object. For example:

1. Object obj=getObject();//we don't know what object will be returned fro


m this method

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 String toString() returns the string representation of 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).

protected void finalize()throws is invoked by the garbage collector before


Throwable object is being garbage collected.

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:

Methods of Object class

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";

Java String class provides a lot of methods to perform operations on


strings such as compare(), concat(), equals(), split(), length(), replace(),
compareTo(), intern(), substring() etc.

The java.lang.String class


implements Serializable, Comparable and CharSequence interfaces.
The Java String is immutable which means it cannot be changed.
Whenever we change any string, a new instance is created. For
mutable strings, you can use StringBuffer and StringBuilder classes.

What is String in Java?


Generally, String is a sequence of characters. But in Java, string is an
object that represents a sequence of characters. The java.lang.String
class is used to create a string object.

How to create a string object?


There are two ways to create String object:

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).

Java String Example


StringExample.java

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. }}

Java String class methods


The java.lang.String class provides many useful methods to perform
operations on sequence of char values.

No. Method Description

1 char charAt(int index) It returns char value for the


particular index

2 int length() It returns string length

3 static String format(String format, Object... It returns a formatted string.


args)

4 static String format(Locale l, String format, It returns formatted string with


Object... args) given locale.

5 String substring(int beginIndex) It returns substring for given


begin index.
6 String substring(int beginIndex, int endIndex) It returns substring for given
begin index and end index.

7 boolean contains(CharSequence s) It returns true or false after


matching the sequence of char
value.

8 static String join(CharSequence delimiter, It returns a joined string.


CharSequence... elements)

9 static String join(CharSequence delimiter, It returns a joined string.


Iterable<? extends CharSequence> elements)

10 boolean equals(Object another) It checks the equality of string


with the given object.

11 boolean isEmpty() It checks if string is empty.

12 String concat(String str) It concatenates the specified


string.

13 String replace(char old, char new) It replaces all occurrences of the


specified char value.

14 String replace(CharSequence old, It replaces all occurrences of the


CharSequence new) specified CharSequence.

15 static String equalsIgnoreCase(String another) It compares another string. It


doesn't check case.

16 String[] split(String regex) It returns a split string matching


regex.

17 String[] split(String regex, int limit) It returns a split string matching


regex and limit.

18 String intern() It returns an interned string.

19 int indexOf(int ch) It returns the specified char


value index.

20 int indexOf(int ch, int fromIndex) It returns the specified char


value index starting with given
index.

21 int indexOf(String substring) It returns the specified substring


index.

22 int indexOf(String substring, int fromIndex) It returns the specified substring


index starting with given index.

23 String toLowerCase() It returns a string in lowercase.

24 String toLowerCase(Locale l) It returns a string in lowercase


using specified locale.

25 String toUpperCase() It returns a string in uppercase.

26 String toUpperCase(Locale l) It returns a string in uppercase


using specified locale.

27 String trim() It removes beginning and ending


spaces of this string.

28 static String valueOf(int value) It converts given type into string.


It is an overloaded method.

public class FormatExample2 {


public static void main(String[] args) {
String str1 = String.format("%d", 101); // Integer value
String str2 = String.format("%s", "Amar Singh"); // String value
String str3 = String.format("%f", 101.00); // Float value
String str4 = String.format("%x", 101); // Hexadecimal value
String str5 = String.format("%c", 'c'); // Char value
System.out.println(str1);
System.out.println(str2);
System.out.println(str3);
System.out.println(str4);
System.out.println(str5);
}

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.

StringBuffer is a peer class of String that provides much of


the functionality of strings. The string represents fixed-
length, immutable character sequences while StringBuffer
represents growable and writable character
sequences. StringBuffer may have characters and substrings
inserted in the middle or appended to the end. It will
automatically grow to make room for such additions and
often has more characters preallocated than are actually
needed, to allow room for growth.
StringBuffer class is used to create mutable (modifiable)
string. The StringBuffer class in java is same as String class
except it is mutable i.e. it can be changed.

Important Constructors of StringBuffer class


 StringBuffer(): creates an empty string buffer with the initial capacity
of 16.
 StringBuffer(String str): creates a string buffer with the specified
string.
 StringBuffer(int capacity): creates an empty string buffer with the
specified capacity as length.
1) append() method
The append() method concatenates the given argument with this string.

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:

1. ClassName obj[]=new ClassName[array_length]; //declare and instanti


ate an array of objects

Or

ClassName[] objArray;

Or

ClassName objeArray[];

Suppose, we have created a class named Employee. We want to keep


records of 20 employees of a company having three departments. In
this case, we will not create 20 separate variables. Instead of this, we
will create an array of objects, as follows.

1. Employee department1[20];
2. Employee department2[20];
3. Employee department3[20];

The above statements create an array of objects with 20 elements.

ArrayOfObjects.java

public class ArrayOfObjects


{
public static void main(String args[])
{
//create an array of product object
Product[] obj = new Product[5] ;
//create & initialize actual product objects using constructor
obj[0] = new Product(23907,"Dell Laptop");
obj[1] = new Product(91240,"HP 630");
obj[2] = new Product(29823,"LG OLED TV");
obj[3] = new Product(11908,"MI Note Pro Max 9");
obj[4] = new Product(43590,"Kingston USB");
//display the product object data
for(int i=0;i<5;i++)
{
obj[i].display();
}
}
//Product class with product Id and product name as attributes
class Product
{
int pro_Id;
String pro_name;
//Product class constructor
Product(int pid, String n)
{
pro_Id = pid;
pro_name = n;
}
public void display()
{
System.out.print("Product Id = "+pro_Id + " " + " Product Name = "+pro_
name);
System.out.println();
} }

}
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.

Consider the following Java program, in which we have used different


constructors in the class.

Example

public class Student


{
//instance variables of the class
int id;
String name;
String class;

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);

System.out.println("\nParameterized Constructor values: \n");


Student student = new Student(10, "David");
System.out.println("Student Id : "+student.id + "\nStudent Name :
"+student.name);
Student student_two= new Student(11, "Akshay",”TYBSC);
System.out.println("Student Id : "+student.id + "\nStudent Name :
"+student.name+”\nStudentClass:”+student_two.class);

}
}

Output:

this a default constructor

Default Constructor values:

Student Id : 0
Student Name : null

Parameterized Constructor values:

Student Id : 10
Student Name : David

In the above example, the Student class constructor is overloaded with


two different constructors, I.e., default and parameterized.

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.

We must also notice that the java compiler invokes a default


constructor when we do not use any constructor in the class. However,
the default constructor is not invoked if we have used any constructor
in the class, whether it is default or parameterized. In this case, the
java compiler throws an exception saying the constructor is undefined.

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.

1. public class Colleges {


2. String collegeId;
3. Colleges(String collegeId){
4. this.collegeId = "IIT " + collegeId;
5. }
6. public static void main(String[] args) {
7. // TODO Auto-generated method stub
8. Colleges clg = new Colleges(); //this can't create colleges constructor n
ow.
9. }
10.
11.
12. }

Use of this () in constructor overloading


However, we can use this keyword inside the constructor, which can be
used to invoke the other constructor of the same class.

Consider the following example to understand the use of this keyword


in constructor overloading.
1. public class Student {
2. //instance variables of the class
3. int id,passoutYear;
4. String name,contactNo,collegeName;
5.
6. Student(String contactNo, String collegeName, int passoutYear){
7. this.contactNo = contactNo;
8. this.collegeName = collegeName;
9. this.passoutYear = passoutYear;
10. }
11.
12. Student(int id, String name){
13. this("9899234455", "IIT Kanpur", 2018);
14. this.id = id;
15. this.name = name;
16. }
17.
18. public static void main(String[] args) {
19. //object creation
20. Student s = new Student(101, "John");
21. System.out.println("Printing Student Information: \n");
22. System.out.println("Name: "+s.name+"\nId: "+s.id+"\nContact N
o.: "+s.contactNo+"\nCollege Name: "+s.contactNo+"\nPassing Year:
"+s.passoutYear);
23. }
24. }

Output:

Printing Student Information:

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

, methods, blocks and nested classes

. The static keyword belongs to the class than an instance of the class.

The static can be:

1. Variable (also known as a class variable)


2. Method (also known as a class method)
3. Block
4. Nested class
1) Java static variable
If you declare any variable as static, it is known as a static variable.

o The static variable can be used to refer to the common property


of all objects (which is not unique for each object), for example,
the company name of employees, college name of students, etc.
o The static variable gets memory only once in the class area at
the time of class loading.

Advantages of static variable

It makes your program memory efficient (i.e., it saves memory).

Understanding the problem without static variable

Example of static variable

1. //Java Program to demonstrate the use of static variable


2. class Student{
3. int rollno;//instance variable
4. String name;
5. static String college ="ITS";//static variable
6. //constructor
7. Student(int r, String n){
8. rollno = r;
9. name = n;
10. }
11. //method to display the values
12. void display (){System.out.println(rollno+" "+name+"
"+college);}
13. }
14. //Test class to show the values of objects
15. public class TestStaticVariable1{
16. public static void main(String args[]){
17. Student s1 = new Student(111,"Karan");
18. Student s2 = new Student(222,"Aryan");
19. //we can change the college of all objects by the single line of co
de
20. //Student.college="BBDIT";
21. s1.display();
22. s2.display();
23. }
24. }
1. class Student{
2. int rollno;
3. String name;
4. String college="ITS";
5. }

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.

1. //Java Program to demonstrate the use of an instance variable


2. //which get memory each time when we create an object of the class.
class Counter{
int count=0;//will get memory each time when the instance is created

Counter(){
count++;//incrementing value
System.out.println(count);
}

public static void main(String args[]){


//Creating objects
Counter c1=new Counter();
Counter c2=new Counter();
Counter c3=new Counter();
}
}

Output:

1
1
1

Program of counter by static variable


As we have mentioned above, static variable will get the memory only
once, if any object changes the value of the static variable, it will retain its
value.

1. //Java Program to illustrate the use of static variable which


2. //is shared with all objects.
3. class Counter2{
4. static int count=0;//will get memory only once and retain its value
5.
6. Counter2(){
7. count++;//incrementing the value of static variable
8. System.out.println(count);
9. }
10.
11. public static void main(String args[]){
12.//creating objects
13. Counter2 c1=new Counter2();
14.Counter2 c2=new Counter2();
15. Counter2 c3=new Counter2();
16.}
17. }

Output:

1
2
3

2) Java static method


If you apply static keyword with any method, it is known as static method.

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.

Example of static method

1. //Java Program to demonstrate the use of a static method.


class Student{
int rollno;
String name;
static String college = "ITS";
//static method to change the value of static variable
static void change(){
college = "BBDIT";
}
//constructor to initialize the variable
Student(int r, String n){
rollno = r;
name = n;
}
//method to display values
void display(){System.out.println(rollno+" "+name+" "+college);}
}
//Test class to create and display the values of object
public class TestStaticMethod{
public static void main(String args[]){
Student.change();//calling change method
//creating objects
Student s1 = new Student(111,"Karan");
Student s2 = new Student(222,"Aryan");
Student s3 = new Student(333,"Sonoo");
//calling display method
s1.display();
s2.display();
s3.display();
}
}
Output:111 Karan BBDIT
222 Aryan BBDIT
333 Sonoo BBDIT

Another example of a static method that performs a


normal calculation

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

Restrictions for the static method

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

Q) Why is the Java main method static?


Ans) It is because the object is not required to call a static method. If it
were a non-static method, JVM creates an object first then call main()
method that will lead the problem of extra memory allocation.

3) Java static block


o Is used to initialize the static data member.
o It is executed before the main method at the time of classloading.
Example of static block

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

Q) Can we execute a program without main() method?

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:

static block is invoked


Java Package
A java package is a group of similar types of classes, interfaces and sub-
packages.

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

OOPs Concepts in Java

Advantage of Java Package

1) Java package is used to categorize the classes and interfaces so that


they can be easily maintained.

2) Java package provides access protection.

3) Java package removes naming collision.


Simple example of java package
The package keyword is used to create a package in java.

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. }

How to compile java package

If you are not using any IDE, you need to follow the syntax given below:

1. javac -d directory javafilename

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.

To Compile: javac -d . Simple.java

To Run: java mypack.Simple

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.

How to access package from another package?


There are three ways to access the package from outside the package.

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.

Example of package that import the packagename.*

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.

Example of package by import package.classname

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

3) Using fully qualified name


If you use fully qualified name then only declared class of this package will
be accessible. Now there is no need to import. But you need to use fully
qualified name every time when you are accessing the class or interface.

It is generally used when two packages have same class name e.g.
java.util and java.sql packages contain Date class.

Example of package by import fully qualified name

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

Note: If you import a package, subpackages will not be imported.

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.

Let's take an example, Sun Microsystem has definded a package named


java that contains many classes like System, String, Reader, Writer,
Socket etc. These classes represent a particular group e.g. Reader and
Writer classes are for Input/Output operation, Socket and ServerSocket
classes are for networking etc and so on. So, Sun has subcategorized the
java package into subpackages such as lang, net, io etc. and put the
Input/Output related classes in io package, Server and ServerSocket
classes in net packages and so on.

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

To Run: java com.javatpoint.core.Simple


Output:Hellosubpackage

package Assignment2.SY;

import java.io.BufferedReader;
import java.io.*;

public class SYClass {


public int ct,mt,et;
public void get() throws IOException{
System.out.println("Enter marks of students for computer, maths and electronics subject out of 200 ");
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
ct=Integer.parseInt(br.readLine());
mt=Integer.parseInt(br.readLine());
et=Integer.parseInt(br.readLine());
}

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{

BufferedReader br=new BufferedReader(new InputStreamReader(System.in));


System.out.println("Enter the number of students:");
int n=Integer.parseInt(br.readLine());
SYClass sy[]=new SYClass[n];
TYClass ty[]=new TYClass[n];
StudentInfo si[]=new StudentInfo[n];
for(int i=0;i<n;i++)
{
si[i]=new StudentInfo();
sy[i]=new SYClass();
ty[i]=new TYClass();

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);

}
}

Wrapper classes in Java


The wrapper class in Java provides the mechanism to convert
primitive into object and object into primitive.
Since J2SE 5.0, autoboxing and unboxing feature convert primitives
into objects and objects into primitives automatically. The automatic
conversion of primitive into an object is known as autoboxing and vice-
versa unboxing.

Use of Wrapper classes in Java


Java is an object-oriented programming language, so we need to deal
with objects many times like in Collections, Serialization,
Synchronization, etc. Let us see the different scenarios, where we need
to use the wrapper classes.

o Change the value in Method: Java supports only call by value.


So, if we pass a primitive value, it will not change the original
value. But, if we convert the primitive value in an object, it will
change the original value.
o Serialization: We need to convert the objects into streams to
perform the serialization. If we have a primitive value, we can
convert it in objects through the wrapper classes.
o Synchronization: Java synchronization works with objects in
Multithreading.
o java.util package: The java.util package provides the utility
classes to deal with objects.
o Collection Framework: Java collection framework works with
objects only. All classes of the collection framework (ArrayList,
LinkedList, Vector, HashSet, LinkedHashSet, TreeSet,
PriorityQueue, ArrayDeque, etc.) deal with objects only.

The eight classes of the java.lang package are known as wrapper


classes in Java. The list of eight wrapper classes are given below:

Primitive Type Wrapper class

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.

Since Java 5, we do not need to use the valueOf() method of wrapper


classes to convert the primitive into objects.

Wrapper class Example: Primitive to Wrapper

1. //Java program to convert primitive into objects


2. //Autoboxing example of int to Integer

public class WrapperExample1


{
public static void main(String args[])
{
//Converting int into Integer
int a=20;
Integer i=Integer.valueOf(a);/converting int into Integer explicitly
Integer j=a;//autoboxing, now compiler will write Integer.valueOf(a) intern
ally

System.out.println(a+" "+i+" "+j);


}
}

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.

Wrapper class Example: Wrapper to Primitive

1. //Java program to convert object into primitives


2. //Unboxing example of Integer to int
3. public class WrapperExample2{
4. public static void main(String args[]){
5. //Converting Integer to int
6. Integer a=new Integer(3);
7. int i=a.intValue();//converting Integer to int explicitly
8. int j=a;//unboxing, now compiler will write a.intValue() internally
9.
10. System.out.println(a+" "+i+" "+j);

11. }}

Output:

3 3 3

Java Wrapper classes Example


1. //Java Program to convert all primitives into its corresponding
2. //wrapper objects and vice-versa
3. public class WrapperExample3{
4. public static void main(String args[]){
5. byte b=10;
6. short s=20;
7. int i=30;
8. long l=40;
9. float f=50.0F;
10. double d=60.0D;
11. char c='a';
12. boolean b2=true;
13.
14. //Autoboxing: Converting primitives into objects
15. Byte byteobj=b;
16. Short shortobj=s;
17. Integer intobj=i;
18. Long longobj=l;
19. Float floatobj=f;
20. Double doubleobj=d;
21. Character charobj=c;
22. Boolean boolobj=b2;
23.
24. //Printing objects
25. System.out.println("---Printing object values---");
26. System.out.println("Byte object: "+byteobj);
27. System.out.println("Short object: "+shortobj);
28. System.out.println("Integer object: "+intobj);
29. System.out.println("Long object: "+longobj);
30. System.out.println("Float object: "+floatobj);
31. System.out.println("Double object: "+doubleobj);
32. System.out.println("Character object: "+charobj);
33. System.out.println("Boolean object: "+boolobj);
34.
35. //Unboxing: Converting Objects to Primitives
36. byte bytevalue=byteobj;
37. short shortvalue=shortobj;
38. int intvalue=intobj;
39. long longvalue=longobj;
40. float floatvalue=floatobj;
41. double doublevalue=doubleobj;
42. char charvalue=charobj;
43. boolean boolvalue=boolobj;
44.
45. //Printing primitives
46. System.out.println("---Printing primitive values---");
47. System.out.println("byte value: "+bytevalue);
48. System.out.println("short value: "+shortvalue);
49. System.out.println("int value: "+intvalue);
50. System.out.println("long value: "+longvalue);
51. System.out.println("float value: "+floatvalue);
52. System.out.println("double value: "+doublevalue);
53. System.out.println("char value: "+charvalue);
54. System.out.println("boolean value: "+boolvalue);
55. }}

You might also like