UNIT 2
Classes and objects
Class: A class is blueprint that defines the variables and the methods
common to all object of a certain kind.
Creating a Class
We create a class in java using the class keyword.
Syntax:
class ClassName
{
//fields //methods
}
Here, fields(variable) used store data and method are used to perform operation.
Creating an Object
Object: is called instance of class.
Syntax:
className Object = new className();
Here, new is a keword along with the constructor of class to create object.
Example Program to illustrate class and object
Class Bicycle
{
//state or fields
int gear=5;
//method
public void braking()
{
[Link](“working of Brake”);
}
public static void main(String args[])
{
//creating object Bicycle
sportsBicycle=new Bicycle();
//accessing field and method
[Link]; [Link]();
}
}
0U TPUT
5
working of Brake
Constructors
Constructor is block of codes Similar to method. It is called when an instance of
the class is created. At the time of calling constructor, memory for object is
allocated in the memory.
Rules to be followed for writing a constructor
• The name of the constructor is same as the name of the class.
• A constructor, even though it is a function there is no return type for constructor
(not even void) .
• A constructor is invoked automatically when objects are created. Constructor
can have default arguments.
• A class can have more than one constructor. And constructor cannot be abstract
,static and final
• The constructor makes implicit calls of the operators new when memory
allocation is required.
• They cannot be inherited, though a derived class can call the base class
constructor.
Syntax :
class ClassName
{
ClassName()
{ …………………
…………………
}
}
Types of Constructors In Java
There are two types of constructors:
1)Default Constructor
2)Parameterized Constructor
1)Default Constructor: A Constructor is called “Default Constructor” when it
doesn’t have any parameter.
Syntax:
ClassName()
{ ……….
}
Example Program to illustrate Default Constructor
class Bike1
{
Bike1()
{
//default constroctor
[Link](“Bike is create”);
}
public static void main(String args [] )
{
//calling a default constroctor
Bike1 b = new Bike1();
}
}
Output:
Bike is create
2)Parameterized Constructor: Constructor which has a specific number of
parameters is called a parameterized Constructor.
Example Program to illustrate parameterized Constructor
class Student1
{
int id;
String name;
Student1 (int i, String n)
{
id=i; name=n;
}
Void display()
{
[Link](+id“ ”+name);
}
public static void main(String args [] )
{
Student1 s1 = new Student1 (101,”Sindu”);
Student1 s2 = new Student1 (102,”Ananya”);
[Link]();
[Link]();
}
}
Output:
101 Sindu
102 Ananya
Constructor Overloading in Java
Constructor Overloading is technique of having more than one constructor
with different parameter list.
Example Program to illustrate Constructor Overloading
class Student2
{
int id;
String name;
int age;
Student2 (int i, String n)
{
id=i; name=n;
}
Student2 (int i, String n, int a)
{
id=i; name=n; age=a;
}
void display()
{
[Link](+id“ ”+name+” “+age);
}
public static void main(String args [] )
{
Student1 s1 = new Student1 (101,”karan”);
Student1 s2 = new Student1 (102,”Pooja”,19);
[Link](); [Link]();
}
}
Output:
101 karan
102 Pooja 19
Method overloading
that enables defining several methods in a class having the same name but with
different parameters lists.
1. // Class Adder contains overloaded methods to add numbers
2. class Adder {
3. // Method to add two integers
4. static int add(int a, int b) {
5. return a + b;
6. }
7. // Method to add two doubles
8. static double add(double a, double b) {
9. return a + b;
10. }
11. }
12. public class Main {
13. public static void main(String[] args) {
14. // Calling the add method with two integers
15. [Link]([Link](11, 11)); // Output: 22
16. // Calling the add method with two doubles
17. [Link]([Link](12.3, 12.6)); // Output: 24.9
18. }
19. }
Visibility Modifiers OR Access modifiers
There are four types of Java Visibility modifiers:
1. Private: The access level of a private modifier is only within the class. It
cannot be accessed from outside the class.
2. Default: The access level of a default modifier is only within the package.
It cannot be accessed from outside the package. If you do not specify any
access level, it will be the default.
3. Protected: The access level of a protected modifier is within the package
and outside the package through child class. If you do not make the child class,
it cannot be accessed from outside the package.
4. Public: The access level of a public modifier is everywhere. It can be
accessed from within the class, outside the class, within the package and
outside the package.
Static Members
Variables and methods declared using keyword static are called static
members of a class.
You know that non-static variables and methods belong to instance. But
static members (variables, methods) belong to class.
Static members are not part of any instance of the class.
Static members can be accessed using class name directly, in other
words, there is no need to create instance of the class specifically to use
them.
Static members have three types
1)Static variable
2)Static method.
3)Static blocks
Static Variables
Static variables are also called class variables because they can be
accessed using class name, whereas,
Static variables occupy single location in the memory.
• Class variables also known as static variables are declared with the
static keyword in a class, but outside a method, constructor or a block.
•Static variables are created when the program starts and destroyed
when the program stops.
• Visibility is similar to instance variables. However, most static
variables are declared public since they must be available for users of
the class.
• Static variables can be accessed by calling with the class name
[Link].
Static Methods/Class Methods
Static methods are also called class methods.
A static method belongs to class, it can be used with class name directly.
It is also accessible using instance references.
Static methods can use static variables only, whereas non-static
methods can use both instance variables and static variables.
Static blocks:
It is used to in order to initialize the static variables
A static block in Java is a code associated with the static keyword,
executed only once when the class is loaded into memory by the
Java ClassLoader.
It is used for static initialization of a class, ensuring that certain
fields or operations are performed just once, typically at the
beginning of the program’s execution.
Syntax: static
{
………….
…………
}
// Java program to demonstrate static members
class Example
{
// Static variable
static int count;
// Static block (executes once when the class is loaded)
static
{
count = 0;
[Link](“Static block executed. Initial count: “ + count);
}
// Constructor
Example()
{
count++; // Increment count for every object created
}
// Static method
static void displayCount()
{
[Link](“Total objects created: “ + count);
}
}
public class StaticDemo {
public static void main(String[] args) {
// Creating objects
Example obj1 = new Example();
Example obj2 = new Example();
Example obj3 = new Example();
// Calling static
method without an object
[Link]();
}
}
‘this’ keyword in Java
In Java, this keyword is a reference variable that refers to the current
object.
Usage of Java this keyword
1. this can be used to refer current class instance variable.
2. this can be used to invoke current class method (implicitly)
3. this() can be used to invoke current class constructor.
4. this can be passed as an argument in the method call.
5. this can be passed as argument in the constructor call.
6. this can be used to return the current class instance from the method.
Example
class Student
{
int rollno;
String name;
float fee;
Student(int rollno,String name,float fee)
{
[Link]=rollno;
[Link]=name;
[Link]=fee;
}
void display()
{
[Link](rollno+” “+name+” “+fee);
}
}
public class Main
{
public static void main(String args[])
{
Student s1=new Student(111,”ankit”,5000f);
Student s2=new Student(112,”sumit”,6000f);
[Link]();
[Link]();
}
}
Output:
111 ankit 5000.0
112 sumit 6000.0
Arrays
An array is a collection of similar type of elements, which has
contiguous memory location.
It is a data structure where we store similar elements. We can store only a fixed
set of elements in a Java array.
Array in Java is index-based, the first element of the array is stored at the 0th
index, 2nd element is stored on 1st index and so on.
Types of Array in java
There are two types of array.
1. Single Dimensional Array
2. Multidimensional Array
SINGLE DIMENSIONAL ARRAY (one dimensional array):
• A list of items can be given one variable name using only one subscript
and such a variable is called one dimensional array.
• One dimensional array is a list of variables of same type that are
accessed by a common name.
• An individual variable in the array is called an array element.
Declaration of arrays:
• To declare an array below is a general form or syntax.
Datatype arrayName[ ];
Where, Datatype is valid data type in java and arrayName is a name of an
array.
Example : int physics[ ];
Creation of arrays
• To allocate space for an array element use below general form or
syntax.
arrayName = new type[size];
Where arrayName is the name of the array and type is a valid java
datatype and size specifies the number of elements in the array.
Example: physics = new int[10];
Above statement will create an integer of an array with ten elements
that can be accessed by physics.
physics[0]
Structure of one dimensional array physics[1]
• Note that array indexes begins with zero.
physics[2]
• That means if you want to access 1st element of an array use zero
physics[3]
as an index.
• To access 3rd element refer below example. physics[4]
• physics[2] = 10; // it assigns value 10 to the third element of an physics[5]
array.
physics[6]
• java also allows an abbreviated syntax to declare an array. General
form or syntax of is is as shown below. physics[7]
physics[8]
physics[9]
Initialization of an Array
The final step is to put values into the array created. This process is
known as initialization. Syntax:
arrayname[subscript] = value;
Example:
physics[0]=12;
physics[1]=15;
physics[2]=16;
physics[3]=18;
physics[4]=20;
physics[5]=23;
physics[6]=25;
physics[7]=27;
physics[8]=30;
physics[9]=35;
Example Program:
class Testarray
{
public static void main(String args[])
{
int a[]=new int[5];//declaration and
instantiation a[0]=10;//initialization
a[1]=20; a[2]=70; a[3]=40;
a[4]=50; //printing array
for(int i=0;i<[Link];i++)//length is the property of array
[Link](a[i]);
}
}
Output:
10
20
7
0
4
0
50
Example for Declaration, Instantiation and Initialization of Java Array
We can declare, instantiate and initialize the java array together by:
int a[]={33,3,4,5};//declaration, instantiation and
initialization Let's see the simple example to print this array.
class Testarray1
{
public static void main(String args[])
{
int a[]={33,3,4,5};//declaration, instantiation and initialization
//printing array
for(int i=0;i<[Link];i++)//length is the property of array
[Link](a[i]);
}
}
TWO DIMENSIONAL ARRAY:
• Two Dimensional Array in Java is the simplest form of Multi-
Dimensional Array.
• In Two Dimensional Array, data is stored in row and columns.
• The record can access using both the row index and column index.
Declaration of Two Dimensional Array in Java
Following the format of declaration of two-dimensional array in Java
Programming Language:
Syntax:
DataType ArrayName[][];
ArrayName = new
DataType[][]; (or) DataType
ArrayName[][] = new
DataType[][];
Data_type:
• This will decide the type of elements it will accept.
• For example, If we want to store integer values then, the Data Type will
be declared as int, If we want to store Float values then, the Data Type
will be float etc.
Array_Name:
• This is the name you want to give it to array.
• For example Car, students, age, marks, department, employees etc
Creating of Two Dimensional Array in java
int[][] a = new int[3][4];
• Here, a is a two-dimensional array. The
array can hold maximum of 12 elements of
type int.
• Java uses zero-based indexing, that is,
indexing of arrays in Java starts with 0 and
not 1.
Intialization of Array:
int[][] a =
{
{1 , 2 , 3} ,
{4 , 5 , 6 , 9} ,
{7} ,
};
Example:
class MultidimensionalArray
{
public static void main(String[] args)
{
int[][] a = {
{1, 2, 3},
{4, 5, 6, 9},
{7},
};
[Link]("Length of row 1: " + a[0].length);
[Link]("Length of row 2: " + a[1].length);
[Link]("Length of row 3: " +
a[2].length);
}
}
Output:
Length of
row 1: 3
Length of
row 2: 4
Length of row 3: 1
Array of Objects in Java
Java is an object-oriented programming language. Most of the work
done with the help of objects. Java allows us to store objects in an
array.
In Java, the class is also a user-defined data type. An array that
conations class type elements are known as an array of objects. It
stores the reference variable of the object.
Creating an Array of Objects
Before creating an array of objects, we must create an instance of the
class by using the new keyword. We can use any of the following
statements to create an array of objects.
Syntax:
1. ClassName obj[]=new ClassName[array_length];
//declare and instantiate an array of objects
Or
1. ClassName[] objArray;
Or
1. ClassName objeArray[];
Suppose, we have created a class named Employee. We want to keep
records of 20 employees of a company having three departments. In this
case, we will not create 20 separate variables.
Instead of this, we will create an array of objects, as follows.
1. Employee department1[20];
2. Employee department2[20];
3. Employee department3[20];
The above statements create an array of objects with 20 elements.
Let's create an array of objects in a Java program.
In the following program, we have created a class named Product and
initialized an array of objects using the constructor. We have created a
constructor of the class Product that contains product id and product name.
In the main function, we have created individual objects of the class
Product. After that, we have passed initial values to each of the objects
using the constructor.
Example,
[Link]
public class ArrayOfObjects
{
public static void main(String args[])
{
//create an array of product object
Product[] obj = new Product[5] ;
//create & initialize actual product objects using constructor
obj[0] = new Product(23907,"Dell Laptop");
obj[1] = new Product(91240,"HP 630");
obj[2] = new Product(29823,"LG OLED TV");
obj[3] = new Product(11908,"MI Note Pro Max 9");
obj[4] = new Product(43590,"Kingston USB");
//display the product object data
[Link]("Product Object 1:");
obj[0].display();
[Link]("Product Object 2:");
obj[1].display();
[Link]("Product Object 3:");
obj[2].display();
[Link]("Product Object 4:");
obj[3].display();
[Link]("Product Object 5:");
obj[4].display();
}
}
//Product class with product Id and product name as attributes
class Product
{
int pro_Id;
String pro_name;
//Product class constructor
Product(int pid, String n)
{
pro_Id = pid;
pro_name = n;
}
public void display()
{
[Link]("Product Id = "+pro_Id + " " + " Product Name = "+pro_na
me);
[Link]();
}
}
Output:
Product Object 1:
Product Id = 23907 Product Name = Dell Laptop
Product Object 2:
Product Id = 91240 Product Name = HP 630
Product Object 3:
Product Id = 29823 Product Name = LG OLED TV
Product Object 4:
Product Id = 11908 Product Name = MI Note Pro Max 9
Product Object 5:
Product Id = 43590 Product Name = Kingston USB
String
String is the sequence of characters that is enclosed by double quotes.
Syntax:
<String_Type><string_variable>=“<sequence_of_string>”;
Example:
String name = “Geeks”;
String num = “1234”
// Java Program to demonstrate String
public class Geeks {
// Main Function
public static void main(String args[])
{
// creating Java string using new keyword
String str = new String("GeeksforGeeks");
[Link](str);
}
}
Output
GeeksforGeeks
Ways of Creating a Java String
There are two ways to create a string in Java:
String Literal
Using new Keyword
1. String literal (Static Memory)
To make Java more memory efficient (because no new objects are created
if it exists already in the string constant pool).
Example:
String s1 = “GeeksforGeeks”;
2. Using new keyword (Heap Memory)
String s = new String(“Welcome”);
Example:
String demoString = new String (“GeeksforGeeks”);
Here are some common string handling functions in Java with examples:
1. charAt(int index): Returns the character at the specified index.
Stringstr="Hello";
char firstChar = [Link](0); // firstChar = 'H'
2. length(): Returns the number of characters in the string.
Stringstr="Hello";
int length = [Link](); // length = 5
[Link]() and toLowerCase(): Converts the string to uppercase or
lowercase, respectively.
String str = "Hello";
String upperCase = [Link](); // upperCase = "HELLO"
String lowerCase = [Link](); // lowerCase = "hello"
4. a) substring(int beginIndex)
b) substring(int beginIndex, int endIndex): Extracts a substring from the
string.
String str = "Hello World";
String sub1 = [Link](6); // sub1 = "World"
String sub2 = [Link](0, 5); // sub2 = "Hello"
[Link](char oldChar, char newChar): Replaces all occurrences of a
character with another character.
String str = "Hello World";
String replaced = [Link]('l', 'x'); // replaced = "Hexxo Worxd"
[Link](String str): Returns the index of the first occurrence of a substring in
the string
String str = "Hello World";
int index = [Link]("World"); // index = 6
[Link](String anotherString): Checks if two strings are equal (case-
sensitive).
String str1 = "Hello";
String str2 = "Hello";
boolean isEqual = [Link](str2); // isEqual = true
8. split(String regex): Splits the string into an array of strings based on a regular
expression.
String str = "apple,banana,orange";
String[] fruits = [Link](","); // fruits = {"apple", "banana", "orange"}
9. trim():Removes leading and trailing whitespace from the string.
String str = " Hello World ";
String trimmed = [Link](); // trimmed = "Hello World"
10)String Concatenation():Concatenation means joining two or more strings
together. In Java, you can use the “+” operator to concatenate strings:
String1 firstName = "Ram";
String2 lastName = "Dev";
String3 fullName = firstName + " " + lastName;
// String3 ="Ram Dev"
11)Comparing Strings:You can compare strings to see if they are equal or not
using the equals() method:
String str1 = "Hello";
String str2 = "World";
boolean are Equal = [Link](str2); // Returns false
12)a) String StartWith():check whether the string start with the specified string
or not.
Syntax:Boolean startwith(string s);
S1=”Ram”;
S2=”Ramdas”
A=[Link](s2)
//return true
b) String EndsWith():check whether the string ends with the specified
string or not.
Boolean endssWith(string s);
S1=”Ram”;
S2=”Ramdas”;
A=[Link](string s2);
// return false