0% found this document useful (0 votes)
2 views25 pages

java_part-2

Uploaded by

sauravguptaapr
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)
2 views25 pages

java_part-2

Uploaded by

sauravguptaapr
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
You are on page 1/ 25

Access Modifiers in java

1. private access modifier


2. Role of private constructor
3. default access modifier
4. protected access modifier
5. public access modifier
6. Applying access modifier with method overriding

There are two types of modifiers in java: access modifiers andnon-access modifiers.

The access modifiers in java specifies accessibility (scope) of a data member, method, constructor or class.

There are 4 types of java access modifiers:

1. private
2. default
3. protected
4. public

There are many non-access modifiers such as static, abstract, synchronized, native, volatile, transient etc.
Here, we will learn access modifiers.

1) private access modifier


The private access modifier is accessible only within 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 compile time
error.
1. class A{
2. private int data=40;
3. private void msg(){System.out.println("Hello java");}
4. }
5.
6. public class Simple{
7. public static void main(String args[]){
8. A obj=new A();
9. System.out.println(obj.data);//Compile Time Error
10. obj.msg();//Compile Time Error
11. }
12. }

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 access modifier


If you don't use any modifier, it is treated as default bydefault. The default modifier is accessible only
within package.

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. import pack.*;
4. class B{
5. public static void main(String args[]){
6. A obj = new A();//Compile Time Error
7. obj.msg();//Compile Time Error
8. }
9. }

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 access modifier


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.

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 access modifier


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

Understanding all java access modifiers


Let's understand the access modifiers by a simple table.

Access Modifier within class within package outside package by subclass only outside package

Private Y N N N

Default Y Y N N

Protected Y Y Y N

Public Y Y Y Y

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 compile time error.

Encapsulation in Java
Encapsulation in java is a process of wrapping code and data together into a single unit, for example
capsule i.e. mixed of several medicines.

We can create a fully encapsulated class in java by making all the data members of the class private. Now
we can use setter and getter methods to set and get the data in it.

The Java Bean class is the example of fully encapsulated class.

Advantage of Encapsulation in java

By providing only setter or getter method, you can make the class read-only or write-only.

It provides you the control over the data. Suppose you want to set the value of id i.e. greater than 100
only, you can write the logic inside the setter method.

Object class in Java


The Object class is the parent class of all the classes in java bydefault. 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, know 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 what object would be returned from this method

The Object class provides some common behaviours to all the objects such as object can be compared,
object can be cloned, object can be notified etc.

Methods of Object class


The Object class provides many methods. They are as follows:

Method Description

public final ClassgetClass() 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 this object.
CloneNotSupportedException

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 timeout)throws causes the current thread to wait for the specified
InterruptedException 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 specified
nanos)throws InterruptedException miliseconds and nanoseconds, until another thread notifies
(invokes notify() or notifyAll() method).

public final void wait()throws causes the current thread to wait, until another thread
InterruptedException notifies (invokes notify() or notifyAll() method).

protected void finalize()throws Throwable is invoked by the garbage collector before object is being
garbage collected.

Object Cloning in Java


The object cloning is a way to create exact copy of an object. For this purpose, clone() method of Object
class is used to clone an object.
The java.lang.Cloneable interface must be implemented by the class whose object clone we want to
create. If we don't implement Cloneable interface, clone() method
generatesCloneNotSupportedException.

The clone() method is defined in the Object class. Syntax of the clone() method is as follows:

1. protected Object clone() throws CloneNotSupportedException

Why use clone() method ?

The clone() method saves the extra processing task for creating the exact copy of an object. If we perform
it by using the new keyword, it will take a lot of processing to be performed that is why we use object
cloning.

Advantage of Object cloning

Less processing task.

Example of clone() method (Object cloning)

Let's see the simple example of object cloning

1. class Student18 implements Cloneable{


2. int rollno;
3. String name;
4.
5. Student18(int rollno,String name){
6. this.rollno=rollno;
7. this.name=name;
8. }
9.
10. public Object clone()throws CloneNotSupportedException{
11. return super.clone();
12. }
13.
14. public static void main(String args[]){
15. try{
16. Student18 s1=new Student18(101,"amit");
17.
18. Student18 s2=(Student18)s1.clone();
19.
20. System.out.println(s1.rollno+" "+s1.name);
21. System.out.println(s2.rollno+" "+s2.name);
22.
23. }catch(CloneNotSupportedException c){}
24.
25. }
26. }
Test it Now
Output:101 amit
101 amit
As you can see in the above example, both reference variables have the same value. Thus, the clone()
copies the values of an object to another. So we don't need to write explicit code to copy the value of an
object to another.

