JPR Unit1Notes
JPR Unit1Notes
=============================================
Features of OOP:
================
• Emphasis is on data rather than procedure.
• Programs are divided into Objects.
• Data is hidden and cannot accessed from the external functions.
• Objects may communicate with each other through functions.
• New data and functions can be added easily whenever required.
• OOP follow bottom-up approach in program design.
• Object is a collection of data & functions; function operates on data.
• More security provided for the data compare to POP.
• Data cannot move openly from one function to another function.
2. Classes:
• It is a collection of similar types of objects.
• Class is a collection of data and functions; functions operate on data.
• You may create objects from the class.
• When you define the class then memory will not be allocated for the members.
• Class shows data abstraction and data encapsulation features.
• Example: Fruit mango
• In above example, mango is an object which is created from class Fruit.
3. Data Abstraction:
• To show only essential details without background details.
4. Data Encapsulation:
• The wrapping up of data and functions into a single unit is known as Data Encapsulation.
5. Inheritance:
• The process of creating new class by using the concept of old class is known as Inheritance.
• Newly created class is known as Derived class.
• Old class is known as Base class.
6. Polymorphism:
• Polymorphism is a Greek word.
• Poly means 'many' and morphism means 'forms'
➢ Ability to take more than one forms is known as Polymorphism.
In OOP, we can create set of objects that communicate with each other.
I) Creating classes that define objects.
II) Creating objects from the class definition.
III) Establishing communication among objects.
=====================
Benefits of OOP
====================
1) Using concept inheritance, we can achieve reusability.
2) Data hiding
3) Software complexity can be easily managed.
4) Object oriented system can be easily upgraded from small to large systems.
5) It is easy to partition work in the project based on objects.
===Application of OOP===
1) Real time systems.
2) Simulation and modeling
3) Object-oriented databases
4) Hypertext, hypermedia and expert text.
5) AI and expert systems.
6) Neural networks and parallel programming.
7) Decision support and office automation System.
8) CIM/CAD System
Java History:
================
================
Java Features:
================
1. Compiled and Interpreted:
• Usually, computer language is either compiled or interpreted.
• But java combines both these approaches that’s via Java is called as two stage compilation
process programming language.
• Java compiler takes java source file(.java) as input and generates byte file(.byte).
• Byte file is not a machine code and this file not exists physically in your machine.
• Byte code generated virtually and process virtually.
• Java Interpreter generates machine code from byte code.
2. Platform Independent and Portable:
• Java program can be easily moved from one computer to another computer, anywhere and
anytime.
• It means, if we develop Java code on Windows machine then you can easily run that code on
other operating systems like Linux, Unix, etc.
• To move java code from one machine to another machine is known as portability.
3. Object Oriented:
• Java is true object-oriented language.
• Almost everything in java is an object.
• All program code and data reside within objects and classes.
• Java is a collection of rich set of predefined classes and packages, that we can use in our
programs by inheritance.
4. Robust & Secure:
• Java is robust language.
• It provides many safeguards to ensure reliable code.
• It has strict compile time and runtime checking for data types.
• It supports garbage collection feature that would solve memory management problem.
• It supports exception handling which help us to captures many errors.- Java is more secure
programming language which is used for programming on internet.
• Java systems not only verify all memory access but also ensure that no viruses are communicated
with an applet.
5. Distributed:
• Java is designed as distributed language for creating applications on networks.
• It has ability to share both data and programs.
• Java application can open and access remote objects on internet.
• This enables multiple programmers at multiple locations to collaborate and worktogether on a
single object.
6. Simple, Small and Familiar:
• Java is a small and simple language.
• Many features of C & C++ which are not relible that was not added in Java.
• Java does not use pointers, preprocessor directive, goto statement and many others.
• Also not included multiple inheritance and operator overloading features.- Familiarity is another
important feature of Java.
7. Multi-threaded and Interactive:
• Thread is a light weight process because it takes small amount of memory space for their
execution.
• When mutliple thread executes simultaneously then it is called as Multithreading.- Java supports
multithreaded programs.
• This means that we need not to wait for the application to finish one task before beginning
another.
• Due to this feature, we can create more interactive programs in java.
8. High Performance:
• Java performance is impressive for an interpreted language, mainly due to the use of byte code.
• Java speed is faster than C/C++ language.
• Java architecture is also designed to reduce overhead during the runtime.
• Due to multi-threading fetures Java program execution speed is increased.
9. Dynamic & Extensible:
• Java is dynamic language.
• Java is capable of dynamically linking in new class libraries, methods and objects.
• Java programs support functions written in othet languages such as c and C++
• This facility enables the programmers to use the efficient functions in these languages.
• It is called as native functions/methods.
• Native methods are linked dynamically at runtime.
=================================================
Difference between Java and C
=================================================
• Java is Object oriented programming language and C is Procedure oriented programming.
• Java does not include c keyword sizeof and typedef.
• Java does not contain data types struct and union.
• Java does not define the data type modifiers keyword auto,extern,register,signedand unsigned.
• Java does not support pointer concept.
• Java does not have preprocessor directive and thats via we don't use #define, #include
• Java adds labeled break and continue statements.
• Java adds new operators such as instanceof.
• Java adds many required features of Object Oriented Programming Language.
=================================================
Difference between Java and C++
=================================================
• C++ is object-oriented programming but Java is true object-oriented programming.
• Java does not support operator overloading.
• Java does not support pointer concept.
• Java does not support multiple inheritance. But you can implement it using new feature called
'interface'.
• Java does not support global variable.
• Java does not support destructor function but we use finalize() method.
• There is no header files in Java.
==================================
Java Environment
==================================
• Java environment includes development tools(JDK) and classes & method(JSL-API).
• JDK stands for Java development kit.
• JSL stands for Java Standard Library.
• JRE stands for Java Runtime Environment.
• Java Development kit(JDK)
• The JDK (Java Development Kit) is a software development kit provided by Oracle (or other
vendors) to develop Java applications. It includes all the necessary tools, libraries, and
documentation required to write, compile, and run Java programs. It contains the JRE (Java
Runtime Environment), but it also adds additional development tools like the compiler (javac),
debugger, and other utilities for building Java applications.
Components of the JDK:
1. JVM (Java Virtual Machine): The JVM is responsible for running Java bytecode. It's platform-
independent and allows Java programs to be executed on any device that has the JVM installed.
2. JRE (Java Runtime Environment): This is a part of the JDK and provides the libraries and other
resources necessary to run Java programs, but it doesn't contain development tools like compilers.
3. Compiler (javac): The Java compiler converts Java source code (.java files) into bytecode (.class
files) that can be executed by the JVM.
4. Libraries: The JDK includes many standard libraries, such as the java.lang, java.util, javax.swing,
java.io, and many others that are commonly used for building Java applications.
5. Debugger (jdb): A debugger tool that allows you to analyze and step through Java programs
while they are running.
6. JavaDoc: A tool for generating API documentation in HTML format from Java source code
comments.
- Comments part ignored by the compiler.
1. Single line comment
//This is single line comment
2. Multi-line comment
/*
This is multi-line comment
*/
• Command line arguments:
-- Give input to Java code.
Example:
java filename <list of input values> java sample 100 200
Program:
//Commandlineargument class CommandLineArgsD
{
public static void main(String args[])
{
Int a,b,c;
a=Integer.parseInt(args[0]);
b=Integer.parseInt(args[1]);
c=a+b;
System.out.println("Addition of two numbers="+c);
}
}
• Scanner Class:
• The Scanner class in Java is part of the java.util package and is used to read input from various
sources, including user input from the console, files, or strings. It is commonly used to gather input
from users during runtime in console-based applications.
• Importing the Scanner Class
To use the Scanner class, you must import it at the beginning of your Java program:
➢ import java.util.Scanner;
• Creating a Scanner Object
To create an instance of the Scanner class, you use the following syntax:
➢ Scanner scanner = new Scanner(System.in);
Here, System.in is an input stream that represents input from the console (keyboard).
Data Types:
===========
Constants:
Scope of Variables:
• Scope of the variables is nothig but the life time of variables.
• Its scope is depended on where in the program that variables are declared.
• The area of the program where the variable is accessible is called as scope.
• There are three different types of variables present in java
Instance Variables:
• Instance variable is declared inside the class.
• Instance variables are created when the objects are instantiated.
• Instance variables allocate separate memory space when object is created.
• They take different values for each object.
Class Variables:
• Class variables are declared inside the class.
• They are the global to the class.
• It common between all objects.
• Only one memory location is created for each class variables.
Local Variables:
• Local Variables declared and used inside the functions.
• The variables which are declared inside the body of methods in known as local variables.
• They are not available outside the method.
• Local variables can be declared inside the body of methods which is starting from opening curly
braces “{“and closing braces “}”.
Example:
class Student {
int rollno; //instance variable
String name; //instance variable
float marks; //instance variable
static int college_code=1010; //class variable void calc_marks()
{
int total; //local variable
}
}
==================================
Type casting/ Data Type conversion
==================================
• The process of converting one data type to another data type is known as type casting.
• To change entity of one data type to another data type is known as data type conversion.
• Tyep casting occurs when we want to store value of one data type into variable of another type.
• This type casting is required while developing applications.
• If you store large data type value into small data type then it might be data loss.
• If you will store an int value into byte variable then this will be illegal operation.
• To avoid data loss, you should store smaller data type value into larger data type variable.
Conversion Table:
From To
byte short,char,int,long,float,double short
int,long,float,double char int,long,float,double int
long,float,double
long float,double
float double
There are two types of casting:
1. Implicit Type casting
The type casting which is done by the system is known as Implicit type casting. - Example:
//Implicit Type casting c
class ImplicitTypeCastingDemo {
public static void main(String args[]) {
int a = 70;
float b;
b = a; // Implicit type casting
System.out.println("Value of int variable a = " + a);
System.out.println("Value of float variable b = " + b);
}
}
2. Explicit Type Casting
The type casting which is done by the programmer is known as Explicit type casting.
Syntax:
datatype VariableName1=(datatype)VariableName2;
Example:
//Explicit Type casting class
class ExplicitTypeCastingDemo {
public static void main(String args[]) {
int a = 70;
float b;
b = (float) a;
System.out.println("Value of int variable a = " + a);
System.out.println("Value of float variable b = " + b);
}
}
========================
Standard Default Values
========================
• Every variable has default value in JAVA.
• If variable is not initialized then java provides default value to that varible automatically.
Type Of Variables Default Value
byte zero(0)
short zero(0)
int zero(0)
long zero(0L)
float 0.0f
double 0.0d
char Null
Character boolean false
==============================
Operators and Expression
==============================
• Operator is a symbol which indicate operation to be perform.
• Operands is a variable on which we can perform operation.
• The proper arrangement of operators and operands is known as Expression.
• Following are the classification of operators in JAVA:
❖ Arithmetic Operators(+,-,*,/,%)
❖ Relational Operators(<,>,<=,>=,==,!=)
❖ Logical Operators(&&,||,!)
❖ Assignment Operators(=)
❖ Increment and decrement Operators(++,--)
❖ Conditional Operator(?:) condition?expression1:expression2;
❖ Bitwise Operator(&,|,^,<<,>>,~)
❖ Special operators(instanceof, dot)
Instanceof Operator:
- This operator return true if the object on the left side is an instance of the class given on the right side. -
Syntax:
if(object instanceof ClassName)
{
//body
}
- Example:
import java.util.*;
class InstanceOfOpDemo {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
class ForLoopDemo {
public static void main(String args[]) {
int i;
for (i = 1; i <= 5; i++) {
System.out.println("Jaihind");
}
}
}
/*
Jaihind Jaihind
Jaihind Jaihind
Jaihind
*/
while loop:
=============
=
- while is a predefined keyword
- Syntax:
while(Condition)
{
//body of while loop
}
- Example:
import java.util.*;
class WhileLoopDemo {
public static void main(String args[]) {
int i = 1;
while (i <= 5) {
System.out.println("Jaihind"); i++;
}
}
}
/*
Jaihind Jaihind
Jaihind Jaihind
Jaihind
*/
do-while loop:
==================
do & while both are predefined keywords.
Syntax:
do
{
//body
}while(condition);
Enhanced for loop/For each loop:
===============================
• It is also called as for each loop.
• Using this loop, we can easily retrieve the value of array without using indexes.
• Using for each loop, we can easily iterate over the array.
Syntax:
for(DataType VariableName:Expression)
{
//statements
}
Example: //for each loop class ForEachLoopDemo
{
public static void main(String args[])
{
int num[]={10,20,30,40,50};
System.out.println("Your Array Elements are:");
for(int x:num)
{
System.out.println("Value of x :"+x);
}
}
}
/*
Your Array Elements are: Value of x :10
Value of x :20 Value of x :30 Value of x :40 Value of x :50 */
Defining the Class:
======================
• Class is a collection of similiar types of objects.
• Class is a user defined data type.
• Class contains instance variables and methods.
• Class shows data abstraction and data encapsulation properties.
Syntax:
class Class_Name
{
datatype instance_variable1; datatype instance_variable2; datatype instance_variableN;
returntype Method_Name1(parameter_list)
{
//body of method
}
returntype Method_Name2(parameter_list)
{
//body of method
}
returntype Method_NameN(parameter_list)
{
//body of method
}
}
Example:
class Addition
{
int a,b,c; void getdata()
{
a=100; b=50;
}
void display()
{
c=a+b; System.out.println("Addition="+c);
}
}
Note:
• No semicolon after the closing curly bracket.
• ClassName is valid java identifier
• The instance variable and methods defined inside the class is known as member of
the class.
• Class declaration only creates template, it does not create an actual object.
• Memory should not be allocated for the data members of the class.6) Method definition should
present inside the class only.
Creating an Objects:
=======================
• An object is instance of the class.
• When object is created then memory will be allocated for the instance variables of the class.
• We can create N no of objects from the class.
• Objects are created using new operator.
• The new operator creates an object of the class and return reference to the object created.
Declaration of Object:
Syntax : ClassName ObjectName; Example: Addition a1;
Instantiate of Object:
Syntax : ObjectName=new ClassName(Parameter_list); Example: a1=new Addition();
- Combining the above two steps:
Syntax : ClassName ObjectName=new ClassName(Parameter_list); Example: Addition a1=new Addition();
***Accessing Class Members:
===========================
Object contain data members and member function.
So we can access them by using object name and dot operator.
Syntax:
ObjectName.Variable_Name=value; ObjectName.Method_Name(Parameter_list)
; - Example:
a1.a=100; a1.b=200;
a1.getdata();
a1.display();
***Array of objects:
====================
Array of object is the collection of objects of same class.
Instead of creating mutiple objects, it would be better to create array of objects.
Array index should begin with 0 and end with size-1. - Object Name is same but its indexes are different.
Syntax:
ClassName ObjectName[]=new ClassName[SIZE]; - Example:
Kuran v[]=new Kuran[5];
for(int i=0;i<5;i++)
{ v[i]=new Kuran();//Assigning object to individual reference in the array.
}
==================
***Constructors***
==================
• Constructor is a special member function of the class.
• It is used to initialize the data members of the objects.
• There is no any return type for the constructor.- Constructor name and class name both are same.
• Constructor automatically called when object is created.
• Constructor is used for creation of an object.
• Suppose, in our class we have not defined constructor then system will supply thedefault
constructor for creation of an objects. –
• There are three different types of the constructor:
I. Default constructor
II. Parameterized constructor
III. Copy constructor
I. Default constructor:
When constructor does not takes any parameters then it is called as default constructor.
Syntax:
class ClassName
{
ClassName()
{
//body of constructor.
}
}
II. Parameterized constructor:
When constructor takes any parameters then it is called as Parameterized constructor.
Syntax:
class ClassName
{
ClassName(parameter_list)
{
//body of constructor.
}
}
III. Copy constructor:
To initialize data members of the object, we are passing another object as argument is called as copy
constructor.
When constructor takes reference of its class as paramater then it is called as copy constructor.
Syntax:
class ClassName
{
ClassName(ClassName ObjectName)
{
//body of constructor.
}
}
Example: //copy constructor
class Item
{
int x;
Item()
{
x=100;
}
Item(Item m)
{
x=m.x;
}
void display()
{
System.out.println("Value of X : "+x);
}
public static void main(String args[])
{
Item i1=new Item();
Item i2=new Item(i1);
i1.display();
i2.display();
}
}
***Constructor overloading:
==========================
Constructor names are same but its arguments are different.
Example:
//constructor overloading
class Room
{
float length;
float width;
Room(float x)
{
length=x;
width=20.50f;
}
Room(float m,float n)
{
length=m;
width=n;
}
void display()
{
float room_area;
room_area=(length*width);
System.out.println("Area of Room : "+room_area);
}
public static void main(String args[])
{
Room r1=new Room(10.10f);
Room r2=new Room(50.50f,23.50f);
r1.display();
r2.display();
}
}
=================
Static Members
=================
• Static members can be data and methods.
• When we create objects of the class then separate memory allocated for each data members of the
class.
• But sometime, there could be situation where we want to keep one variable common between all
objects.
• In this case, we can make that variable as static.
• When we make variable as static then only one copy of that variable created in computer memory
and all objects share it commonaly.
• Static members come under the scope of class.
• We can access static members using classname and dot operator.
• Inside the body of static member function, we can access only other static data members. - There
is no need to define static data member outside the class.
• By default, static variable contains zero value.
Example:
//static data member and static member function
class StaticDemo
{
int no;
static int count; //static variable void getdata(int x)
{
no=x;
count++;
}
void display_no()
{
System.out.println("Value of no="+no);
}
static void display_count() //static method
{
System.out.println("Value of count="+count);
}
public static void main(String args[])
{
StaticDemo s1=new StaticDemo(); StaticDemo s2=new StaticDemo(); StaticDemo s3=new StaticDemo();
s1.getdata(100);
s2.getdata(200);
s3.getdata(300);
System.out.println("Object s1 :");
s1.display_no();
StaticDemo.display_count();
System.out.println("Object s2 :");
s2.display_no();
StaticDemo.display_count();
System.out.println("Object s3 :");
s3.display_no();
StaticDemo.display_count();
}
}
OUTPUT:
Object s1 : Value of no=100
Value of count=3 Object s2 :
Value of no=200 Value of count=3
Object s3 :
Value of no=300 Value of count=3
================================================
Visibility Control/Access Specifiers Parameter:
=================================================
Java provides four types of visibility control.
❖ public
❖ private
❖ protected
❖ Friendly Access
public: ------
• Any variables and methods declared as public, it can be accessible outside the class.
private: --------
• Those members are declared as private, it can accessible within the class in which they are
declared.
• It cannot be inherited in its subclass.
protected: ---------
• Those members are declared as protected, it can accessible in same class and its immediate sub-
class.
Friendly Access:
• In the situation where no access modifier is specified then by default all members considered as
friendly access level.
• There is basic difference between public and friendly access is that public members accessible
anywhere but friendly access member available in same package not outside the package.
===================
Arrays
===================
• Normally, one variable can store one value at a time.
• But sometimes, we need to store multiple values then creation of multiple variables is not a better
solution.
• In this case, we can create array variable.
• Array variable name is same but it will store multiple values.
• Array is a collection of similiar types of elements.
• Array index should begin with Zero and end with SIZE-1.
• Array elements are stored in continues memory location.
• There are three different types of array:
➢ One dimensional array
➢ Two dimensional array
➢ Multi-dimensional array
======================
One Dimensional Array
======================
Creating an Array involes following steps:
I) Declaration of Array: - Syntax:
form-1 datatype ArrayName[]; form-2 datatype [] ArrayName;
Example:
int marks[];
float average[]; int [] sum;
II) Creation of Array:
After declaration of array, we need to create it in the memory. Java allows us tocreate array using new
operator only.
Syntax:
Example:
ArrayName=new datatype[SIZE];
marks=new int[5];
average=new float[10];
Combining step-I and step-II:
Syntax: datatype ArrayName[]=new datatype[SIZE]; Example: int marks[]=new int[5];
Array Initialization:
• In this step, we will put values into the array.
• This process is known as initialization.
• We can initialize array elements using index number and subscripts.
Example:
ArrayName[index]=value
marks[0]=99;
marks[1]=78;
marks[2]=65;
We can also initialize array elements automatically at the time of declaration.
Syntax:
datatype ArrayName[]={list of values};
- Example: int number[]={10,20,30,40,50};
Array Length:
Java provides predefined method length to calculate length of array.
Example:
len=3;
int a[]={10,20,30};
int len=a.length;
Example-1:
class OneDArray
{
public static void main(String args[])
{
int a[]=new int[5];
a[0]=10;
a[1]=20;
a[2]=30;
a[3]=40;
a[4]=50;
for(int i=0;i<a.length;i++)
{
System.out.println("Element present at index "+i+" is "+a[i]);
}
}
}
/*
Element present at index 0 is 10 Element present at index 1 is 20 Element present at index 2 is 30
Element present at index 3 is 40 Element present at index 4 is 50
*/
Example-2:
import java.util.*;
class OneDArray1
{
public static void main(String args[])
{
int a[]=new int[5];
int i;
Scanner sc=new Scanner(System.in);
System.out.println("Enter Five Array Elements:");
for(i=0;i<5;i++)
{
a[i]=sc.nextInt();
}
System.out.print("Array Elements are : ");
for(i=0;i<5;i++)
{
System.out.print(a[i]+" ");
}
}
}
/*
Enter Five Array Elements:
100
200
300
400
500
Array Elements are : 100 200 300 400 500
*/
Example-3:
//one dimensional Array : reverse the elements of array
import java.util.*;
class OneDArray2
{
public static void main(String args[])
{
int a[]=new int[5];
int i;
Scanner sc=new Scanner(System.in);
System.out.println("Enter Five Array Elements:");
for(i=0;i<5;i++)
{
a[i]=sc.nextInt();
}
System.out.print("Display Array Elements in Reverse Order: ");
for(i=a.length-1;i>=0;i--)
{
System.out.print(a[i]+" ");
}
}
}
/*
Enter Five Array Elements:
100
200
300
400
500
Display Array Elements in Reverse Order: 500 400 300
200 100 */
======================
Two-Dimensional Array
======================
• Two-Dimensional array is used to maintain elements in rows and column format.
• We can represent data in tabular format.
• Rows index should begin with 0 and end with size-1.
• Columns index should begin with 0 and end with size-1.
Creating an Array involes following steps:
I) Declaration of Array:
Syntax:
form-1 datatype ArrayName[][]; form-2 datatype [][] ArrayName;
Example:
int marks[][];
float average[][];
int [][] sum;
II) Creation of Array:
After declaration of array, we need to create it in the memory. Java allows us tocreate array using new
operator only.
Syntax:
Example:
ArrayName=new datatype[ROWS][COLUMNS];
marks=new int[3][3];
average=new float[10][10];
Combining step-I and step-II:
Syntax: datatype ArrayName[][]=new datatype[ROWS][COLUMNS]; Example: int marks[][]=new
int[3][3];
Array Initialization:
In this step, we will put values into the array.
This process is known as initialization.
We can initialize array elements using index number and subscripts.
Syntax:
Example:
ArrayName[Row-Index][Column-Index]=value;
int a[][]=new int[3][3];
a[0][0]=10;
a[0][1]=20;
a[0][2]=30;
a[1][0]=40;
a[1][1]=50;
a[1][2]=60;
a[2][0]=70;
a[2][1]=80;
a[2][2]=90;
We can also initialize array elements automatically at the time of declaration.
Syntax:
datatype ArrayName[][]={list of values};
Example: int number[][]={{10,20,30},
{40,50,60},
{70,80,90}
};
Program:
import java.util.*;
class TwoDArray
{
public static void main(String args[])
{
int i,j;
int a[][]=new int[3][3];
Scanner sc=new Scanner(System.in);
System.out.println("Enter 3*3 Array Elements:");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++) {
a[i][j]=sc.nextInt();
}
}
System.out.println("Your 3*3 Array Elements: ");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
System.out.print(a[i][j]+" ");
}
System.out.println();
}
}
}
/*
Enter 3*3 Array Elements:
10
20
30
40
50
60
70
80
90
Your 3*3 Array Elements:
10 20 30
40 50 60
70 80 90
*/
=================
***Vectors***
=================
• Vector is an extensible array.
• Vector is a collection of objects and it can be retrived by using index number.- Array is a collection
of similiar types of elements but its size is fixed.
• But vector is a collection of objects but its size is not fixed.
• Vector class provides array of variable size.
• The main difference between vector and array : Vector automatically grow when they run out of
space.
• Vectors class provides extra method for adding and removing elements.
• The class is used to create dynamic array known as Vector that can holds objects of any type and
any numbers.
• Vector is a predefined class which is present under java.util package.
• Vectors are created like array as follow:
• Declaration of Vector without size. Vector VectorName=new Vector():
• Declaration of Vector with size. Vector VectorName=new Vector(10):
• Advantages of Vector over arrays:
• It is convenient to the vector to store objects.
• Vector is used to store multiple objects and its size not fixed.
• Objects can be added and deleted from the vector whenever required. DisAdvantages of Vector
• It can not directly store simple data type only objects can be stored.
• To store simple data type value in the vector, they must be converted into objects.
• Wrapper classes are required for above conversion. Important Vector Methods:
Vector v1=new Vector();
v1.addElement(item) - Adds the item to the vector at the end.
v1.elementAt(10) - Gives the name of 10th object.
v1.size() - Gives the number of objects present.
v1.removeElement(item) - Removes the specified item from the vector.
v1.removeElementAt(n) - Removes the item stored in nth position.
v1.removeAllElements() - Removes all the elements in the list.
v1.copyInto(array) - Copies all items from vector to array.
v1.insertElementAt(item,n) - Insert the item at nth position.
- Program- 1:
/*Write a program to create vector with six elements (10,30,60,70,80,100). Removes element 3rd and
4th position. Insert new element at 3rd position. Display the original and current size of vector
*/
import java.util.*;
class VectorDemo1
{
public static void main(String args[])
{
Vector v1=new Vector();
v1.addElement(new Integer(10));
v1.addElement(new Integer(30));
v1.addElement(new Integer(60));
v1.addElement(new Integer(70));
v1.addElement(new Integer(80));
v1.addElement(new Integer(100));
System.out.println("Initial Vector Size = "+v1.size());
v1.removeElementAt(3);
v1.removeElementAt(4);
v1.insertElementAt(new Integer(150),3);
System.out.println("Final Vector Size = "+v1.size());
}
}
/*
Initial Vector Size = 6 Final Vector Size = 5
*/
Program-2: -------
---import java.util.*;
class VectorDemo2
{
public static void main(String args[])
{
Vector v1=new Vector();
for(int i=0;i<args.length;i++)
{
v1.addElement(args[i]);
}
System.out.println("Vector of Size = "+v1.size());
System.out.println("Your Vector Elements:");
for(int i=0;i<v1.size();i++)
{
System.out.println(v1.elementAt(i));
}
}
}
/*
F:\Academic 2022\JavaBatch2022\UNIT-II>java VectorDemo2 10 20 30 40 50 Vector of Size = 5 Your
Vector Elements:
10
20
30
40
50
*/
================
Wrapper Classes
================
• As you already aware about, in java some concepts only works on objects.
• Let take one example - Vector : Vector cannot handle primitive data types like int,float,long,char
and double.
• Using Wrapper classes, we can convert primitive data type into objects.
• In Java different wrapper clases are given which is present under java.lang package.
Following table shows wrapper classes for converting simple types: Simple Type Wrapper
Class
boolean Boolean
char
float Float
doubleDouble
int
long Long
Character
Integer
- The wrapper classes have number of unique method for handling primitive data typeand objects.
=========================
Strings:
=========================
String is a sequence of characters.
Collection of characters is known as String.
String is a predefined class which is present under java.lang package.
String should be represented by using double quotation.
The easiest way to represent string in java is by using character array.
Example:
char name[]=new char[4];
name[0]='J';
name[1]='a';
name[2]='v';
name[3]='a';
• By using above approach, we require lot of overhead to manage the string.- For example, copy one
character array into another array is difficult due to size issues.
• In java, we have one good approach to manage string i.e creation of string class object.
• This class provides lots of good methods to manipulate string.
Syntax:
Example:
String strName="Value"; OR
String strName=new String("String");
String firstName="Vishal";
String firstName=new String("Vishal");
In java, we use + operator as concatenation operator.String Arrays:
We can also create and use arrays that contain strings.
Example:
String x[]=new String[5];
In above example, we can see string name is x and its size is 5. It means we can hold five string constants.
String Methods:
String class provides different methods.
public class StringMethodsDemo {
public static void main(String args[]) {
String str = "Jaihind";
StringBuffer class:
====================
StringBuffer is a peer class of String.
String class creates fixed length of string.
StringBuffer class creates flexible length of string.
We can insert characters and substring in the middle of the string.
We can append another string to the end.
Some methods of String class also supported in StringBuffer class.
Commonly used StringBuffer methods:
s1.setCharAt(n,'x') - modifies the nth character to x.
s1.append(s2) - Appends the string s2 to s1 at the end.
s1.insert(n,s2) - Inserts the string s2 at the position n of the string s1.
s1.setLength(n) - Sets the length of string s1.
s1.length() - Gives the length of s1.
s1.charAt(n) - Gives the nth character of s1.
s1.equals(s2) - Return true if s1 is equal to s2
- Example:
//StringBuffer class
class StringBufferDemo
{
public static void main(String args[])
{
StringBuffer str=new StringBuffer("Kuran");
System.out.println("Original String :"+str);
System.out.println("Length of String :"+str.length());
for(int i=0;i<str.length();i++)
{
System.out.println("Character at position "+i+" is
"+str.charAt(i));
}
str.setCharAt(3,'T'); System.out.println("Modified String :"+str);
str.append("Academy");
System.out.println("Appended String :"+str) ;
}
}
Array Vector
The Array can store similar type of values Vectors can store any type of objects
Methods are not provided for adding and Methods are provided for adding and removing
removing the element from the array the element from the Vector.
The size of array needs to be declared in No need to declare the size of the vector. You
advance. may give its size & you may not.
The Array can store primitive data types Vector can store only object
String StringBuffer
The length of the String object is fixed. The length of the StringBuffer can be increased.
String objects are stored in a constant pool StringBuffer objects are stored in heap memory.
String objects provides less functionality to the StringBuffer objects provide more functionality
strings as compared to the class StringBuffer to the strings as compared to the class String.