Java Unit 2
Java Unit 2
B 2 1 D A 0 3 0 2 - A c a d e m i c Ye a r- 2 0 2 2 - 2 0 2 3 - s e m I I I O D D
Semester
Classes, Objects and Methods: Introduction, Defining a Class, Adding Variables, Adding
Methods, Creating Objects, Accessing Class Members, Constructors, Methods
Overloading, Static Members, Nesting of Methods, Inheritance: Extending a
Class Overriding Methods, Final Variables and Methods, Finalizer methods, Abstract
Methods and Classes, Visibility Control. Arrays, Strings and Vectors: Arrays, One –
dimensional Arrays, Creating an Array, Two– dimensional Arrays, Strings,
Vectors, Wrapper Classes.
3
Topics to be learned from this class
Introduction
Defining a Class
Adding Variables
4
Introduction
OOPs (Object-Oriented Programming System)
1. Object
2. Class
3. Inheritance
4. Polymorphism
5. Abstraction
6. Encapsulation
5
Inheritance
When one object acquires all the properties and behaviors of a parent
6
Polymorphism
7
Abstraction
8
Encapsulation
Binding (or wrapping) code and data together into a single unit are known as
encapsulation.
A capsule, it is wrapped with different medicines.
A java class is the example of encapsulation.
Java bean is the fully encapsulated class because all the data members are private
here.
9
Classes in Java – Defining a class
10
DEFINING OBJECTin java
11
Object and Class Example
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.
A method is like a function which is used to expose the behavior of an object. (main
method)
The new keyword is used to allocate memory at runtime. All objects get memory in
Heap memory area.
13
Variables can be added inside the class called instance variable or inside the
method called (local variable).
Let's see a simple example, where we are having main() method in another class.
We can have multiple classes in different Java files or single Java file.
If you define multiple classes in a single Java source file, it is a good idea
to save the file name with the class name which has main() method.
14
EXAMPLE
class Student{
int id; // instance variables
String name;
int mobno; // adding instance variable
}
class TestStudent1{
public static void main(String args[]){
int a=10; // adding local variable
Student s1=new Student(); // object
System.out.println(s1.id);
System.out.println(s1.name);
System.out.println(s1.mobno);
System.out.println(a);
}
}
15
TOPICS TO BE LEARNED FROM THIS CLASS
Creating Objects
16
Creating Objects
17
Example1:-
public class MyClass
{
int x = 5;
public static void main(String[] args)
{
MyClass m1 = new MyClass();
System.out.println(m1.x);
}
}
18
INITIALIZING OBJECTS
By method
By constructor
19
1. Initialization through reference
Initializing an object means storing data into the object. Let's see a simple example where
we are going to initialize the object through a reference variable.
class Student{
int id;
String name;
}
class TestStudent2{
public static void main(String args[]){
Student s1=new Student();
s1.id=101;
s1.name=“Raghav";
System.out.println(s1.id+" "+s1.name);
}
} 20
2) Initialization through a method
In this example, we are creating the two objects of Student class and initializing the value to these objects
by invoking the insertRecord method. Here, we are displaying the data of the objects by invoking
the displayInformation() method.
class Student{
class TestStudent4{
int rollno;
public static void main(String args[])
String name;
{
void insertRecord(int r, String n){
Student s1=new Student();
rollno=r;
Student s2=new Student();
name=n;
s1.insertRecord(111,"Karan");
}
s2.insertRecord(222,"Aryan");
void displayInformation()
s1.displayInformation();
{
s2.displayInformation();
System.out.println(rollno+" "+name);
}
}
}
}
21
3) Initialization through a constructor : We will learn about constructors in Java later.
22
class Rectangle class TestRectangle1
{ {
int length; public static void main(String args[])
int width; {
void insert(int l, int w) Rectangle r1=new Rectangle();
{ Rectangle r2=new Rectangle();
length=l; r1.insert(11,5);
width=w; r2.insert(3,15);
} r1.calculateArea();
void calculateArea() r2.calculateArea();
{ }
System.out.println(length*width); }
}
}
23
TOPICS TO BE LEARNED FROM THIS CLASS
Visibility Control
Adding Methods
24
CLASSES, OBJECTS AND METHODS
Visibility control also known as access modifiers. It can be applied to the instance variables and methods
within a class.
The visibility specifies the accessibility or scope of a field, method, constructor, or class.
We can change the access level of fields, constructors, methods, and class by applying the access
modifier on it.
25
1.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.
class A
Example: {
public void display()
{
System.out.println("SoftwareTestingHelp!!");
}
}
class Main
{
public static void main(String args[])
{
A obj = new A ();
obj.display();
}
}
26
2. Private: The access level of a private modifier is only within the class. It cannot be
accessed from outside the class.
In this example, we have created two classes A and
Example: class A{
private int data=40; Simple. A class contains private data member and private
private void msg() method. We are accessing these private members from
{ outside the class, so there is a compile-time error.
System.out.println("Hello java");}
}
27
3. Protected: It 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.
package pack; In this example, we have created the two packages pack
public class A{ and mypack. The A class of pack package is public, so
protected void msg(){ can be accessed from outside the package. But msg
System.out.println("Hello");} method of this package is declared as protected, so it can
} be accessed from outside the class only through
//save by B.java inheritance.
package mypack;
import pack.*;
class B extends A
{
public static void main(String args[]){
B obj = new B();
obj.msg();
}
} 28
4. 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. It provides more accessibility than private. But it is more restrictive than protected,
and public. class BaseClass
{
Example: void display() //no access modifier indicates default modifier
{
System.out.println("BaseClass::Display with 'dafault' scope");
}
}
class Main
{
public static void main(String args[])
{
//access class with default scope
BaseClass obj = new BaseClass();
30
ADDING METHODS
We write a method once and use it many times, not require to write code again and
again.
31
The most important method in Java is the main() method.
Every method has a method signature and it is a part of the method declaration.
Method signature includes method name and parameter list.
32
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.
Method Name: It is a unique name that is used to define the name of a method. It
must be corresponding to the functionality of the method. Suppose, if we are
creating a method for addition of two numbers, the method name must
be addition() or sum(). A method is invoked or called by its name.
33
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.
Types of Methods
There are two types of methods in Java:
1. Predefined Method
2. User-defined Method
34
User-defined Method
The method written by the user or programmer is known as a user-defined method. These
methods are modified according to the requirement.
How to Create a User-defined Method
Let's create a user defined method that checks the number is even or odd. First, we will
define the method.
public class Demo
{ public void msg(){ //user defined method
System.out.print(“Hello”);
}
public static void main(String[] args)
{
Demo d1=new Demo();
d1.msg();
} }
35
Predefined Method
In Java, predefined methods are the method that is already defined in the Java class libraries
is known as predefined methods. It is also known as the standard library method or built-
in method. We can directly use these methods just by calling them in the program at any
point. Some pre-defined methods are length(), equals(), compareTo(), sqrt(), etc.
public class Demo
{
public static void main(String[] args)
{
// using the max() method of Math class
System.out.print("The maximum number is: " + Math.max(9,7));
}
}
36
TOPICS TO BE LEARNED FROM THIS CLASS
Constructors
Constructor Overloading
37
CONSTRUCTORS
At least one constructor will be invoked every time an object is created using the
new() keyword.
38
The rules for defining a constructor are.
39
TYPES OF CONSTRUCTORS
The default constructor is used to provide the default values to the object like 0,
null, etc..
40
Example of default constructor.
//Java Program to create and call a default constructor
class Bike1
{
//creating a default constructor
Bike1()
{
System.out.println("Bike is created");
}
//main method
public static void main(String args[])
{
//calling a default constructor
Bike1 b=new Bike1();
}
}
41
Example of default constructor that public static void main(String args[])
displays the default values {
// //creating objects
Let us see another example of default construc Student3 s1=new Student3();
tor Student3 s2=new Student3();
//which displays the default values //displaying values of the object
class Student3 s1.display();
{ s2.display();
int id; }
String name; }
//method to display the value of id and name
void display()
{
System.out.println(id+" "+name);
}
42
2. Parameterized Constructor
In this example, we have created the constructor of Student class that have two
parameters. We can have any number of parameters in the constructor.
43
Example of Parameterized Constructor
class Student4
{ public static void main(String args[])
int id; {
String name; //creating objects and passing values
//creating a parameterized constructor Student4 s1 = new Student4();
Student4(int i,String n) Student4 s2 = new Student4(222,"Aryan");
{ //
id = i; calling method to display the values of object
name = n; s1.display();
} s2.display();
//method to display the values }
void display() }
{
System.out.println(id+" "+name);
}
44
Constructor Overloading in Java
They are arranged in a way that each constructor performs a different task.
They are differentiated by the compiler by the number of parameters in the list and
their types.
45
Example of Constructor Overloading
class Student5
{ void display()
int id; {
String name; System.out.println(id+" "+name+" "+age);
int age; }
//creating two arg constructor
Student5(int i,String n) public static void main(String args[])
{ {
id = i; Student5 s1 = new Student5(111,"Karan");
name = n; Student5 s2 = new Student5(222,"Aryan",25);
} s1.display();
//creating three arg constructor s2.display();
Student5(int i,String n,int a) }
{ }
id = i;
name = n;
age=a;
}
46
TOPICS TO BE LEARNED FROM THIS CLASS
Methods Overloading
47
Methods Overloading
If a class has multiple methods having same name but different in parameters, it is known
as Method Overloading.
If we have to perform only one operation, having same name of the methods increases the
readability of the program.
Suppose you have to perform addition of the given numbers but there can be any number
of arguments, if you write the method such as a(int,int) for two parameters, and
b(int,int,int) for three parameters then it may be difficult for you as well as
other programmers to understand the behavior of the method because its name differs.
So, we perform method overloading to figure out the program quickly.
48
ADVANTAGE OF METHOD OVERLOADING
49
1) Method Overloading: changing no of arguments
In this example, we have created two methods, first add() method performs addition of two numbers and
second add method performs addition of three numbers.
In this example, we are creating static methods so that we don't need to create instance for calling
methods.
class Adder
{
static int add(int a,int b){return a+b;}
static int add(int a,int b,int c){return a+b+c;}
}
class TestOverloading1{
public static void main(String[] args){
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(11,11,11));
}}
50
2) Method Overloading: changing data type of arguments
In this example, we have created two methods that differs in data type. The first add
method receives two integer arguments and second add method receives two double
arguments.
class Adder{
static int add(int a, int b){return a+b;}
Output:
static double add(double a, double b){return a+b;}
22
}
24.9
class TestOverloading2{
public static void main(String[] args){
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(12.3,12.6));
}}
51
Why Method Overloading is not possible by changing the return type of method only?
In java, method overloading is not possible by changing the return type of the method only because of
ambiguity. Let's see how ambiguity may occur:
class Adder{
static int add(int a,int b){return a+b;}
static double add(int a,int b){return a+b;}
}
class TestOverloading3{
public static void main(String[] args){
System.out.println(Adder.add(11,11));//ambiguity
}}
Output:
Compile Time Error: method add(int,int) is already defined in class Adder
System.out.println(Adder.add(11,11)); //Here, how can java determine which sum() method should be
called?
Note: Compile Time Error is better than Run Time Error. So, java compiler renders compiler time
error if you declare the same method having same parameters.
52
TOPICS TO BE LEARNED FROM THIS CLASS
53
Static Members
In Java, static members are those which belongs to the class and you can access these
members without instantiating the class.
The static keyword can be used with methods, fields, classes (inner/nested), blocks.
Static Methods −
• we can create a static method by using the keyword static.
• Static methods can access only static fields, methods.
• To access static methods there is no need to instantiate the class, you can do it just
using the class name asshown in the below example
public class MyClass {
public static void sample(){
System.out.println("Hello");
}
public static void main(String args[]){
MyClass.sample();
} 54
STATIC FIELDS
57
METHOD 1 (USING ANONYMOUS SUBCLASSES)
•It is an inner class without a name and for which only a single object is created.
•An anonymous inner class can be useful when making an instance of an object with
certain “extras” such as overloading methods of a class or interface, without having
to actually subclass a class.
•Anonymous inner classes are useful in writing implementation classes for listener
interfaces in graphics programming.
58
EXAMPLE - ANONYMOUS INNER CLASS
Class a
{
public void show()
{
System.out.println(“nested class”);
}
}
Class anonumous
{
Public static void main(String args[])
{
a obj=new a()
{
public void show()
{
System.out.println(“this is anonyomous
class”);
}};
obj.show();
}}
59
METHOD 2 : USING LOCAL CLASSES
•We can also implement a method inside a local class.
• A class created inside a method is called local inner class.
• To invoke the method of local inner class, we must instantiate the class inside method.
/ Java program implements method inside
method new Local().fun();
public class method2 { }
public static void main(String[] args)
{
// function have implementation of another Display();
// function inside local class }
void Display() }
{
// local class
class Local {
void fun()
{
System.out.println(“Hello");
}
60
}
TOPICS TO BE LEARNED FROM THIS CLASS
INHERITANCE
TYPES OF INHERITANCE
61
INHERITANCE
Inheritance: Extending a Class
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).
The idea behind inheritance in Java is that you can create new classes that are built
upon existing classes. When you inherit from an existing class, you can reuse methods
and fields of the parent class. Moreover, you can add new methods and fields in your
current class also.
Inheritance represents the IS-A relationship which is also known as a parent-
child relationship.
Why use inheritance in java
For Method Overriding (so runtime polymorphism can be achieved).
For Code Reusability.
62
Terms used in Inheritance
3. Super Class/Parent Class: Super class is the class from where a subclass
inherits the features. It is also called a base class or a parent class.
class A The extends keyword indicates that we are making a new class
{ that derives from an existing class.
//methods and fields The meaning of "extends" is to increase the functionality.
} The relationship between the two classes is Programmer IS-
class B Extends A A Employee.
{ It means that Programmer is a type of Employee.
64
Example of INHERITANCE
class Employee
{ Output
float salary=40000; Programmer salary is:40000.0
} Bonus of programmer is:10000
class Programmer extends Employee
{
int bonus=10000;
public static void main(String args[])
{
Programmer p=new Programmer();
System.out.println("Programmer salary is:"+p.salary);
System.out.println("Bonus of Programmer is:"+p.bonus);
}
}
65
TYPES OF INHERITANCE
66
class Animal
1.Single Inheritance {
void eat()
{
•When a single class is derived from System.out.println("eating...");
a single parent class, it is }
called Single inheritance. }
• The subclass class acquires the data class Dog extends Animal
members and variables of super class {
•It is the simplest form of all inheritances. void bark()
{
System.out.println("barking...");
}
}
class SingleDemo
{
public static void main(String args[])
{
Dog d=new Dog();
d.bark();
d.eat();
}
} 67
2.Multilevel Inheritance
class Dept{
•When there is a chain of inheritance, it is void deptData(){System.out.println(“CS
known as multilevel inheritance. Dept");}
• In Multilevel Inheritance, a derived class will }
be inheriting a base class and as well as the derived class class Emp extends Dept{
also act as the base class to other class. void empData()
{System.out.println(“Abhilash");}
}
class Salary extends Emp{
void salData(){System.out.println(“50000");}
}
class MultiLevelDemo{
public static void main(String args[]){
Salary s1=new Salary();
s1.salData(); s1.empData(); s1.deptData()
}}
68
3.Hierarchical Inheritance.
Class Animal{
•When two or more classes inherits a single void eat(){System.out.println("eating...");}
class, it is known }
as hierarchical inheritance. class Dog extends Animal{
void bark(){System.out.println("barking..."); }
}
class Cat extends Animal{
void meow(){System.out.println("meowing...");}
}
class HierarchicalDemo{
public static void main(String args[]){
Dog d=new Dog(); Cat c=new Cat();
d.bark(); d.eat();
c.meow(); c.eat();
}}
69
TOPICS TO BE LEARNED FROM THIS CLASS
Overriding Methods
70
Overriding Methods
71
RULES FOR OVERRIDING METHODS
•The method must have the same name as in the parent class.
•The method must have the same parameter as in the parent class.
•There must be an IS-A relationship (inheritance).
72
Overriding Methods - Example of method overriding
The name and parameter of the method are the same, and there is IS-A relationship between the classes, so
there is method overriding.
//Creating a child class
/
Java Program to illustrate the use of Java Method O class Bike2 extends Vehicle
verriding {
//Creating a parent class. //defining the same method as in
the parent class
class Vehicle void run()
{ {System.out.println("Bike is running safely");}
//defining a method
void run() public static void main(String args[]){
{ Bike2 obj = new Bike2();//creating object
System.out.println("Vehicle is running"); obj.run();//calling method
} }
} }
73
Another example of Java Method Overriding
Consider a scenario where Bank is a class that provides functionality to get the rate of interest.
However, the rate of interest varies according to banks. For example, SBI, ICICI and AXIS banks
could provide 8%, 7%, and 9% rate of interest.
74
// class AXIS extends Bank{
Java Program to demonstrate the real scenario int getRateOfInterest(){return 9;}
of Java Method Overriding }
// //Test class to create objects and call the methods
where three classes are overriding the method class Test2{
of a parent class. public static void main(String args[]){
//Creating a parent class. SBI s=new SBI();
class Bank{ ICICI i=new ICICI();
int getRateOfInterest(){return 0;} AXIS a=new AXIS();
} System.out.println("SBI Rate of Interest: "+s.getRateOfIn
//Creating child classes. terest());
class SBI extends Bank{ System.out.println("ICICI Rate of Interest: "+i.getRateOf
int getRateOfInterest(){return 8;} Interest());
} System.out.println("AXIS Rate of Interest: "+a.getRateOf
class ICICI extends Bank{ Interest());
int getRateOfInterest(){return 7;} }
} }
75
Difference between method overloading and method overriding
76
TOPICS TO BE LEARNED FROM THIS CLASS
77
FINAL VARIABLES AND METHODS, FINALIZER METHOD
The final keyword in java is used to restrict the user. The java final keyword can be used
in many context. Final can be:
1.variable
2.method
3.class
The final keyword can be applied with the variables, a final variable that have no value it
is called blank final variable or uninitialized final variable. It can be initialized in the
constructor only. The blank final variable can be static also which will be initialized in the
static block only. We will have detailed learning of these. Let's first learn the basics of
final keyword.
78
1) Java final variable: If you make any variable as final, you cannot change the value of
final variable(It will be constant).
There is a final variable speed limit, we are going to change the value of this variable, but
It can't be changed
because final variable once assigned a value can never be changed.
class Bike9{
final int speedlimit=90;//final variable
void run(){
speedlimit=400;
}
public static void main(String args[]){
Bike9 obj=new Bike9();
obj.run();
}
}//end of class Output: Compile Time Error
79
2) Java final method
If you make any method as final, you cannot override it.
class Bike{
final void run(){System.out.println("running");}
}
class Honda extends Bike{
void run(){System.out.println("running safely with 100kmph");}
public static void main(String args[]){
Honda honda= new Honda();
honda.run();
}
}
80
3) Java final class
81
FINAL VARIABLES AND METHODS, FINALIZER METHOD
82
Finalize Method - Example
83
TOPICS TO BE LEARNED FROM THIS CLASS
84
CLASSES, OBJECTS AND METHODS
Abstract class in Java
85
Example of Abstract class that has an abstract abstract class Bike
{
abstract void run();
A method which is declared as abstract and does }
not have implementation is known as an abstract
method. class Honda4 extends Bike
Example of abstract method {
abstract void printStatus();// void run()
no method body and abstract {System.out.println("running safely");
}
Example of Abstract class that has an abstract public static void main(String args[])
method {
In this example, Bike is an abstract class that Bike obj = new Honda4();
contains only one abstract method run. Its obj.run();
implementation is provided by the Honda class. }
}
Output: running safely
86
Understanding the real scenario of Abstract class
In this example, Shape is the abstract class, and its implementation is provided by the
Rectangle and Circle classes.
Mostly, we don't know about the implementation class (which is hidden to the end user),
and an object of the implementation class is provided by the factory method.
A factory method is a method that returns the instance of the class. We will learn about the
factory method later.
In this example, if you create the instance of Rectangle class, draw() method of Rectangle
class will be invoked.
File: TestAbstraction1.java
abstract class Shape
{
abstract void draw();
}
87
//In real scenario, implementation is provided by others i.e. unknown by end user
class Rectangle extends Shape{
void draw()
{
System.out.println("drawing rectangle");}
}
class Circle1 extends Shape{
void draw(){System.out.println("drawing circle");}
}
//In real scenario, method is called by programmer or user
class TestAbstraction1{
public static void main(String args[])
{
Shape s=new Circle1();//In a real scenario, object is provided through method, e.g., getShape() method
s.draw();
} }
89
//Creating a Test class which calls abstract and non-abstract methods
class TestAbstraction2
{
public static void main(String args[])
{
Bike obj = new Honda();
obj.run();
obj.changeGear();
}
}
Output:
bike is created
running safely..
gear changed
90
TOPICS TO BE LEARNED FROM THIS CLASS
91
ARRAYS
92
•It is a data structure where we store similar elements.
•Unlike C/C++, we can get the length of the array using the length member.
•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.
• In Java, we can store primitive values or objects in an array.
•We can create single dimensional or multi dimensional arrays.
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, which grows automatically.
93
TYPES OF ARRAYS
•One dimensional array will have only one index point to store values
•If the data is linear, we can use the One Dimensional Array.
94
Syntax to Declare an Array in Java
We can declare, instantiate and initialize the java array together by:
int a[]={80,30,40,50}; //declaration, instantiation and initialization
Let's see the simple example to print this array.
//
Java Program to illustrate the use of declaration, instantiation and initialization of Java
array in a single line
class Testarray1{
public static void main(String args[])
{
int a[]={80,30,40,50}; //declaration, instantiation and initialization
for(int i=0;i<a.length;i++) //length is the property of array
System.out.println(a[i]); //printing array elements
}}
96
ARRAY USING FOR-EACH LOOP
97
PASSING ARRAY TO A METHOD
•We can pass the array to method as a parameter so that we can reuse the same logic
on any array.
class PassArray{
static void min(int arr[]){
int min=arr[0];
for(int i=1;i<arr.length;i++)
if(min>arr[i])
min=arr[i];
System.out.println(min);
}
public static void main(String args[]){
int a[]={33,3,4,5};//declaring and initializing an array
min(a);//passing array to method
}}
98
TWO DIMENSIONAL ARRAYS
•Syntax:
a[row_index][column_index]
•For Example:
int[][] a = new int[3][4]; //array with 3 rows and 4 columns
99
Two Dimensional Arrays - Example
10
0
System.out.println(“Array B”);
//Java Program to add 2 arrays
for(int i=0;i<3;i++){
class Testarray4{
for(int j=0;j<3;j++){
public static void main(String args[]){
System.out.println(b[i][j]+" ");
//declaring and initializing 2D array
}
int a[][]={{1,2,3},{2,4,5},{4,4,5}};
System.out.println();
int b[][]={{1,2,3},{4,5,6},{7,8,9}};
}
System.out.println(“Array A”);
System.out.println(“Sum of Array”);
for(int i=0;i<3;i++){
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
for(int j=0;j<3;j++){
System.out.println(a[i][j]+" ");
System.out.println(a[i][j]+b[i][j]);
}
}
System.out.println();
System.out.println();
}
} }}
10
1
Jagged Array in Java
It is an array of arrays with different number for (int i=0; i<arr.length; i++)
of columns. for(int j=0; j<arr[i].length; j++)
//Java Program to illustrate the jagged array arr[i][j] = count++;
class TestJaggedArray{
public static void main(String[] args){ //printing the data of a jagged array
// for (int i=0; i<arr.length; i++){
declaring a 2D array with odd columns int for (int j=0; j<arr[i].length; j++){
arr[][] = new int[3][]; System.out.print(arr[i][j]+" ");
arr[0] = new int[3]; }
arr[1] = new int[4]; System.out.println();//new line
arr[2] = new int[2]; }
//initializing a jagged array }
int count = 0; }
10
2
Strings
10
3
Create String object: By string literal
10
4
In the above example, only one object will be created.
Firstly, JVM will not find any string object with the
value "Welcome" in string constant pool, that is why it will
create a new object. After that it will find the string with
the value "Welcome" in the pool, it will not create a new
object but will return the reference to the same instance.
Note: String objects are stored in a special memory
area known as the "string constant pool".
Why Java uses the concept of String literal?
To make Java more memory efficient (because no new
objects are created if it exists already in the string
constant pool).
10
5
2) By new keyword
String s=new String("Welcome");//creates two objects and one reference variable
In such case, JVM will create a new string object in normal (non-pool) heap memory,
and the literal "Welcome" will be placed in the string constant pool. The variable s will
refer to the object in a heap (non-pool).
10
6
Java String class methods
The java.lang.String class provides many useful methods to perform operations on sequence of
char values.
No. Method Description
1 char charAt(int index) returns char value for the particular index
2 int length() returns string length
3 String substring(int beginIndex) returns substring for given begin index.
4 String substring(int beginIndex, int endIndex) returns substring for given begin index and end index.
5 boolean contains(CharSequence s) returns true or false after matching the sequence of char value.
7 boolean equals(Object another) checks the equality of string with the given object.
10
7
8 String concat(String str) concatenates the specified string.
9 String replace(char old, char new) replaces all occurrences of the specified char value.
10 static String equalsIgnoreCase(String another) compares another string. It doesn't check case.
12 int indexOf(int ch) returns the specified char value index.
15 String trim() removes beginning and ending spaces of this string.
10
8
Write a java program to implement few string operations (methods)
import java.util.*;
class StringOperation
{
public static void main(String[] args)
{
String str1=“Hello“;
String str2=“Welcome";
System.out.println(“Str1 length is :"+str1.length());
System.out.println(“Str2 length is :"+str2.length());
System.out.println("The concatenation is :"+str1.concat(“ System.out.println("Replacing ‘H' with ‘T' in
"+str2)); str1 : "+str1.replace(‘H',‘T'));
System.out.println("The first character of " +str1+"
is: "+str1.charAt(0)); }
System.out.println("The uppercase of " +str1+" }
is: "+str1.toUpperCase());
System.out.println("The lowercase of " +str1+"
is: "+str1.toLowerCase());
System.out.println("The “l" occurs at position in str2 :
" +str.indexOf(‘c’));
10
9
Vectors
11
0
Vectors in java
Vector is like the dynamic array which can grow or shrink its size. Unlike array, we can store
n-number of elements in it as there is no size limit. It is a part of Java Collection framework
since Java 1.2. It is found in the java.util package and implements the List interface.
It is similar to the ArrayList, but with two differences-
•Vector is synchronized.
•Java Vector contains many legacy methods that are not the part of a collections framework.
Java Vector class Declaration
public class Vector<E>
extends Object<E>
implements List<E>, Cloneable, Serializable
11
1
Java Vector Methods
The following are the list of Vector class methods:
11
2
13 lastElement() It is used to get the last component of the vector.
14 remove() It is used to remove the specified element from the vector. If the vector does not
contain the element, it is unchanged.
15 removeAll() It is used to delete all the elements from the vector that are present in the
specified collection.
16 removeAllElements() It is used to remove all elements from the vector and set the size of the vector to zero.
17 removeElement() It is used to remove the first (lowest-indexed) occurrence of the argument from
the vector.
18 removeElementAt() It is used to delete the component at the specified index.
19 replaceAll() It is used to replace each element of the list with the result of applying the operator
to that element.
20 set() It is used to replace the element at the specified position in the vector with the
specified element.
21 setElementAt() It is used to set the component at the specified index of the vector to the
specified object.
22 setSize() It is used to set the size of the given vector.
23 size() It is used to get the number of components in the given vector.
24 sort() It is used to sort the list according to the order induced by the specified Comparator.
11
3
import java.util.*;
public class VectorExample {
public static void main(String args[]) {
Vector<String> vec = new Vector<String>(); //Create a vector
vec.add("Tiger");
vec.add("Lion"); //Adding elements using add() method of List
vec.add("Dog");
vec.add("Elephant");
vec.addElement("Rat");
//Adding elements using addElement() method of Vector
vec.addElement("Cat");
vec.addElement("Deer");
System.out.println("Elements are: "+vec);
}
}
Output: Elements are: [Tiger, Lion, Dog, Elephant, Rat, Cat, Deer]
11
4
Wrapper Classes
11
5
Wrapper Classes
The wrapper class in Java provides the mechanism to convert primitive into object and object into primitive.
Since J2SE 5.0, autoboxing and unboxing feature convert primitives into objects and objects into primitives
automatically. The automatic conversion of primitive into an object is known as autoboxing and vice-
versa unboxing.
boolean Boolean
char Character
byte Byte
short Short
int Integer
long Long
float Float
double Double
11
7
Autoboxing
The automatic conversion of primitive data type into its corresponding wrapper class is known as autoboxing,
for example, byte to Byte, char to Character, int to Integer, long to Long, float to Float, boolean to Boolean,
double to Double, and short to Short.
Since Java 5, we do not need to use the valueOf() method of wrapper classes to convert the primitive into
objects.
Wrapper class Example: Primitive to Wrapper
//Java program to convert primitive into objects -Autoboxing example of int to Integer
public class WrapperExample1{
public static void main(String args[]){
int a=20; //Converting int into Integer
Integer i=Integer.valueOf(a);//converting int into Integer explicitly
Integer j=a; //autoboxing, now compiler will write Integer.valueOf(a) internally
System.out.println(a+" "+i+" "+j);
}}
Output:
20 20 20
11
8
Unboxing
The automatic conversion of wrapper type into its corresponding primitive type is known as unboxing. It is
the reverse process of autoboxing. Since Java 5, we do not need to use the intValue() method of wrapper
classes to convert the wrapper type into primitives.
Wrapper class Example: Wrapper to Primitive
//Java program to convert object into primitives - Unboxing example of Integer to int
public class WrapperExample2{
public static void main(String args[]){
//Converting Integer to int
Integer a=new Integer(3);
int i=a.intValue();//converting Integer to int explicitly
int j=a;//unboxing, now compiler will write a.intValue() internally
System.out.println(a+" "+i+" "+j);
}}
Output:
333
11
9
Java Wrapper classes Example
//Java Program to convert all primitives into its corresponding-wrapper objects and vice-versa
public class WrapperExample3
{
public static void main(String args[])
{
byte b=10;
short s=20;
int i=30;
long l=40;
float f=50.0F;
double d=60.0D;
char c='a';
boolean b2=true;
//Autoboxing:
Converting primitives into objects
Byte byteobj=b; Short shortobj=s;
12
0
Integer intobj=i; Long longobj=l;
Float floatobj=f; Double doubleobj=d;
Character charobj=c; Boolean boolobj=b2;
//Printing objects
System.out.println("---Printing object values---");
System.out.println("Byte object: "+byteobj);
System.out.println("Short object: "+shortobj);
System.out.println("Integer object: "+intobj);
System.out.println("Long object: "+longobj);
System.out.println("Float object: "+floatobj);
System.out.println("Double object: "+doubleobj); System.out.println("Character object: "
+charobj); System.out.println("Boolean object: "+boolobj);
//Unboxing: Converting Objects to Primitives
byte bytevalue=byteobj; short shortvalue=shortobj;
int intvalue=intobj; long longvalue=longobj; float floatvalue=floatobj;double doublevalu
e=doubleobj; char charvalue=charobj; boolean boolvalue=boolobj;
12
1
//Printing primitives
System.out.println("---Printing primitive values---");
System.out.println("byte value: "+bytevalue); System.out.println("short valu
e: "+shortvalue);
System.out.println("int value: "+intvalue);
System.out.println("long value: "+longvalue); System.out.println("float valu
e: "+floatvalue); System.out.println("double value: "+doublevalue);
System.out.println("char value: "+charvalue); System.out.println("boolean v
alue: "+boolvalue);
}}
12
2