Object Oriented Programming with JAVA (4341602)| Unit-2
Unit– II: Object Oriented Programming Concepts (CO1) (12 Marks)
Class
A class is a template or blueprint that specifies the attributes and behavior of things or objects. It is
a logical entity. It can't be physical. No memory is allocated for them.
Class is derived or abstract datatype; it combines members of different datatypes into one.
For Example: Car, College, Bus etc.
This new datatype can be used to create objects.
A class is a template for an object.
A class in Java can contain:
o Fields (Data members)
o Methods
o Constructors
o Blocks
o Nested class and interface
Syntax to declare a class:
class <class_name>{
field;
method;
}
Syntax:
class classname
{
Datatype variable1;
Datatype variable2;
// ...
Datatype variableN;
return_type methodname1(parameter-list)
{
// body of method
}
return_type methodnameN(parameter-list)
{
// body of method
}
}
Department of Information Technology [Ms. N. A. Patel & Mrs. A. K. Virani] 1
Object Oriented Programming with JAVA (4341602)| Unit-2
Instance variable - A variable which is created inside the class but outside the method is known as
an instance variable. Instance variable doesn't get memory at compile time. It gets memory at runtime
when an object or instance is created. That is why it is known as an instance variable.
Method - Method is a collection of instructions that performs a specific task. It provides the
reusability of code. We write a method once and use it many times.
Syntax:
access_specifier return_type method_name(argument_list)
{
// code
}
o Access Specifier: Access specifier or modifier is the access type of the method. It specifies the
visibility of the method. Public, Private, Protected, Default
o Return Type: Return type is a data type that the method returns. It may have a primitive data
type, object, collection, void, etc. If the method does not return anything, we use void keyword.
o Method Name: It is a unique name that is used to define the name of a method.
o Parameter List: It is the list of parameters separated by a comma and enclosed in the pair of
parentheses. It contains the data type and variable name. If the method has no parameter, left the
parentheses blank.
o Method Body: It is a part of the method declaration. It contains all the actions to be performed.
It is enclosed within the pair of curly braces.
Return value - Method that have a return type other than void return a value to the calling method using
the following form of the return statement:
Syntax: return value;
Example,
class demo1 {
int add(int n1, int n2) {
int a;
a = n1 + n2;
return a; //returning the sum
}
}
Method Call
Syntax: var_name = object_name.method_name(parameter-list);
Example, int sum=d.add(10,20);
Department of Information Technology [Ms. N. A. Patel & Mrs. A. K. Virani] 2
Object Oriented Programming with JAVA (4341602)| Unit-2
Write a program and explain how to create class and object. 04
Creating objects
An object is an instance of a class.
An object has a state and behavior, Identity.
It can be physical or logical.
Example: chair, bike, marker, pen, table, car, etc.
The state of an object is stored in fields (variables), while methods (functions) display the object's
behavior.
Creating Object & Accessing members:
new keyword creates new object. The new operator dynamically (run time) allocates memory for an
object and returns a reference to it.
Syntax: ClassName objName = new ClassName();
Example, demo1 d = new demo1();
Dot Operator: The dot is used to obtain the value of the object. Object variables and methods can be
accessed using the dot (.) operator
Syntax: objName.variableName=value;
Example, d.i = 10;
Example,
class demo1 {
int i; // instance variable
void display() {
System.out.println("i=" + i);
}
int add(int n1, int n2) {
int a; // local variable
a = n1 + n2;
return a; //returning the sum
}
}
class demo {
public static void main(String args[]) {
demo1 d = new demo1();
d.i = 10;
d.display();
Department of Information Technology [Ms. N. A. Patel & Mrs. A. K. Virani] 3
Object Oriented Programming with JAVA (4341602)| Unit-2
int sum=d.add(10,20);
System.out.println("Addition="+sum);
}
}
Output:
i=10
Addition=30
Passing and Returning object from Method
In java, you can pass object as parameter to method. A method can return any type of data including
class types that you create.
Example,
public class MethodReturn {
int i = 10;
int demo(MethodReturn m1) {
return m1.i;
}
public static void main(String[] args) {
MethodReturn m = new MethodReturn();
System.out.println("Used passing and return objects:" + m.demo(m));
}
}
Output: Used passing and return objects:10
What is method overloading? Explain with example. 07 – Winter-2023
Method overloading
If class have multiple methods with same name but different parameters is known as Method
Overloading.
Method overloading is also known as compile time (static) polymorphism.
Overloading allows different methods to have same name, but different signatures.
Signature can differ by number of input parameters or type of input parameters or both.
However, the two functions with the same name must differ in at least one of the following,
o The number of parameters
o The data type of parameters
o The order of parameter
Department of Information Technology [Ms. N. A. Patel & Mrs. A. K. Virani] 4
Object Oriented Programming with JAVA (4341602)| Unit-2
Example,
class OverloadingDemo {
//Method Overloading
void sum(int a, int b) {
System.out.println("Sum of (a+b) is:: " + (a + b));
}
void sum(int a, int b, int c) {
System.out.println("Sum of (a+b+c) is:: " + (a + b + c));
}
void sum(double a, double b) {
System.out.println("Sum of double (a+b) is:: " + (a + b));
}
public static void main(String args[]) {
OverloadingDemo o1 = new OverloadingDemo();
o1.sum(10, 10); // call method1
o1.sum(10, 10, 10); // call method2
o1.sum(10.5, 10.5); // call method3
}
}
Output:
Sum of (a+b) is:: 20
Sum of (a+b+c) is:: 30
Sum of double (a+b) is:: 21.0
What is constructor? Explain parameterized constructor with example. 07 – Winter-2023
Define: Constructor. List out types of it. Explain Parameterized and copy constructor with
suitable example. 07 – Summer-2023, 2024, Winter-2024
Constructors
A constructor is a “special” member method which initializes the objects of class.
Properties of constructor:
o Constructor is invoked automatically whenever an object of class is created.
o Constructor name must be same as class name.
o Constructors do not have return types and they cannot return values, not even void.
o All classes have constructors by default: if you do not create a class constructor yourself, Java
creates one for you. However, then you are not able to set initial values for object attributes.
Department of Information Technology [Ms. N. A. Patel & Mrs. A. K. Virani] 5
Object Oriented Programming with JAVA (4341602)| Unit-2
Types of Constructor
1. Default Constructor
2. Parameterized Constructor
3. Copy Constructor
1. Default constructors - A constructor that has no parameter is known as default constructor.
Default constructor is the one which invokes by default when object of the class is created.
It is generally used to initialize the default value of the data members.
It is also called no argument constructor.
We can create an object using default constructor as:
new class_name();
Example,
public class ConstDemo {
int id;
String name;
ConstDemo() { //Default Constructor
System.out.println("Inside default constructor");
id = 1;
name = "Rahul";
}
void display() { //method to display the value of id and name
System.out.println(id + " " + name);
}
public static void main(String args[]) {
ConstDemo s1 = new ConstDemo(); //creating objects
s1.display(); //displaying values of the object
}
}
Output:
Inside default constructor
1 Rahul
2. Parameterized constructors - Constructors that can take arguments are called parameterized
constructors.
It is used to provide different values to the distinct objects.
Department of Information Technology [Ms. N. A. Patel & Mrs. A. K. Virani] 6
Object Oriented Programming with JAVA (4341602)| Unit-2
It is required to pass parameters on creation of objects.
If we define only parameterized constructors, then we cannot create an object with default constructor.
This is because compiler will not create default constructor. You need to create default constructor
explicitly.
Example,
public class ConstDemo {
int id;
String name;
ConstDemo(int i, String n) { //Parameterized Constructor
System.out.println("Inside Parameterized constructor");
id = i;
name = n;
}
void display() { //method to display the value of id and name
System.out.println(id + " " + name);
}
public static void main(String args[]) {
ConstDemo s2 = new ConstDemo(2, "Diya");
s2.display();
}
}
Output:
Inside Parameterized constructor
2 Diya
3. Copy constructors
A copy constructor is used to initialize an object from another object.
Copy constructor takes object as argument.
A copy constructor is used to create another object that is a copy of the object that it takes as a
parameter. But, the newly created copy is totally independent of the original object.
It is independent in the sense that the copy is located at different address in memory than the original.
There are many ways to copy the values of one object into another in Java. They are:
o By constructor
o By assigning the values of one object into another
o By clone() method of Object class
Department of Information Technology [Ms. N. A. Patel & Mrs. A. K. Virani] 7
Object Oriented Programming with JAVA (4341602)| Unit-2
Example,
class ConstDemo {
int id;
String name;
ConstDemo(int i, String n) { //Parameterized Constructor
System.out.println("Inside Parameterized constructor");
id = i;
name = n;
}
ConstDemo(ConstDemo c) { //Copy Constructor
System.out.println("Inside Copy constructor");
id = c.id;
name = c.name;
}
void display() { //method to display the value of id and name
System.out.println(id + " " + name);
}
public static void main(String args[]) {
ConstDemo s2 = new ConstDemo(2, "Diya");
s2.display();
ConstDemo s3 = new ConstDemo(s2);
s3.display();
}
}
Output:
Inside Parameterized constructor
2 Diya
Inside Copy constructor
2 Diya
Private constructor - Java allows us to declare a constructor as private. We can declare a constructor
private by using the private access specifier.
Note that if a constructor is declared private, we are not able to create an object of the class. Instead, we
can use this private constructor in Singleton Design Pattern.
Rules for Private Constructor
Department of Information Technology [Ms. N. A. Patel & Mrs. A. K. Virani] 8
Object Oriented Programming with JAVA (4341602)| Unit-2
The following rules keep in mind while dealing with private constructors.
o It does not allow a class to be sub-classed.
o It does not allow to create an object outside the class.
o If a class has a private constructor and when we try to extend the class, a compile-time error
occurs.
o We cannot access a private constructor from any other class.
o If all the constant methods are there in our class, we can use a private constructor.
Explain constructor overloading with example. 07 – Summer-2024
Constructor Overloading
Constructor overloading is just like as the method overloading.
Method overloading is also known as compile time (static) polymorphism.
When any object created, it will execute the constructor, which matches number of input parameters or
type of input parameters or both.
Constructor overloading is a technique of having more than one constructor with different parameter
lists, so that each constructor performs a different task. They are differentiated by the compiler by the
number of parameters in the list and their types.
Example,
class ConstDemo {
int id;
String name;
int age;
//Constructor Overloading
ConstDemo() { //Default Constructor
System.out.println("Inside default constructor");
id = 1;
name = "Rahul";
}
ConstDemo(int i, String n) { //Parameterized Constructor
System.out.println("Inside Parameterized constructor");
id = i;
name = n;
}
ConstDemo(int i, String n, int a) { //Parameterized Constructor
System.out.println("Inside Parameterized constructor");
Department of Information Technology [Ms. N. A. Patel & Mrs. A. K. Virani] 9
Object Oriented Programming with JAVA (4341602)| Unit-2
id = i;
name = n;
age = a;
}
void display() { //method to display the value of id and name
System.out.println(id + " " + name+ " "+age);
}
public static void main(String args[]) {
ConstDemo s1 = new ConstDemo(); //creating objects
s1.display(); //displaying values of the object
ConstDemo s2 = new ConstDemo(2, "Diya");
s2.display();
ConstDemo s3 = new ConstDemo(3, "Rahul", 18);
s3.display();
}
}
Output:
Inside default constructor
1 Rahul 0
Inside Parameterized constructor
2 Diya 0
Inside Parameterized constructor
3 Rahul 18
Difference between constructor and method in Java.
Constructor Method
A constructor is used to initialize the state of an A method is used to expose the behaviour of an
object. object.
A constructor must not have a return type. A method must have a return type.
The constructor is invoked implicitly. The method is invoked explicitly.
The Java compiler provides a default constructor if The method is not provided by the compiler in
you don't have any constructor in a class. any case.
The constructor name must be same as the class The method name may or may not be same as the
name. class name.
Department of Information Technology [Ms. N. A. Patel & Mrs. A. K. Virani] 10
Object Oriented Programming with JAVA (4341602)| Unit-2
Explain this keyword with suitable example. 04 – Summer-2023, 2024
this keyword - this is a reference variable that refers to the current object.
Sometimes a method will need to refer to the object that invoked it.
To allow this, Java defines this keyword. this keyword can be used inside any method or constructor of
class to refer to the current object.
We cannot create two Instance/Local variables with same name. But it is legal to create one instance
variable & one local variable or method parameter with same name.
Local Variable will hide the instance variable which is called Variable Hiding.
this keyword can be used to refer current class instance variable. If there is ambiguity between the
instance variables and parameters, this keyword resolves the problem of ambiguity.
this can be used to invoke current object's method.
this() can be used to invoke current class constructor.
this can be passed as a parameter to constructor and method call.
Example1,
class DemoThis {
int i = 5; // instance variable
void method() {
int i = 40; // local variable
System.out.println("Value of Instance variable :" + this.i); // Access instance variable
System.out.println("Value of Local variable :" + i); // Access local variable
}
public static void main(String args[]) {
DemoThis a1 = new DemoThis();
a1.method();
}
}
Output:
Value of Instance variable :5
Value of Local variable :40
Example2,
class ThisDemo1 {
int rollno;//instance variable
String name;
String college = "TDEC";
Department of Information Technology [Ms. N. A. Patel & Mrs. A. K. Virani] 11
Object Oriented Programming with JAVA (4341602)| Unit-2
ThisDemo1(int rollno, String name) { //constructor
this.rollno = rollno;
this.name = name;
}
//method to display the values
void display() {
System.out.println(rollno + " " + name + " " + college);
}
}
class ThisDemo {
public static void main(String args[]) {
ThisDemo1 t1 = new ThisDemo1(1, "Rahul");
ThisDemo1 t2 = new ThisDemo1(2, "Aryan");
t1.display();
t2.display();
}
}
Output:
1 Rahul TDEC
2 Aryan TDEC
Explain static keyword with example. 03 – Winter-2023, 2024, Summer-2023, 2024
static keyword - static keyword is mainly used for memory management.
When a member is declared static, it can be accessed before any objects of its class are created, and
without reference to any object.
It can be used with
o Variables
o Methods
o Blocks
o Nested classes
You can declare both methods and variables to be static. The most common example of a static
member is main( ).
main( ) is declared as static because it must be called before any objects exist.
Department of Information Technology [Ms. N. A. Patel & Mrs. A. K. Virani] 12
Object Oriented Programming with JAVA (4341602)| Unit-2
static variable - The static variable gets memory only once in the class area at the time of class
loading.
When objects of its class are declared, no copy of a static variable is made. Instead, all instances of the
class share the same static variable.
Instance variables declared as static.
Syntax: static type variablename;
Example,
class StaticVariable1 {
int rollno;//instance variable
String name;
static String college = "TDEC"; //static variable
//constructor
StaticVariable1(int r, String n) {
rollno = r;
name = n;
}
//method to display the values
void display() {
System.out.println(rollno + " " + name + " " + college);
}
}
class StaticVariable {
public static void main(String args[]) {
StaticVariable1 s1 = new StaticVariable1(1, "Rahul");
StaticVariable1 s2 = new StaticVariable1(2, "Aryan");
//we can change the college of all objects by the single line of code
//Student.college="TDEC";
s1.display();
s2.display();
}
Department of Information Technology [Ms. N. A. Patel & Mrs. A. K. Virani] 13
Object Oriented Programming with JAVA (4341602)| Unit-2
}
Output:
1 Rahul TDEC
2 Aryan TDEC
static method - If you apply static keyword with any method, it is known as static method.
A static method belongs to the class rather than the object of a class.
A static method can be invoked without the need for creating an instance of a class.
A static method can access static data member and can change the value of it.
Restrictions
o They can only call other static methods.
o They must only access static data.
o They cannot refer to this or super in any way.
Example,
class StaticDemo1 {
static int count =0;
int a; // We cannot use non-static variables in static methods
static void paint() {
System.out.println("Count:"+count);
count++;
//a=10;
}
public static void main(String[] args) {
System.out.println("Main block executed");
paint();
paint();
}
}
Output:
Main block executed
Count:0
Count:1
static block - static block is executed exactly once, when the class is first loaded.
It is used to initialize static variables of the class.
Department of Information Technology [Ms. N. A. Patel & Mrs. A. K. Virani] 14
Object Oriented Programming with JAVA (4341602)| Unit-2
It will be executed even before the main method.
Syntax:
static
{
//initialisation of static variables…
}
Example,
class StaticDemo1
{
static
{
System.out.println("Static block executed");
}
public static void main(String[] args)
{
System.out.println("Main block executed");
}
}
Output:
Static block executed
Main block executed
Explain any four string function in java with example. 03 – Summer-2024
String class - String is a sequence of characters enclosed within double quotes. E.g. “JAVA
PROGRAMMING”, “123”, “Me2” etc.
Strings are widely used in JAVA Programming, are not only a sequence of characters but it defines
object.
String Class is defined in java.lang.String package.
String Creation:
There are two ways to create String object:
i. Using String Literal - String literal is created by double quote.
o Example: String s1="Welcome"; // new object will be created
ii. Using String Constructor - The String class supports several constructors.
o Example: String s = new String("Welcome");
Department of Information Technology [Ms. N. A. Patel & Mrs. A. K. Virani] 15
Object Oriented Programming with JAVA (4341602)| Unit-2
Method of String Class:
Sr.
Method Description
No.
It returns string length. (number of characters).
Example,
1 int length()
String s="Welcome";
System.out.print(s.length()); // 7
It returns a string in lowercase.
2 String toLowerCase()
Example, System.out.print(s.toLowerCase()); // welcome
It returns a string in uppercase.
3 String toUpperCase()
Example, System.out.print(s.toUpperCase()); // WELCOME
It concatenates the specified string to the end of current
string.
Example,
4 String concat(String str)
String s1="Indian "; String s2="Cricketer";
String s3 = s1.concat(s2);
System.out.println(s3); // IndianCricketer
It returns single character at a specific index in string.
Example,
5 char charAt(int index) String s="Welcome";
System.out.println(s.charAt(0)); // W
System.out.println(s.charAt(3)); // c
It returns true if the strings contain the same characters in the
same order, and false otherwise. (case-sensitive)
Example,
String s1 = "Indian";
6 boolean equals(Object another)
String s2 = "Indian";
String s3 = “Hello";
System.out.println(s1.equals(s2)); // true
System.out.println(s1.equals(s3)); // false
It returns part of string for given begin index.
Example,
7 String substring(int beginIndex)
String s="Welcome";
System.out.println(s.substring(2)); // lcome
8 String substring(int beginIndex, It returns substring for given begin index and end index.
int endIndex)
Department of Information Technology [Ms. N. A. Patel & Mrs. A. K. Virani] 16
Object Oriented Programming with JAVA (4341602)| Unit-2
Example,
System.out.println(s.substring(1, 4)); // elc
It removes beginning and ending spaces of this string.
Example,
9 String trim() String s1=" hello ";
System.out.println(s1+"hey"); //without trim() - hello hey
System.out.println(s1.trim()+"hey"); //with trim() - hellohey
It replaces all occurrences of the specified char value.
Example,
10 String replace(char old, char new) String s1="Welcome";
System.out.println(s1.replace('e','a'));
//replaces all occurrences of 'e' to 'a' - Walcoma
Example,
class Stringfun {
public static void main(String[] args) {
String s = "Welcome";
System.out.println("Length of String: "+s.length()); // 7
System.out.println("Uppercase String: "+s.toUpperCase()); // welcome
System.out.println("Lowercase String: "+s.toLowerCase()); // WELCOME
String s1 = "Indian";
String s2 = "Cricketer";
String s3 = s1.concat(s2);
System.out.println("Concatenation of Strings: "+s3);
System.out.println("Char at 0 index: "+s.charAt(0));
System.out.println("Char at 3 index: "+s.charAt(3));
System.out.println("Equal of String: "+s1.equals(s2));
System.out.println("Substring from index 2: "+s.substring(2));
System.out.println("Substring from index 1 to 4: "+s.substring(1, 4));
String s4 = " hello ";
System.out.println("Without trim: "+s4 + "hey");
System.out.println("With trim: "+s4.trim() + "hey");
Department of Information Technology [Ms. N. A. Patel & Mrs. A. K. Virani] 17
Object Oriented Programming with JAVA (4341602)| Unit-2
System.out.println("Replace e with a: "+s.replace('e', 'a'));
}
}
Output:
Length of String: 7
Uppercase String: WELCOME
Lowercase String: welcome
Concatenation of Strings: IndianCricketer
Char at 0 index: W
Char at 3 index: c
Equal of String: false
Substring from index 2: lcome
Substring from index 1 to 4: elc
Without trim: hello hey
With trim: hellohey
Replace e with a: Walcoma
Explain StringBuffer in Java. 03
StringBuffer class
The StringBuffer class is used to created mutable (modifiable) string.
The StringBuffer class is same as String except it is mutable i.e. it can be changed.
Constructors of StringBuffer class:
o StringBuffer(): creates an empty string buffer with the initial capacity of 16.
o StringBuffer(String str): creates a string buffer with the specified string.
o StringBuffer(int capacity): creates an empty string buffer with the specified capacity as length.
Method of StringBuffer Class:
Sr.
Method Description
No.
1 length() It returns string length. (number of characters).
2 charAt(int index) returns single character at a specific index in string.
3 insert(int offset, char c) inserts the given string with this string at the given position.
4 append(String str) concatenates the given argument with this string.
5 reverse() reverses the current String.
Department of Information Technology [Ms. N. A. Patel & Mrs. A. K. Virani] 18
Object Oriented Programming with JAVA (4341602)| Unit-2
Example,
class StringBufferDemo {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer("Indian");
System.out.println(sb.length()); // 6
System.out.println(sb.charAt(3)); // i
sb.append("Bharat"); // now original string is changed
System.out.println(sb); // IndianBharat
sb.insert(6, " and "); //now original string is changed
System.out.println(sb); // IndianandBharat
System.out.println(sb.reverse()); // tarahBdnanaidnI
}
}
Differentiate between String class and StringBuffer class. 03 – Summer-2023
Sr.
String StringBuffer
No
1 String class object is immutable (can’t modify) StringBuffer class object is mutable (can modify)
String class is slower than the StringBuffer. StringBuffer class is faster than the String.
2
When we create an object of String class by When we create an object of StringBuffer class by
default no additional character memory space default we get 16 additional character memory
3
is created. space.
StringJoiner class
It is used to join multiple strings together with a specified delimiter. Java 8 added a new final class
StringJoiner in java.util package.
Now, you can create string by passing delimiters like comma(,), hyphen(-) etc. You can also pass prefix
and suffix to the char sequence.
Constructors of StringJoiner Class:
o StringJoiner(CharSequence delimiter): It constructs a StringJoiner with no characters, no
prefix or suffix, and a copy of the supplied delimiter.
o StringJoiner(CharSequence delimiter, CharSequence prefix, CharSequence suffix): It
constructs a StringJoiner with no characters using copies of the supplied prefix, delimiter, and
suffix. If no characters are added to the StringJoiner and methods accessing the string value are
invoked, it will return the prefix + suffix (or properties thereof) in the result
unless setEmptyValue has first been called.
Department of Information Technology [Ms. N. A. Patel & Mrs. A. K. Virani] 19
Object Oriented Programming with JAVA (4341602)| Unit-2
Method of StringJoiner Class:
Sr.
Method Description
No
1 add(CharSequence newElement) It adds the next element to the StringJoiner.
It adds the contents of the given StringJoiner without prefix and
2 merge(StringJoiner other) suffix as the next element if it is non-empty. If the given
StringJoiner is empty, the call has no effect.
It returns the length of the String representation of this
3 length()
StringJoiner.
setEmptyValue(CharSequence It sets the value to use if there are no elements in the
4
emptyValue) StringJoiner.
Example,
import java.util.StringJoiner;
class StringBufferDemo {
public static void main(String[] args) {
StringJoiner sj1 = new StringJoiner(",", "[", "]");
sj1.add("Red");
sj1.add("Green");
sj1.add("Blue");
System.out.println(sj1);
StringJoiner sj2 = new StringJoiner(",");
sj2.add("Yellow");
sj1.merge(sj2);
System.out.println(sj1);
System.out.println("Length of sj1 : " + sj1.length());
}
}
Output:
[Red,Green,Blue]
[Red,Green,Blue,Yellow]
Length of sj1 : 23
What is wrapper class? Explain with example. 03 – Winter-2023, 2024, Summer-2024
Wrapper Class - Wrapper class in Java provides the mechanism to convert primitive data type into
object (autoboxing) and object into primitive data type (unboxing).
Wrapper class wraps (encloses) around a data type and gives it an object appearance.
The primitive data types are not objects and they do not belong to any class.
So, sometimes it is required to convert data types into objects in java.
Department of Information Technology [Ms. N. A. Patel & Mrs. A. K. Virani] 20
Object Oriented Programming with JAVA (4341602)| Unit-2
Wrapper classes include methods to unwrap the object and give back the data type.
Autoboxing - To convert primitive data type into object
o valueOf() method - Return wrapper class object (Integer, Double, …), it convert primitive
datatype to object explicitly.
Unboxing - To unwrap the object into primitive data type.
Example, (Convert Interger object to int datatype)
o intValue() is a method of Integer class that returns an int data type.
Eight wrapper classes exist in java.lang package that represent 8 data types.
Primitive Data Type Wrapper Class Unwrap Methods
Byte Byte byteValue()
Short Short shortValue()
Int Integer intValue()
Long Long longValue()
Float Float floatValue()
Double Double doubleValue()
Char Character charValue()
Boolean Boolean booleanValue()
Example,
class WrapperClassDemo {
public static void main(String[] args) {
int a = 100;
Integer iobj = new Integer(a); // wrapping around Integer object
System.out.println("Integer object iobj: " + iobj); // printing the values from objects
Integer iobj2 = Integer.valueOf(a); // converting int into Integer explicitly
System.out.println("Integer object iobj2: " + iobj2);
int i = iobj.intValue(); // converting Integer to int explicitly
System.out.println("int i: " + i);
}
}
Output:
Integer object iobj: 100
Integer object iobj2: 100
int i: 100
Department of Information Technology [Ms. N. A. Patel & Mrs. A. K. Virani] 21
Object Oriented Programming with JAVA (4341602)| Unit-2
There are mainly two uses with wrapper classes:
o To convert simple data types into objects.
o To convert strings into data types (known as parsing operations), here methods of type
parseX() are used. (Ex. parseInt())
To convert a String to any of the primitive data types, except character. These methods have the
format parsex() where x refers to any of the primitive data types except char.
Example:
int x = Integer.parseInt("34"); // x=34
double y = Double.parseDouble("34.7"); // y =34.7
To convert any of the primitive data type value to a String, we use the valueOf() methods of the
String class.
Example:
String s1 = String.valueOf('a'); // s1="a"
String s2 = String.valueOf(true); // s2="true"
Access modifiers
Access modifiers is the process of controlling visibility of a variable or method.
Access modifiers in Java specifies the accessibility or scope of a field, method, constructor, or class.
There are four levels of visibility:
1. Private – Accessed only within class.
2. Public - Accessed from within class, outside class, within package and outside package.
3. Protected - Accessed only by classes that are subclass of class directly, Visible to package and all
sub Classes.
4. Default (or Package) - Visible to package. No modifiers are needed.
outside package by
Access Modifier within class within package outside package
subclass only
Private Y N N N
Default Y Y N N
Protected Y Y Y N
Public Y Y Y Y
**********
Department of Information Technology [Ms. N. A. Patel & Mrs. A. K. Virani] 22
inprotected.com