java_part-2
java_part-2
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.
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.
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. }
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.
The protected access modifier can be applied on the data member, method and constructor. It can't be
applied on the class.
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
Output:Hello
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
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.
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.
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.
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 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.
The clone() method is defined in the Object class. Syntax of the clone() method is as follows:
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.
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.
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
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
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
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
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
Output:caffein
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
Output:
20 20 20
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.
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
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.
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. }
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.
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.
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
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
2) Object is a real world entity such as pen, laptop, mobile, bed, Class is a group of similar
keyboard, mouse, chair etc. objects.
4) Object is created through new keyword mainly e.g. Class is declared using class
Student s1=new Student(); keyword e.g.
class Student{}
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.
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.
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.