Java Notes
Java Notes
2. Translators:
Compilers
Interpreters
1. Loading:
2. Linking:
Verifying:
o Java bytecode is taken care off here
o It checks whether it is compatible with Java specification or not
o Usually ClassNotFound Exceptions are thrown here
Prepare:
o all the class data / variable are initialized to their default values here
o Ex: static int a = 5 is created in class but a is re initialized to default value i.e 0
Resolving
o loads reference objects and Variables
o Ex: bike class is having another class called owner now checks whether owner
class is defined or not
o Throws ClassDefNotFound Exception
3. Initializing:
o static block initiates first
o Original values are reassigned back
like a = 5
Execution Engine: Executes byte code info
1. JIT: whenever engine encounters same kind of instructions again and again
JIT compiles some part if code so perform is improved
JIT compiles converts the byte code into native code after compiling it
system used the native code directly
LANGUAGE BASICS :
Program 1
class Sample
{
public static void main(String[] args)
{
System.out.println("Hi all welcome to JAVA training");
}
}
/*
compilaction -> javac Sample.java -> .class file
execution -> java Sample
*/
Program 2
class Convertion
{
public static void main(String[] args)
{
System.out.println("Length of the String arrays is : "+args.length);
if(args.length==0)
{
System.out.println("array is empty");
}
else
{
}
}
}
/*
int arrays -> 1,2,3 -> length is 3 index 0 1 2
if an array length is 0 - means -> array is empty
length of an array -> arrayname.length
during execution command when i pass data then only it will be stored in string array
String to integer -> Integer.parseInt(name of string)
args[0] - 10
args[1]- 20
int var1 = Integer.parseInt(args[0]);
abc - args[0]
"123bc" "abc" "@#$" all these are strings
*/
Exercises on language basics:
1. Write a Program that accepts two Strings as command line arguments and generate the output
in a specific way as given below.
Example:
If the command line arguments are ABC and Mumbai then the output generated should be ABC
Technologies Mumbai
[Note: It is mandatory to pass two arguments in command line]
public class Command
{
public static void main(String args[])
{
System.out.println(args[0] + " Technologies " + args[1]);
}
}
//For output Wipro Technologies Banglore
2. Write a Program to accept a String as a Command line argument and the program should print a
Welcome message.
Example:
C:\> java Sample John
O/P Expected: Welcome John
class Simple
{
public static void main(String args[])
{
System.out.println("Welcome"+ args[0]);
}
}
3. Write a Program to accept two integers through the command line argument and print the sum
of the two numbers
Example:
C:\>java Sample 10 20
O/P Expected: The sum of 10 and 20 is 30
public class SumCommand
{
public static void main(String args[])
{
int x = Integer.parseInt(args[0]); //first arguments
int y = Integer.parseInt(args[1]); //second arguments
int sum = x + y;
System.out.println("The sum of x and y is: " +sum);
}
}
else
{
System.out.println("The number is zero.");
}
}
}
2. Write a program to check if a given number is odd or even.
import java.util.Scanner;
public class Odd_Even
{
public static void main(String[] args)
{
int n;
Scanner s = new Scanner(System.in);
System.out.print("Enter the number you want to check:");
n = s.nextInt();
if(n % 2 == 0)
{
System.out.println("The given number "+n+" is Even ");
}
else
{
System.out.println("The given number "+n+" is Odd ");
}
}
}
3. Write a program to check if the program has received command line arguments or not. If the
program has not received the values then print "No Values", else print all the values in a
single line separated by ,(comma).
Eg1) java Example
O/P: No values
Eg2) java Example Mumbai Bangalore
O/P: Mumbai, Bangalore
[Note: You can use length property of an array to check its length.
class Example
{
public static void main(String[] args)
{
if(args.length== 0)
{
System.out.println("No values");
}
else
{
for(String i : args)
System.out.print(i+ " , ");
}
}
}
4. Initialize two character variables in a program and display the characters in alphabetical
order.
Eg1) if first character is s and second is e
O/P: e,s
Eg2) if first character is a and second is e
O/P:a,e
class Alphabet
{
public static void main (String[] args)
{
char item1='s';
char item2='e';
if (item1>item2)
{
System.out.println(item2+" , "+item1);
}
else
{
System.out.println(item1+" , "+item2);
}
}
}
5. Initialize a character variable in a program and if the value is alphabet then print "Alphabet"
if it’s a number then print "Digit" and for other characters print "Special Character"
class CheckValue
{
public static void main (String[] args)
{
char item1='1'; //here the initialization is carried out
if((item1>96&&item1<123)||(item1>64&&item1<91))
System.out.println("Alphabet");
else if(item1>47&&item1<58)
System.out.println("Digit");
else
System.out.println("Special Character");
}
}
6. Write a program to accept gender ("Male" or "Female") and age (1-120) from command line
arguments and print the percentage of interest based on the given conditions.
Interest == 8.2%
Gender ==> Female
Age ==>1 to 58
Interest == 7.6%
Gender ==> Female
Age ==>59 -120
Interest == 9.2%
Gender ==> Male
Age ==>1-60
Interest == 8.3%
Gender ==> Male
Age ==>61-120
if(c>='a'&&c<='z')
{
System.out.println(c+"->");
i=(int)c;
c=(char)(i-32);
System.out.println(c);
}
else
{
System.out.println(c+"->");
i=(int)c;
c=(char)(i+32);
System.out.println(c);
}
}
}
8. Write a program to print the color name, based on color code. If color code in not valid then
print "Invalid Code". R->Red, B->Blue, G->Green, O->Orange, Y->Yellow, W->White.
import java.util.Scanner;
public class ColorCode
{
public static void main(String args[])
{
Scanner in = new Scanner(System.in);
System.out.println("Enter color code:");
char code = in.next().charAt(0);
switch(code)
{
case 'R':
System.out.println("Red");
break;
case 'B':
System.out.println("Blue");
break;
case 'G':
System.out.println("Green");
break;
case 'O':
System.out.println("Orange");
break;
case 'Y':
System.out.println("Yellow");
break;
case 'W':
System.out.println("White");
break;
default:
System.out.println("Invalid code");
break;
}
}
}
9. Write a program to print month in words, based on input month in numbers
Example1:
C:\>java Sample 12
O/P Expected: December
class MonthName
{
public static void main(String args[])
{
int number = Integer.parseInt(args[0]);
switch(number)
{
case 1:
System.out.println("January");
break;
case 2:
System.out.println("February");
break;
case 3:
System.out.println("March");
break;
case 4:
System.out.println("April");
break;
case 5:
System.out.println("May");
break;
case 6:
System.out.println("June");
break;
case 7:
System.out.println("July");
break;
case 8:
System.out.println("August");
break;
case 9:
System.out.println("September");
break;
case 10:
System.out.println("October");
break;
case 11:
System.out.println("November");
break;
case 12:
System.out.println("December");
break;
default:
System.out.println("Invalid");
break;
}
}
}
Example2:
C:\>java Sample
O/P Expected: Please enter the month in numbers
import java.util.Scanner;
public class Month
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
System.out.println("Please enter the months in numbers:");
int number= sc.nextInt();
switch(number)
{
case 1:
System.out.println("January");
break;
case 2:
System.out.println("February");
break;
case 3:
System.out.println("March");
break;
case 4:
System.out.println("April");
break;
case 5:
System.out.println("May");
break;
case 6:
System.out.println("June");
break;
case 7:
System.out.println("July");
break;
case 8:
System.out.println("August");
break;
case 9:
System.out.println("September");
break;
case 10:
System.out.println("October");
break;
case 11:
System.out.println("November");
break;
case 12:
System.out.println("December");
break;
default:
System.out.println("Invalid");
break;
}
}
}
Example3:
C:\>java Sample 15
O/P Expected: Invalid month
public class Month2
{
public static void main(String args[])
{
int number = Integer.parseInt(args[0]);
switch(number)
{
case 1:
System.out.println("January");
break;
case 2:
System.out.println("February");
break;
case 3:
System.out.println("March");
break;
case 4:
System.out.println("April");
break;
case 5:
System.out.println("May");
break;
case 6:
System.out.println("June");
break;
case 7:
System.out.println("July");
break;
case 8:
System.out.println("August");
break;
case 9:
System.out.println("September");
break;
case 10:
System.out.println("October");
break;
case 11:
System.out.println("November");
break;
case 12:
System.out.println("December");
break;
default:
System.out.println("Invalid month");
break;
}
}
}
10. Write a program to print numbers from 1 to 10 in a single row with one tab space.
public class Tabspace
{
public static void main(String args[])
{
int i;
for(i=1;i<=10;i++)
{
System.out.print(i+" ");
}
}
11. Write a program to print even numbers between 23 and 57, each number should be printed in a
separate row.
public class Even
{
public static void main(String[] args)
{
int i;
for(i=23;i<=57;i++)
{
if(i%2==0)
{
System.out.println(i);
}
}
}
}
12. Write a program to check if a given number is prime or not.
public class prime
{
public static void main(String args[])
{
int i,m=0,flag=0;
int n=3;
m=n/2;
if(n==0 || n==1)
{
System.out.println(n+ "is not prime number");
}
else
{
for(i=2;i<=m;i++)
{
if(n%i == 0)
{
System.out.println(n+ "is not prime number");
flag=1;
break;
}
}
if(flag ==0)
{
System.out.println(n+ "is prime number");
}
}
}
}
13. Write a program to print prime numbers between 10 and 99.
public class Prime1
{
public static void main(String arg[])
{
int i,count;
System.out.println("Prime numbers between 1 to 100 are ");
for(int j=10;j<=99;j++)
{
count=0;
for(i=1;i<=j;i++)
{
if(j%i==0)
{
count++;
}
}
if(count==2)
System.out.print(j+" ");
}
}
}
15. Write a program to add all the values in a given number and print. Ex: 1234->10
import java.util.Scanner;
public class Sum
{
public static void main(String arg[])
{
long number = 1234;
long sum;
for(sum=0; number!=0; number=number/10)
{
sum = sum + number % 10;
}
System.out.println("Sum of digits: "+sum);
}
}
16. Write a program to print * in Floyds format (using for and while loop)
*
* *
* * *
Example1:
C:\>java Sample
O/P Expected : Please enter an integer number
import java.util.Scanner;
public class Firstpattern
{
public static void main(String args[])
{
int i, j, n;
Scanner sc=new Scanner(System.in);
System.out.println("Please enter an integer number");
n=sc.nextInt();
for(i=0; i<n; i++)
{
for(j=0; j<=i; j++)
{
System.out.print("* ");
}
System.out.println();
}
}
}
Example2:
C:\>java Sample 3
O/P Expected :
*
* *
* * *
public class Firstpattern2
{
public static void main(String args[])
{
int i, j;
int n = Integer.parseInt(args[0]);
for(i=0; i<n; i++)
{
for(j=0; j<=i; j++)
{
System.out.print("* ");
}
System.out.println();
}
}
}
17. Write a program to reverse a given number and print
Eg1)
I/P: 1234
O/P: 4321
public class Reverse
{
public static void main(String[] args)
{
int number = 1234, reverse = 0;
for( ;number != 0; number=number/10)
{
int remainder = number % 10;
reverse = reverse * 10 + remainder;
}
System.out.println("The reverse of the given number is: " + reverse);
}
}
Eg2)
I/P: 1004
O/P: 4001
Give number =1004 in above program.
18. Write a Java program to find if the given number is palindrome or not
Example1:
C:\>java Sample 110011
O/P Expected : 110011 is a palindrome
Example2:
C:\>java Sample 1234
O/P Expected : 1234 is not a palindrome.
class Palindrome
{
public static void main(String args[])
{
long r,sum=0;
long temp;
long n = Long.parseLong(args[0]);
temp=n;
while(n>0)
{
r=n%10;
sum=(sum*10)+r;
n=n/10;
}
if(temp==sum)
System.out.println(n+" is a palindrome number ");
else
System.out.println("not palindrome");
}
}
19. Write a program to print first 5 values which are divisible by 2, 3, and 5.
class Divisible
{
public static void main(String []args)
{
int N = 150;
for (int num = 0; num < N; num++)
{
if (num%2 ==0 && num % 3 == 0 && num % 5 == 0)
{
System.out.print(num + " ");
}
}
}
}
20. Write a program that displays a menu with options 1. Add 2. Sub
Based on the options chosen, read 2 numbers and perform the relevant operation. After performing
the operation, the program should ask the user if he wants to continue. If the user presses y or Y,
then the program should continue displaying the menu else the program should terminate.
[ Note: Use Scanner class ]
import java.io.*;
import java.util.*;
public class DisplayMenu
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println("1:ADD");
System.out.println("2:SUB");
String str = "";
int ans;
do
{
System.out.println("Enter your choice");
int choice = sc.nextInt();
System.out.println("Enter two numbers:");
int n1 = sc.nextInt();
int n2 = sc.nextInt();
if(choice == 1)
{
ans = n1+n2;
System.out.println("Addition is " +ans);
}
else
{
ans = n1-n2;
System.out.println("Subtraction is" +ans);
}
System.out.println("Do you want to continue : Y/N");
str = sc.next();
}while(str.equalsIgnoreCase("y"));
}
}
ARRAYS:
Normally, an array is a collection of similar type of elements which has contiguous
memory location.
Java array is an object which contains elements of a similar data type. Additionally, The
elements of an array are stored in a contiguous memory location. It is a data structure
where we store similar elements. We can store only a fixed set of elements in a Java
array.
In Java, array is an object of a dynamically generated class. Java array inherits the Object
class, and implements the Serializable as well as Cloneable interfaces. We can store
primitive values or objects in an array in Java. Like C/C++, we can also create single
dimentional or multidimentional arrays in Java.
Advantages
Code Optimization: It makes the code optimized, we can retrieve or sort the
data efficiently.
Random access: We can get any data located at an index position.
Disadvantages
Size Limit: We can store only the 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 which grows automatically.
Types of Array in java
There are two types of array.
1. dataType[] arr; (or)
2. dataType []arr; (or)
3. dataType arr[];
Syntax to Declare an Array in Java(single dimensional):
1. dataType[][] arrayRefVar; (or)
2. dataType [][]arrayRefVar; (or)
3. dataType arrayRefVar[][]; (or)
4. dataType []arrayRefVar[];
Exercises on Array
1.Write a program to initialize an integer array and print the sum and average of the array
}
4. Initialize an integer array with ascii values and print the corresponding character values in a
single row.
public class AsciiValue
{
public static void main(String[] args)
{
int arr[] = {66,71,76,82,88,99};
for (int i=0; i<arr.length; i++)
{
System.out.print((char)arr[i]+" ");
}
System.out.println();
}
}
5. Write a program to find the largest 2 numbers and the smallest 2 numbers in the given array.
import java.util.Scanner;
public class TwoLargestSmallest
{
public static void main (String[] args)
{
Scanner sc = new Scanner (System.in);
System.out.print("Enter no. of elements you want in array:");
Int n = sc.nextInt();
int array[] = new int[n];
System.out.println("Enter all the elements:");
for (int i = 0; i < array.length; i++)
{
array[i] = scn.nextInt();
}
int largest1, largest2, temp;
largest1 = array[0];
largest2 = array[1];
if (largest1 < largest2)
{
temp = largest1;
largest1 = largest2;
largest2 = temp;
}
for (int i = 2; i < array.length; i++)
{
if (array[i] > largest1)
{
largest2 = largest1;
largest1 = array[i];
}
else if (array[i] > largest2 && array[i] != largest1)
{
largest2 = array[i];
}
}
System.out.println ("The First largest is " + largest1);
System.out.println ("The Second largest is " + largest2);
int smallest1, smallest2;
smallest1 = array[0];
smallest2 = array[1];
if (smallest1 > smallest2)
{
temp = smallest1;
smallest1 = smallest2;
smallest2 = temp;
}
for (int i = 2; i < array.length; i++)
{
if (array[i] < smallest1)
{
smallest2 = smallest1;
smallest1 = array[i];
}
else if (array[i] < smallest2 && array[i] != smallest1)
{
smallest2 = array[i];
}
}
System.out.println ("The First smallest is " + smallest1);
System.out.println ("The Second smallest is " + smallest2);
}
}
6. Write a program to initialize an array and print them in a sorted fashion.
public class ArraySort
{
public static void main(String[] args)
{
int [] arr = new int [] {5, 2, 8, 7, 1};
int temp = 0;
System.out.println("Elements of original array: ");
for (int i = 0; i < arr.length; i++)
{
System.out.print(arr[i] + " ");
}
for (int i = 0; i < arr.length; i++)
{
for (int j = i+1; j < arr.length; j++)
{
if(arr[i] > arr[j])
{
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
System.out.println();
System.out.println("Elements of array sorted in ascending order: ");
for (int i = 0; i < arr.length; i++)
{
System.out.print(arr[i] + " ");
}
}
}
7. Write a program to remove the duplicate elements in an array and print the same.
Example:
I/P : {12,34,12,45,67,89}
O/P : {12,34,45,67,89}
public class DuplicateElements
{
public static int removeDuplicateElements(int arr[], int n)
{
if (n==0 || n==1)
{
return n;
}
int[] temp = new int[n];
int j = 0;
for (int i=0; i<n-1; i++)
{
if (arr[i] != arr[i+1])
{
temp[j++] = arr[i];
}
}
temp[j++] = arr[n-1];
for (int i=0; i<j; i++)
{
arr[i] = temp[i];
}
return j;
}
public static void main (String[] args)
{
int arr[] = {12,34,12,45,67,89};
int length = arr.length;
length = removeDuplicateElements(arr, length);
for (int i=0; i<length; i++)
{
System.out.print(arr[i]+" ");
}
}
}
8. Write a program to print the element of an array that has occurred the highest number of times
Example:
Array -> 10,20,10,30,40,100,99
import java.util.*;
public class MaxCount
{
public static void main(String args[])
{
int arr[]={10,20,10,30,40,100,99};
int maxcounter=0;
int count = 1;
int element =0;
for(int i=0;i<arr.length;i++)
{
for(int j=i+1;j<arr.length;j++)
{
if(arr[i]==arr[j])
{
count++;
}
}
if(maxcounter<count)
{
maxcounter = count;
element = arr[i];
}
}
System.out.println("The element which occurs maximum times is:" +element);
}
}
9.Write a program to print the sum of the elements of the array with the given below condition if the
array has 6 and 7 in succedding orders, ignore 6 and 7 and the numbers between them for the
calculation of sum.
import java.util.*;
public class SumCondition67
{
public static void main(String args[])
{
int arr[] = {1,6,4,7,9};
int sum = 0;
int m=0;
int n=0;
for(int i=0;i<arr.length;i++)
{
if(arr[i] == 6)
{
m = i;
}
if(arr[i] == 7)
{
n = i;
}
}
for(int j=0;j<arr.length;j++)
{
if(!(n>=j&&j>=m) && j<arr.length)
{
sum = sum + arr[j];
}
}
System.out.println("The sum of array elements with condition is:" + sum);
}
}
PACKAGE IN JAVA
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.
1) Java package is used to categorize the classes and interfaces so that they can
be easily maintained.
There are three ways to access the package from outside the package.
1. import package.*;
2. import package.classname;
3. fully qualified name.
package mypack;
import pack.A;
class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
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.
Understanding java access modifiers
OOPS CONCEPTS
Object
Any entity that has state and behavior is known as an object. For example, a chair, pen,
table, keyboard, bike, etc. It can be physical or logical.
An Object can be defined as an instance of a class. An object contains an address and
takes up some space in memory.
Class
Collection of objects is called class. It is a logical entity.
A class can also be defined as a blueprint from which you can create an individual object.
Class doesn't consume any space.
Inheritance
Inheritance in Java is a mechanism in which one object acquires all the properties and
behaviors of a parent object. It is an important part of OOPs (Object Oriented
programming system).
Inheritance represents the IS-A relationship which is also known as a parent-
child relationship.
The extends keyword indicates that you are making a new class that derives from an
existing class. The meaning of "extends" is to increase the functionality.
Types of Inheritance:
1. Single Inheritance:
When a class inherits another class, it is known as a single inheritance. In the
example given below, Dog class inherits the Animal class, so there is the single
inheritance.
Example :
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class TestInheritance{
public static void main(String args[]){
Dog d=new Dog();
d.bark();
d.eat();
}}
2. Multilevel Inheritance:
When there is a chain of inheritance, it is known as multilevel inheritance. As you
can see in the example given below, BabyDog class inherits the Dog class which
again inherits the Animal class, so there is a multilevel inheritance.
Example:
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");} }
class BabyDog extends Dog{
void weep(){System.out.println("weeping...");}
}
class TestInheritance2{
public static void main(String args[]){
BabyDog d=new BabyDog();
d.weep();
d.bark();
d.eat();
}}
3. Hierarchical Inheritance:
When two or more classes inherits a single class, it is known as hierarchical
inheritance. In the example given below, Dog and Cat classes inherits the Animal
class, so there is hierarchical inheritance.
Example:
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class Cat extends Animal{
void meow(){System.out.println("meowing...");}
}
class TestInheritance3{
public static void main(String args[]){
Cat c=new Cat();
c.meow();
c.eat();
//c.bark();//C.T.Error
}}
4. Multiple Inheritance:
To reduce the complexity and simplify the language, multiple inheritance is not
supported in java.
Example:
class A{
void msg(){System.out.println("Hello");}
}
class B{
void msg(){System.out.println("Welcome");}
}
class C extends A,B{//suppose if it were
public static void main(String args[]){
C obj=new C();
obj.msg();//Now which msg() method would be invoked?
}
}
Polymorphism
Polymorphism in Java is a concept by which we can perform a single action in different
ways. Polymorphism is derived from 2 Greek words: poly and morphs. The word "poly"
means many and "morphs" means forms. So polymorphism means many forms.
There are two types of polymorphism in Java: compile-time polymorphism and
runtime polymorphism. We can perform polymorphism in java by method
overloading and method overriding.
If you overload a static method in Java, it is the example of compile time polymorphism.
Compile time polymorphism-Method Overloading
package pack3;
public class Program1 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Calculator c = new Calculator();
c.add(5, 6);
c.add(2.4, 5.6);
System.out.println(c.add(1, 3, 3.5));
c.add(4, 6, 9);
}
}
class Calculator
{
void add(int a , int b)
{
System.out.println("sum 2 of integers : "+(a+b));
}
void add(int a , int b, int c)
{
System.out.println("sum 3 of integers : "+(a+b+c));
}
void add(double a , double b)
{
System.out.println("sum of 2 double data type : "+(a+b));
}
int add(int a , int b ,double c)
{
return (int)(a+b+c);
}
}
Runtime Polyphormism – Over riding
package pack3;
public class Program2 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Dog d = new Dog();
d.eat();
}
}
// static methods cannot be over rided because there are called with class names
class Animal
{
void eat()
{
System.out.println("Animal is eating");
}
static void display()
{
}
}
class Dog extends Animal
{
void eat()
{
super.eat();
System.out.println("Dog is eating");
}
static void display()
{
}
}
Abstraction
Abstraction is a process of hiding the implementation details and showing only
functionality to the user.
Another way, it shows only essential things to the user and hides the internal
details, for example, sending SMS where you type the text and send the message.
You don't know the internal processing about the message delivery.
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 a fully encapsulated class.
Advantages of Encapsulation:
It provides you the control over the data.
It is a way to achieve data hiding in Java because other class will not be able to
access the data through the private data members.
The encapsulate class is easy to test. So, it is better for unit testing.
//A Java class which is a fully encapsulated class.
//It has a private data member and getter and setter methods.
package com.javatpoint;
public class Student{
//private data member
private String name;
//getter method for name
public String getName(){
return name;
}
//setter method for name
public void setName(String name){
this.name=name
}
}
//FileName:Test.java
/A Java class to test the encapsulated class.
package com.javatpoint;
class Test{
public static void main(String[] args){
//creating instance of the encapsulated class
Student s=new Student();
//setting value in the name member
s.setName("vijay");
//getting value of the name member
System.out.println(s.getName());
}
}
GET AND SET:
The private variables can only be accessed within the same class
(an outside class has no access to it). However, it is possible to
access them if we provide public get and set methods.
The get method returns the variable value, and the set method
sets the value.
Example:
// Getter
return name;
// Setter
this.name = newName;
System.out.println(myObj.getName());