If we create another object by new keyword and assign the values of another object to this one, it will require
a lot of processing on this object. So to save the extra processing task we use clone() method

Java Array
Normally, array is a collection of similar type of elements that have contiguous memory location.
Java array is an object the contains elements of similar data type. It is a data structure where we store
similar elements. We can store only fixed set of elements in a java array.

Array in java is index based, first element of the array is stored at 0 index.

Advantage of Java Array


 Code Optimization: It makes the code optimized, we can retrieve or sort the data easily.
 Random access: We can get any data located at any index position.

Disadvantage of Java Array


 Size Limit: We can store only fixed size of elements in the array. It doesn't grow its size at runtime.
To solve this problem, collection framework is used in java.

Types of Array in java


There are two types of array.

 Single Dimensional Array


 Multidimensional Array

Single Dimensional Array in java


Syntax to Declare an Array in java
1. dataType[] arr; (or)
2. dataType []arr; (or)
3. dataType arr[];

Instantiation of an Array in java


1. arrayRefVar=new datatype[size];
Example of single dimensional java array

Let's see the simple example of java array, where we are going to declare, instantiate, initialize and traverse
an array.

1. class Testarray{
2. public static void main(String args[]){
3.
4. int a[]=new int[5];//declaration and instantiation
5. a[0]=10;//initialization
6. a[1]=20;
7. a[2]=70;
8. a[3]=40;
9. a[4]=50;
10.
11. //printing array
12. for(int i=0;i<a.length;i++)//length is the property of array
13. System.out.println(a[i]);
14.
15. }}
Test it Now

Output: 10
20
70
40
50

Declaration, Instantiation and Initialization of Java Array


We can declare, instantiate and initialize the java array together by:

1. int a[]={33,3,4,5};//declaration, instantiation and initialization

Let's see the simple example to print this array.

1. class Testarray1{
2. public static void main(String args[]){
3.
4. int a[]={33,3,4,5};//declaration, instantiation and initialization
5.
6. //printing array
7. for(int i=0;i<a.length;i++)//length is the property of array
8. System.out.println(a[i]);
9.
10. }}
Test it Now

Output:33
3
4
5

Passing Array to method in java


We can pass the java array to method so that we can reuse the same logic on any array.

Let's see the simple example to get minimum number of an array using method.

1. class Testarray2{
2. static void min(int arr[]){
3. int min=arr[0];
4. for(int i=1;i<arr.length;i++)
5. if(min>arr[i])
6. min=arr[i];
7.
8. System.out.println(min);
9. }
10.
11. public static void main(String args[]){
12.
13. int a[]={33,3,4,5};
14. min(a);//passing array to method
15.
16. }}
Test it Now

Output:3

Multidimensional array in java


In such case, data is stored in row and column based index (also known as matrix form).

Syntax to Declare Multidimensional Array in java


1. dataType[][] arrayRefVar; (or)
2. dataType [][]arrayRefVar; (or)
3. dataType arrayRefVar[][]; (or)
4. dataType []arrayRefVar[];

Example to instantiate Multidimensional Array in java


1. int[][] arr=new int[3][3];//3 row and 3 column

Example to initialize Multidimensional Array in java


1. arr[0][0]=1;
2. arr[0][1]=2;
3. arr[0][2]=3;
4. arr[1][0]=4;
5. arr[1][1]=5;
6. arr[1][2]=6;
7. arr[2][0]=7;
8. arr[2][1]=8;
9. arr[2][2]=9;

Example of Multidimensional java array

Let's see the simple example to declare, instantiate, initialize and print the 2Dimensional array.

1. class Testarray3{
2. public static void main(String args[]){
3.
4. //declaring and initializing 2D array
5. int arr[][]={{1,2,3},{2,4,5},{4,4,5}};
6.
7. //printing 2D array
8. for(int i=0;i<3;i++){
9. for(int j=0;j<3;j++){
10. System.out.print(arr[i][j]+" ");
11. }
12. System.out.println();
13. }
14.
15. }}
Test it Now

Output:1 2 3
2 4 5
4 4 5

What is the class name of java array?


In java, array is an object. For array object, an proxy class is created whose name can be obtained by
getClass().getName() method on the object.

1. class Testarray4{
2. public static void main(String args[]){
3.
4. int arr[]={4,4,5};
5.
6. Class c=arr.getClass();
7. String name=c.getName();
8.
9. System.out.println(name);
10.
11. }}
Test it Now

Output:I

Copying a java array


We can copy an array to another by the arraycopy method of System class.

Syntax of arraycopy method


1. public static void arraycopy(
2. Object src, int srcPos,Object dest, int destPos, int length
3. )

Example of arraycopy method


1. class TestArrayCopyDemo {
2. public static void main(String[] args) {
3. char[] copyFrom = { 'd', 'e', 'c', 'a', 'f', 'f', 'e',
4. 'i', 'n', 'a', 't', 'e', 'd' };
5. char[] copyTo = new char[7];
6.
7. System.arraycopy(copyFrom, 2, copyTo, 0, 7);
8. System.out.println(new String(copyTo));
9. }
10. }
Test it Now

Output:caffein

Addition of 2 matrices in java


Let's see a simple example that adds two matrices.

1. class Testarray5{
2. public static void main(String args[]){
3. //creating two matrices
4. int a[][]={{1,3,4},{3,4,5}};
5. int b[][]={{1,3,4},{3,4,5}};
6.
7. //creating another matrix to store the sum of two matrices
8. int c[][]=new int[2][3];
9.
10. //adding and printing addition of 2 matrices
11. for(int i=0;i<2;i++){
12. for(int j=0;j<3;j++){
13. c[i][j]=a[i][j]+b[i][j];
14. System.out.print(c[i][j]+" ");
15. }
16. System.out.println();//new line
17. }
18.
19. }}
Test it Now

Output:2 6 8
6 8 10
Wrapper class in Java
Wrapper class in java provides the mechanism to convert primitive into object and object into primitive.

Since J2SE 5.0, autoboxing and unboxing feature converts primitive into object and object into primitive
automatically. The automatic conversion of primitive into object is known and autoboxing and vice-versa
unboxing.

One of the eight classes of java.lang package are known as wrapper class 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

Wrapper class Example: Primitive to Wrapper


1. public class WrapperExample1{
2. public static void main(String args[]){
3. //Converting int into Integer
4. int a=20;
5. Integer i=Integer.valueOf(a);//converting int into Integer
6. Integer j=a;//autoboxing, now compiler will write Integer.valueOf(a) internally
7.
8. System.out.println(a+" "+i+" "+j);
9. }}

Output:

20 20 20

Wrapper class Example: Wrapper to Primitive


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

Output:

3 3 3
Call by Value and Call by Reference in Java
There is only call by value in java, not call by reference. If we call a method passing a value, it is known as
call by value. The changes being done in the called method, is not affected in the calling method.

Example of call by value in java

In case of call by value original value is not changed. Let's take a simple example:
1. class Operation{
2. int data=50;
3.
4. void change(int data){
5. data=data+100;//changes will be in the local variable only
6. }
7.
8. public static void main(String args[]){
9. Operation op=new Operation();
10.
11. System.out.println("before change "+op.data);
12. op.change(500);
13. System.out.println("after change "+op.data);
14.
15. }
16. }

Output:before change 50
after change 50

Another Example of call by value in java

In case of call by reference original value is changed if we made changes in the called method. If we pass
object in place of any primitive value, original value will be changed. In this example we are passing object
as a value. Let's take a simple example:

1. class Operation2{
2. int data=50;
3.
4. void change(Operation2 op){
5. op.data=op.data+100;//changes will be in the instance variable
6. }
7.
8.
9. public static void main(String args[]){
10. Operation2 op=new Operation2();
11.
12. System.out.println("before change "+op.data);
13. op.change(op);//passing object
14. System.out.println("after change "+op.data);
15.
16. }
17. }

Output:before change 50
after change 150
Java Strictfp Keyword
Java strictfp keyword ensures that you will get the same result on every platform if you perform operations in
the floating-point variable. The precision may differ from platform to platform that is why java programming
language have provided the strictfp keyword, so that you get same result on every platform. So, now you
have better control over the floating-point arithmetic.

Legal code for strictfp keyword

The strictfp keyword can be applied on methods, classes and interfaces.


1. strictfp class A{}//strictfp applied on class
1. strictfp interface M{}//strictfp applied on interface
1. class A{
2. strictfp void m(){}//strictfp applied on method
3. }

Illegal code for strictfp keyword

The strictfp keyword cannot be applied on abstract methods, variables or constructors.

1. class B{
2. strictfp abstract void m();//Illegal combination of modifiers
3. }
1. class B{
2. strictfp int data=10;//modifier strictfp not allowed here
3. }
1. class B{
2. strictfp B(){}//modifier strictfp not allowed here
3. }

Creating API Document | javadoc tool


We can create document api in java by the help of javadoc tool. In the java file, we must use the
documentation comment /**... */ to post information for the class, method, constructor, fields etc.

Let's see the simple class that contains documentation comment.

1. package com.abc;
2. /** This class is a user-defined class that contains one methods cube.*/
3. public class M{
4.
5. /** The cube method prints cube of the given number */
6. public static void cube(int n){System.out.println(n*n*n);}
7. }
To create the document API, you need to use the javadoc tool followed by java file name. There is no need to
compile the javafile.

On the command prompt, you need to write:

javadoc M.java

to generate the document api. Now, there will be created a lot of html files. Open the index.html file to get
the information about the classes.

Java Command Line Arguments


1. Command Line Argument
2. Simple example of command-line argument
3. Example of command-line argument that prints all the values

The java command-line argument is an argument i.e. passed at the time of running the java program.

The arguments passed from the console can be received in the java program and it can be used as an input.

So, it provides a convenient way to check the behavior of the program for the different values. You can
pass N (1,2,3 and so on) numbers of arguments from the command prompt.
Simple example of command-line argument in java

In this example, we are receiving only one argument and printing it. To run this java program, you must
pass at least one argument from the command prompt.
1. class CommandLineExample{
2. public static void main(String args[]){
3. System.out.println("Your first argument is: "+args[0]);
4. }
5. }
1. compile by > javac CommandLineExample.java
2. run by > java CommandLineExample sonoo

Output: Your first argument is: sonoo

Example of command-line argument that prints all the values

In this example, we are printing all the arguments passed from the command-line. For this purpose, we
have traversed the array using for loop.
1. class A{
2. public static void main(String args[]){
3.
4. for(int i=0;i<args.length;i++)
5. System.out.println(args[i]);
6.
7. }
8. }
1. compile by > javac A.java
2. run by > java A sonoo jaiswal 1 3 abc

Output: sonoo
jaiswal
1
3
ab

Difference between object and class


There are many differences between object and class. A list of differences between object and class are
given below:

No. Object Class

1) Object is an instance of a class. Class is a blueprint or


templatefrom which objects are
created.

2) Object is a real world entity such as pen, laptop, mobile, bed, Class is a group of similar
keyboard, mouse, chair etc. objects.

3) Object is a physical entity. Class is a logical entity.

4) Object is created through new keyword mainly e.g. Class is declared using class
Student s1=new Student(); keyword e.g.
class Student{}

5) Object is created many times as per requirement. Class is declared once.

6) Object allocates memory when it is created. Class doesn't allocated memory


when it is created.

7) There are many ways to create object in java such as new There is only one way to define
keyword, newInstance() method, clone() method, factory method class in java using class keyword.
and deserialization.

Difference between method overloading and method


overriding in java
There are many differences between method overloading and method overriding in java. A list of differences
between method overloading and method overriding are given below:

No. Method Overloading Method Overriding

1) Method overloading is used to increase the readability of the Method overriding is used to provide the
program. specific implementation of the method that
is already provided by its super class.

2) Method overloading is performed within class. Method overriding occurs in two


classesthat have IS-A (inheritance)
relationship.

3) In case of method overloading, parameter must be different. In case of method overriding, parameter
must be same.

4) Method overloading is the example of compile time Method overriding is the example of run
polymorphism. time polymorphism.

5) In java, method overloading can't be performed by changing Return type must be same or covariantin
return type of the method only. Return type can be same or method overriding.
different in method overloading. But you must have to
change the parameter.

Java Method Overloading example


1. class OverloadingExample{
2. static int add(int a,int b){return a+b;}
3. static int add(int a,int b,int c){return a+b+c;}
4. }

Java Method Overriding example


1. class Animal{
2. void eat(){System.out.println("eating...");}
3. }
4. class Dog extends Animal{
5. void eat(){System.out.println("eating bread...");}
6. }

You might also like