0% found this document useful (0 votes)
52 views39 pages

U2 Java

The document discusses strings in Java. It defines a string as a group of characters and describes three ways to create strings - by assigning characters to a string variable, using the new operator, and by converting character arrays. It states that strings in Java are immutable and provides an example to demonstrate this. It then discusses various string methods like toLowerCase(), trim(), equals(), length(), charAt(), etc and provides a sample program to illustrate these methods. It also describes the StringBuffer class for creating mutable strings and some of its methods like append(), insert(), reverse(), etc. Finally, it discusses three ways to compare strings in Java - using the equals() method, == operator, and compareTo() method.

Uploaded by

venkat m
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
52 views39 pages

U2 Java

The document discusses strings in Java. It defines a string as a group of characters and describes three ways to create strings - by assigning characters to a string variable, using the new operator, and by converting character arrays. It states that strings in Java are immutable and provides an example to demonstrate this. It then discusses various string methods like toLowerCase(), trim(), equals(), length(), charAt(), etc and provides a sample program to illustrate these methods. It also describes the StringBuffer class for creating mutable strings and some of its methods like append(), insert(), reverse(), etc. Finally, it discusses three ways to compare strings in Java - using the equals() method, == operator, and compareTo() method.

Uploaded by

venkat m
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 39

Page no- 1

UNIT-II, STRINGS
Q). What is a String? How to creating strings in java?

“A group of characters is called a string”. In C/C++ languages, a string represents an array of


characters, where the last character will be '\0'. But this is not valid in java. In Java a string is an
object of String class.

Creating strings: There are three ways to create strings in Java:

1. We can create a string just by assigning a group of characters to a string type variable:

String s; //declare String type variable

s="Hello"; //assign a group of characters to it

The two statements can be combined and written as:

String s="Hello";

2. We can create an object to String class by allocating memory using new operator. This is just
like creating an object to any class, like given here:
String s= new String("Hello");

Here, we are doing two things. First, we are creating object using new operator.

Then, we storing the string: "Hello" into the object.

3. The third way of creating the strings is by converting the character arrays into strings. Let us
take a character type array: arr[] with some characters, as :

char arr []= ('c', 'h', 'a', 'i', 'r', 's'};


Now create a string object, by passing the array name to it, as:

String s= new String(arr);

Now the String object 's' contains the string: "chairs". This means all the characters of the array
are copied into the string. If we do not want all the characters of the array into the string, then we
can also mention which characters we need, as:

String s= new String(arr, 2, 3);

Here, starting from 2nd character a total of 3 characters are copied into the strings.

Q). Immutability of strings:

Immutability of strings:

We can divide objects broadly as, mutable and immutable objects.

Mutable:- Mutable objects are those objects whose contents can be modified.

Immutable:- Immutable objects are those objects, once created cannot be modified.

Prepared by: M.VENKAT (MCA, M-Tech) Lecturer in Computer Science


Page no- 2

And String class objects are immutable. Let us take a program to understand whether the String
objects are immutable or not.

Program: Write a program to test the immutability of strings.

class Test
{
public static void main(String arg[])
{
string s1="data";
string s2=new string("base");
s1=s1 + s2
System.out.println(s1);
}
}

Output:
C:> javac Test.java
C:\>java Test
Database

Q). String Methods (Methods of String class):

In java Strings are class objects and implemented using two classes, namely String and
StringBuffer. A java string is an instantiated object of the string class. A java string is not a
character array and not a NULL terminated. String may be declared and created as follows

Syntax:

String string_name= new String(“string”);


Example:
String country= new String(“India”);

String Methods:

The String class defines a number of methods that allow us to accomplish a variety of string
manipulation tasks. Some most commonly used string methods.
Method Call Task Performed
s2 = s1.toLowerCase(); Converts the String s1 to all lowercase
s2 = s1.toUpperCase(); Converts the String s1 to all Uppercase
s2 = s1.replace(‘x’, ‘y’); Replace all appearances of x with y
s2 = s1.trim(); Remove white spaces at the beginning and
end of String s1
s1.equals(s2) Returns ‘true‘ if s1 is equal to s2

Prepared by: M.VENKAT (MCA, M-Tech) Lecturer in Computer Science


Page no- 3

s1.equalsIgnoreCase(s2) Returns ‘true‘ if s1=s2, ignoring the case of


characters
s1.length() Gives the length of s1
s1.CharAt(n) Gives nth character of s1
s1.compareTo(s2) Returns negative value if s1<s2, positive value
if s1>s2, and
0 if s1 is equal s2
s1.compareToIgnoreCase(s2) Returns negative value if s1<s2, positive value
if s1>s2, and
0 if s1 is equal s2, ignoring the case of
characters
s1.concat(s2) Concatenates s1 and s2
s1.subString(n) Gives the substring starting from nth character
s1.subString(n, m) Gives the substring starting from n th character
up to m
(excluding m)
s1.startsWith(‘x’) Returns true if s1 starts with ‘x’
s1.endsWith(‘x’) Returns true if s1 ends with ‘x’

Write a Java Program illustrates the concept of String class methods


import java.lang.*;
class StringMethods
{
public static void main(String ar[])
{
String s1 = new String(" JAVA IS SECURE ");
String s2 = new String(" Java is robust");

System.out.println(s1);
System.out.println(s2);
System.out.println(s1.toLowerCase());
System.out.println(s1.toUpperCase());
System.out.println(s1.replace('I', 'i'));
System.out.println(s1.trim());
System.out.println(s1.equals(s2));
System.out.println(s1.equalsIgnoreCase(s2));
System.out.println(s1.length());
System.out.println(s1.charAt(3));
System.out.println(s1.compareTo(s2));
System.out.println(s1.compareToIgnoreCase(s2));
System.out.println(s1.concat(s2));
System.out.println(s2.substring(4));
System.out.println(s2.substring(0,6));
System.out.println(s2.startsWith(" "));
System.out.println(s2.endsWith(" "));
}

Output:

Prepared by: M.VENKAT (MCA, M-Tech) Lecturer in Computer Science


Page no- 4

StringBuffer Class
Java StringBuffer class is used to create mutable (modifiable) String objects. The StringBuffer
class in Java is the same as String class except it is mutable i.e. it can be changed.
Method Task
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

// Java program on StringBuffer class methods


import java.lang.*;
class StringManipulation
{
public static void main(String args[])
{
StringBuffer s = new StringBuffer(" JAVA");
System.out.println(s);
System.out.println(s.length());
System.out.println(s.append("DataStructures"));
System.out.println(s.insert(3, "v"));
System.out.println(s.reverse());
}
}
Output:

Java String compare

In java we can’t use (>,<,>=,<=) symbols for string comparison, We can compare String in Java on
the basis of content and reference. It is used in authentication.

There are three ways to compare String in Java:

1. equals() Method
2. Using == Operator
3. compareTo() Method

1) equals() Method

The String class equals() method compares the original content of the string. It compares values of
string for equality. String class provides the following two methods:

 public boolean equals(Object another) compares this string to the specified object.


 public boolean equalsIgnoreCase(String another) compares this string to another string,
ignoring case.

Teststringcomparison1.java

Prepared by: M.VENKAT (MCA, M-Tech) Lecturer in Computer Science


Page no- 5

class Teststringcomparison1
{  
 public static void main(String args[])
{  
   String s1="Virat";  
   String s2="Virat";  
   String s3=new String("Virat");  
   String s4="Kohli";  
   System.out.println(s1.equals(s2)); //true  
   System.out.println(s1.equals(s3)); //true  
   System.out.println(s1.equals(s4)); //false  
 }  
}  
In the above code, two strings are compared using equals() method of String class. And the
result is printed as boolean values, true or false.
2) == operator

The == operator compares references not values.

eststringcomparison3.java
class Teststringcomparison3
{  
 public static void main(String args[])
{  
   String s1="Virat";  
   String s2="Virat";  
   String s3=new String("Virat");  
   System.out.println(s1==s2); //true (because both refer to same instance)  
   System.out.println(s1==s3); //false(because s3 refers to instance )   
}  
}
3) compareTo() method

The String class compareTo() method compares values lexicographically and returns an
integer value that describes if first string is less than, equal to or greater than second string.

Suppose s1 and s2 are two String objects. If:

 s1 == s2 : The method returns 0.


 s1 > s2 : The method returns a positive value.
 s1 < s2 : The method returns a negative value.

Teststringcomparison4.java

class Teststringcomparison4
{  
 public static void main(String args[])
{  
   String s1="Virat";  
   String s2="Virat";  
   String s3="Kohli";  
   System.out.println(s1.compareTo(s2)); //0  
   System.out.println(s1.compareTo(s3)); //1(because s1>s3)  
   System.out.println(s3.compareTo(s1)); //-1(because s3 < s1 )  

Prepared by: M.VENKAT (MCA, M-Tech) Lecturer in Computer Science


Page no- 6

 }  
}  

Introduction to OOPs

Object-Oriented Programming

Definition:
Object-Oriented Programming is an approach that provides a way of modularizing programs
by creating partitioned memory area for both data and methods that can be used as
templates for creating copies of such modules on demand.

Object-Oriented Paradigm
The major objective of Object-Oriented approach is to eliminate some of the Drawbacks
encountered in the Procedural approach. OOP treats data as critical element in the program
development and does not allow the data to flow freely around the system. “It ties data more
closely to the methods that operate on it and protects it from accidental modification from
outside functions”.

The data of an object can be accessed only by the methods associated with the object. However
methods of one object can access the methods of other objects.

OOP allows us to decompose a problem into a number of entities called Objects. The
combination of data and methods make up an object.

Some of the features of Object-Oriented Paradigm are as follows:


 Emphasis is on data rather than procedure.
 Programs are divided into what are known as Objects.
 Data is hidden and cannot be accessed by external functions.
 Objects may communicate with each other through methods.
 New data and methods can be easily added whenever necessary.
 Follows bottom-up approach in program design.

Prepared by: M.VENKAT (MCA, M-Tech) Lecturer in Computer Science


Page no- 7

Fig. Organization of data and methods in OOP

OOP’s Principles (or) OOP’s Concepts


The data in the Object Oriented Programming language is secure. Examples of Object Oriented
Programming Languages are (LISP, ADA, ALGOL, SMALLTALK, OBJECT COBAL, OBJECT PASCAL,
CPP, JAVA, DOT NET, etc).
In order to say any language is an Object Oriented Programming Language it has to satisfy the
following principles of OOPs.

1. Object
2. Class
3. Data Abstraction and Data Encapsulation
4. Inheritance
5. Polymorphism
6. Dynamic Binding
7. Message Passing

1. Object
Objects are the real word entity (or) runtime entities in an object-oriented system. Objects are
closely matched with real world objects. Object may represent a person (or) a place, (or) table
of data (or) any item that can be handled by program. In order to store the data for the data
members of the class, we must create an object.

An object contains properties and actions.


Properties are represented by variables (data) memory location.
Actions are represented by methods.

Example: A dog is an object because it has states like color, name, breed, etc. as well as
behaviors like wagging the tail, barking, eating, etc.

Prepared by: M.VENKAT (MCA, M-Tech) Lecturer in Computer Science


Page no- 8

Definitions of an Object
 Instance of a class is known as an object.
 Class variable is known as an object.
 Real world entities are called as Objects.
The following figure is the representation of an object
Object: student
Data:
name;
regdno;

Methods:
marks();
total();
avg();
result();

Fig: Representation of an Object


While the program is running, the objects interact by sending messages to one another.

2. Class
“Collection of objects is called class”. It is a logical entity. A class is model for an object, and it is
a blue print of an object.
Once class has been defined, we can create any number of objects belongs to that class. Each
class is associated with data and methods.

For example mango, apple and banana are objects of fruit class. The syntax used to create
object is no different than the syntax used to create an integer object in C.
 If fruit has been defined as a class, then the statement
 fruit mango; // will create an object mango belonging to the class fruit.

Fig. Representation of class

Syntax for defining a class

Note: Any JAVA program can be developed with respect to Class only i.e., without Class there
is no JAVA program.

Prepared by: M.VENKAT (MCA, M-Tech) Lecturer in Computer Science


Page no- 9

3. Data Abstraction and Data Encapsulation


Data Abstraction is a mechanism of representing essential features without including the
background details (or) explanations. It is a Technique of creating Abstract Data Type(ADT).

(Classes use the concept of abstraction and are defined as a list of abstract attributes such as
size, weight and cost, and methods that operate on these attributes)

Ex:- While driving a car, you don’t have to concern with its internal working details, here we
need to concern about the parts like Steering, wheels, accelerators, Breaks, etc.

Data Encapsulation
The wrapping up (Combining) of data and methods into a single unit is known as
Encapsulation. Encapsulation is the most important feature of a class.

The data is not accessible to the outside world, but this Encapsulation provides direct access to
data. By this direct access the program is called data hiding or information hiding.

Ex:- In a college a student cannot exist without a class.


4. Inheritance
Inheritance is the process by which one class objects acquire the properties of another class
objects. i.e. one child object acquire the properties of parent class object, it is also called
parent child relationship b/w two classes.
Inheritance supports the concept of hierarchical classification. The concept of inheritance
provides the idea of reusability. This means that we can add additional features to an existing
class without modifying it. This is possible by deriving a new class from the existing class.
The new class will have the combined features of both existing and new class. Inheritance
avoids the redundant code.

AKNU
COURSES

COLLEGE-2 COLLEGE-3
COLLEGE-1
COURSES COURSES
COURSES

UG PG UG PG UG PG
COURSES COURSES COURSES COURSE COURSE COURSES
S S
Fig. Inheritance

5. Polymorphism
Polymorphism is another important OOP concept. Polymorphism, a Greek term, it means the
ability to take more than one form is called Polymorphism.

Prepared by: M.VENKAT (MCA, M-Tech) Lecturer in Computer Science


Page no- 10

The word Polymorphism means combining the two words i.e Poly & Morphism, poly means
many, morphism means availability.

For example, an operation may exhibit different behavior in different instances. The behavior
depends upon the types of data used in the operation. It supports two concepts.

a. Operator Overloading:
The process of making an operator to exhibit different behaviors in different instances is
known as operator overloading i.e. a single operator can perform different operations.
Ex. If the operands are two numbers then the operator is sum i.e., 2 + 3= 5.
If the operands are strings then the operator is concatenation.
b. Function Overloading:
A single function name is used to perform different types of tasks is known as function
overloading. The following is an example for polymorphism concept.

Fig. Polymorphism
6. Dynamic Binding
Binding refers if the code is associated with class function, we can’t identify that until the code
has been executed in run time, it is also called Dynamic binding. It is associated with the
polymorphism and inheritance.

7. Message Passing
The OOP’s consists of a set of objects that communicate with each other. Objects
communicate with one to another by sending and receiving information.
Exchanging the data between multiple objects is known as Message Passing. Objects
communicate with one another by sending and receiving information much the same way as
people pass message to one another.

Prepared by: M.VENKAT (MCA, M-Tech) Lecturer in Computer Science


Page no- 11

Q). Benefits of OOP


The following are the some of the benefits of Object Oriented Programming language
 Through Inheritance, we can eliminate redundant code and extend the use of existing
class.
 The data is designed in simple approach.
 OOPs provide easy understanding and clear module structure for programe.
 By using inheritance we can get the reusability.
 The principle of data hiding helps the programmer to build the secure programs.
 It is easy to partition the work in a project based on objects.
 Object oriented systems can be easily upgraded from small to large systems.
 Software complexity can be easily managed.
Disadvantages:-
 It require more data protection.
 Inadequate for concurrent problems.
 Inability to work existing system.
 Compile time and runtime overheads.
 Unfamilarized causes tracing overheads.
 Data and operations are separated.

Applications of OOP
OOPS applications are very important because of it is used in many areas like windows has
a more popular application in the OOPS. It is designed by interface with oops. The number of
windows systems developed by oops technique, like business system and commercial systems, etc
The following are some of areas of Object Oriented Programming
 Real-Time systems
 Simulation and modeling
 Object oriented databases
 Hypertext, hypermedia and expert text.
 Parallel programming.
 AI and expert systems.
 Designing supports
 Cam//Cad
 Neural networks and parallel programming.
 Decision support and office automation systems.

Difference Between Procedural and Object-Oriented Programming

Procedural-Oriented Programming Object-Oriented Programming


1. It is a procedural oriented 1. It is a object based programming
programming language. language.
2. It is known as POP 2. It is known as OOP.
3. Top-down approach. 3. Bottom-up approach.
4. Access modifiers are not 4. Access modifiers are supported.
supported.
5. Functions are preferred over data. 5. Security and accessibility is preferred.
6. Runs faster than OOP. 6. Runs slower the POP.

Prepared by: M.VENKAT (MCA, M-Tech) Lecturer in Computer Science


Page no- 12

7. If size of the problem is small, POP 7. If the size of the problem is big, OOP
is preferred. is preferred.
8. In POP overloading is not possible 8. In OOP overloading is possible
9. POP does not have hiding 9. OOP has hiding security, so it is a
security, so it is less security highly secured

Q). What are the limitations of procedural programming?

The limitations of procedural programming are:

1. Procedural programming mainly focuses on procedures (or) functions. Less attention is given
to the data.
2. The data and functions are separate from each other.
3. Global data is freely moving and is shared among various functions. Thus, it becomes difficult
for programmers to identify and fix issues in a program that originate due to incorrect data
handling.
4. Changes in data types need to be carried out manually all over the program and in the
functions using the same data type.
5. Limited and difficult code reusability.
6. It does not model real-world entities (e.g., car, table, bank account, loan) very well where we
as a human being, perceive everything as an object.
7. The procedural programming approach does not work well for large and complex systems.

Prepared by: M.VENKAT (MCA, M-Tech) Lecturer in Computer Science


Page no- 13

Classes and Objects


1. Classes
2. Objects
3. Initializing the instance variables
4. Access specifier
5. Constructors

Classes, Objects

1. Defining a Class

“The process of binding the ‘data members’ and ‘member functions’ into a single unit is
called as a class”. In other words a class is a user defined data type. Once the class type has
been defined, we can create “variables” of that type. In java these variables are termed as
instances of class, which are the actual objects.
The basic form of a class definition is as follows;

class <sub_classname> [extends <super_classname>]


{

[fields declaration;]

[methods declaration]
}

Here, sub_classname and super_clsname are any valid java identifiers. The keyword extends
indicates that the properties of the super_classname class are extended to the sub_classname
class. This concept is called as Inheritance.
Everything inside the square brackets is optional. This means that the following would be a
valid class definition.
class <class-name>
{

Here, the body of the class is empty; this does not contain any properties and therefore cannot
do anything.

i). Field Declaration(Adding variables)


Data is encapsulated in a class by placing data fields inside the body of the class definition.
These variables are called Instance Variables because they are created whenever an object of
the class is Instantiated.

We can declare the instance variables exactly the same way as we declare the local variables.

Prepared by: M.VENKAT (MCA, M-Tech) Lecturer in Computer Science


Page no- 14

Syntax:
type < variable1,…… >

Example:
class Rectangle
{
int length; // Instance variable declaration
int width; // Instance variable declaration
}

The class Rectangle contains two integer type instance variables (length, width). Here, these
variables are only declared and therefore no storage space has been created in the memory.
Instance variables are also known as Member Variables.

ii). Methods Declaration


A class with only data fields has no life. The objects created by no data field class cannot
respond to any messages. Methods are declared inside the body of the class but immediately
after the declaration of instance variables. The general form of a method declaration is as
follows.
type method_name( parameter_list)
{
Method-body;
}

Method declaration has four basic parts:


1. type:- defines the type of the value.
2. method_name:- defines the name of the method.
3. parameter_list:- defines the list of parameters.
4. Method-body:- defines the body of the method.

Let us consider a Rectangle class example as follows:


class Rectangle
{
int length, width;

void getData( int x, int y) // Method declaration


{
length=x;
width=y;
}

int rectArea() // Method Declaration


{
Int area=length*width;
return(area);
}
}
Here the getData method is declared to provide values to the instance variables.

Prepared by: M.VENKAT (MCA, M-Tech) Lecturer in Computer Science


Page no- 15

(Note: In class we will have many numbers of variables and methods. Instance variables and methods in classes are accessible
by all the methods in the class but a method cannot access the variables declared in other methods.

Example:

class Check
{
int x;
void method1()
{
int y;
x=10; //legal
y=x; //legal
}
void method2()
{
int z;
x=20; //legal
z=10; //legal
y=5; //illegal
method1(); //legal
}
} )

OBJECT
1. Creating of an Object:
Object is a real word entity. “An instance of a class is called as an Object”. An object in java
is a block of memory that contains space to store all the member variables. Crating an
object is also referred to as Instantiating an object.

Objects in java are created using the new operator. The new operator creates an object for
the specified class and returns a reference to that object.
Here is an example of creating an object of type Rectangle.

Rectangle R1; //Declaring the object


R1 = new Rectangle(); // Instantiating the object

 The first statement declares a variable to hold the object reference(R1) and the second
one actually creates an object and assigns the object reference to the variable R1. The
variable R1 is now an object of the Rectangle class. Both statements can be combined
into one as shown below.
Rectangle R1 = new Rectangle();

 The method Rectangle( ) is the Default Constructor of the class. We can create any
number of objects of Rectangle.
Example:

Prepared by: M.VENKAT (MCA, M-Tech) Lecturer in Computer Science


Page no- 16

 Each object has its own copy of the instance variable of its class. This means if any changes in
variables of one object that cannot effect on the other variables.

 It is also possible to create two or more references to the same object as shown in below.

Rectangle R1 = new Rectangle ();


Rectangle R2 = R1;

Accessing Class Members


To access the instance variables and the methods from the outside of that class, we must use
the concerned object and the dot ( . ) operator as shown in below.

<object_name> . <variable_name> = value;


<object_name> . <method_name>(parameter_list);

1. Here, object_name is the name of the object and variable_name is the name of the
instance variable inside the object.

2. Method_name is the method that we wish to call.

3. parameter-list is separated by comma, and that must match in type and number with
the parameter list of the method name declared in the class.

1. First approach for accessing instance variables:

The instance variables of the Rectangle class may be accessed and assigned values as
follows:
R1.length = 10;
R1.width = 20;
R2.length = 30;
R2.width = 40;
Note that the two objects R1 and R2 store different values as shown below:

This is one way to assigning values to the variables in the objects.

2. Second approach for accessing Instance variables:

Prepared by: M.VENKAT (MCA, M-Tech) Lecturer in Computer Science


Page no- 17

In our case getData() method can be used to do this. We can call this getData() method by
using objects R1/R2 as follows:
R1.getData(1,2); // calls getData method and pass values 1, 2 to parameters x, y of the method getData
R2.getData(10,20);//calls getData method and pass values 10, 20 to parameters x, y of the method getData

The following is the program that illustrates the concepts discussed so far.
import java.lang.*;
class Rectangle // Declaration of class
{
int len, wid; // Declaration of instance variables

void getData(int x, int y) //Declaration of method


{
Ien=x;
wid=y;
}

void rectArea() //Declaration of another method


{
int area;
area=len*wid;
System.out.println("Area from Method =" + area);
}
}

class RectArea // class with main method


{
public static void main(String args[])
{
int area1;
Rectangle r1=new Rectangle(); // Creating objects1
Rectangle r2=new Rectangle(); // Creating objects2
r1.len=15; //Accessing Variables
r1.wid=10;
area1=r1.len * r1.wid;
r2.getData(20,12); //Accessing methods
r2.rectArea();
System.out.println(area1);
}
}
Output:

Constructors in Java

Prepared by: M.VENKAT (MCA, M-Tech) Lecturer in Computer Science


Page no- 18

A constructor in Java is similar to a method, which is invoked when an object of the class is
created. Unlike Java methods, a constructor has the same name as that of the class and does not
have any return type.
For example,

class Test //Class created


{
Test() //Constructor creating
{
// constructor body
}
}

Here, Test() is a constructor. It has the same name as that of the class and doesn't have a return
type.

 It is a special type of method which is used to initialize the object. Every time an object is
created using the new() keyword, at least one constructor is called.

 It calls a default constructor if there is no constructor available in the class. In such case, Java
compiler provides a default constructor by default.

The following program illustrates the concept of constructors in java.

Program To find the area of a rectangle.

class Main
{
private String name;

Main() // constructor
{
System.out.println("Constructor Called:");
name = "Programiz";
}

public static void main(String[] args)


{
Main obj = new Main(); // constructor is invoked, while creating an object of the Main class
System.out.println("The name is " + obj.name);
}
}

Output:
Constructor Called:
The name is Programiz

Types of Java constructors

There are two types of constructors in Java:

Prepared by: M.VENKAT (MCA, M-Tech) Lecturer in Computer Science


Page no- 19

1. Default constructor (no-arg constructor)


2. Parameterized constructor
1. Java Default Constructor

A constructor is called "Default Constructor" when it doesn't have any parameter.

Syntax of default constructor:

<class_name>
()
{

}  

Example of default constructor

In this example, we are creating the no-arg constructor in the Bike class. It will be invoked at the
time of object creation.

//Java Program to create and call a default constructor  
class Bike
{  
Bike() //creating a default constructor  
{
System.out.println("Bike is created");
}  

public static void main(String args[]) //main method  
{  
Bike1 b=new Bike1();   //calling a default constructor  
}  
}  

2. Java Parameterized Constructor

A constructor which has a specific number of parameters is called a parameterized constructor.


Why use the parameterized constructor?

The parameterized constructor is used to provide different values to distinct objects. However,
you can provide the same values also.

Example of 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.

Prepared by: M.VENKAT (MCA, M-Tech) Lecturer in Computer Science


Page no- 20

//Java Program to demonstrate the use of the parameterized constructor.  
class Main
{
String lang;

Main(String language) // constructor accepting single value


{
lang =language
System.out.println(lang);
}

public static void main(String[] args)


{
Main obj1 = new Main("Java"); // call constructor by passing a single value
Main obj2 = new Main("Python");
Main obj3 = new Main("C");
}
}

Q). Constructor Overloading in Java

In Java, a constructor is just like a method but without return type. It can also be overloaded like
Java methods.

1) Constructor overloading in Java is a technique.


2) It’s having more than one constructor with different parameter lists.

3) They are arranged in a way that each constructor performs a different task.

4) They are differentiated by the compiler by the number of parameters in the list and
their types.

Example of Constructor Overloading


//Java program to overload constructors  
class Student
{  
    int id;  
    String name;  
    int age;  

    Student(int i, String s)      //creating two arg constructor  


{  
   id = i;  
     name = s;  
     }  
    Student(int i, String s, int a) //creating three arg constructor  
{  
     id = i;  
     name = s;  
     age=a;  
     }  
    void display()
{
System.out.println(id+" "+name+" "+age);
}  
   

Prepared by: M.VENKAT (MCA, M-Tech) Lecturer in Computer Science


Page no- 21

    public static void main(String args[])
{  
     Student s1 = new Student(111,"Karan");  
     Student s2 = new Student5(222,"Aryan",25);  
     s1.display();  
     s2.display();  
    }  

Q).How to initializing the instance variables?


It is the duty of the programmer to initialize the instance variables, depending on his
requirements.

Examplel: A program to initialize the Person class instance variables in Demo class.
//Initializing the instance variables
class Person
{
public String name; //public Instance variable

int age ; //Default instance variable

void disp()
{
System.out.println("Hello lam " + name);
System.out.println("My age is " + age);
}

public static void main(String args[])


{
Person P = new Person();
P.name="Raju";
P.age=5;
P.disp();
}
}

Output:
Hello lam Raju
My age is 5

Q). Access Specifier (or)Modifiers in Java

Prepared by: M.VENKAT (MCA, M-Tech) Lecturer in Computer Science


Page no- 22

There are two types of modifiers in Java: access modifiers and non-access modifiers.

The access modifiers in Java specify 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.

There are four types of Java access 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.

Q). Difference between constructor and method in Java:

There are many differences between constructors and methods. They are given below.

Java Constructor Java Method


1.A constructor is used to initialize the 1. A method is used to expose the behavior of an
state of an object. object.
2.A constructor must not have a return 2. A method must have a return type.
type.
3.The constructor is invoked implicitly. 3. The method is invoked explicitly.
4.The Java compiler provides a default 4. The method is not provided by the compiler in
constructor if you don't have any any case.
constructor in a class.
5.The constructor name must be same as 5. The method name may or may not be same as
the class name. the class name.

Methods in JAVA

Prepared by: M.VENKAT (MCA, M-Tech) Lecturer in Computer Science


Page no- 23

Explain about methods in Java?


A method is a block of code (or) collection of statements (or) a set of code grouped together to
perform a certain task (or) operation. It is used to achieve the reusability of code. “We write a
method once and use it many times”. We do not require to write code again and again.

Methods must be declared inside the body of the class but immediately after the declaration of
instance variables.

Declaration:

type method_name (parameter_list)


{
method body
}

A method has two parts


1. Method header (or) method prototype
2. Method body

1. Method header (or) method prototype:


It contains method name, method parameters and method return data type. Method prototype
is written in the form:

return_datatype method_name(parameter 1, parameter 2,...)

Here, method name represents the name given to the method. After the method name, we
write some variables in the simple braces. These variables are called parameters. Method
parameters are useful to receive data from outside into the method.

Example
int sqrt (int num)

Here, sqrt is the method name, num is method parameter that represents that this method
accepts a int type value.

2. Method Body:

Below the method header, we should write the method body Method body consists of a group
of statements which contains logic to perform the task. Method body can be written in the
following format:

int method_name(parameter_list)
{
//statements;
}
For example, we want to write a method that calculates sum of two numbers. It may contain
the body, as shown here:

int sum(int a, int b)


{

Prepared by: M.VENKAT (MCA, M-Tech) Lecturer in Computer Science


Page no- 24

int c = a + b;
System.out.println("Sum of two = "+c);
}
If a method returns some value, then a return statement should be written within the body of
the method, as :
return x; // return x value

A method can never return more than one value.

Program: Write a program for a method with two parameters and return type.
class Sample
{
int sum(int num1, int num2)
{
int res=num1 + num2;
return res; //return result

}
}

class Methods
{
public static void main(String args[])
{
Sample s = new Sample();
int x=s.sum (10, 22);
System.out.println("Sum="+x);
}
}

Output:
C:\>javac Methods.java
C:\> java Methods

Static Members
The variables and methods in the class are called as instance variables and instance methods.
This is because every time the class is instantiated, a new copy of each of them is created.
They are accessed using the objects (with dot operator).

Let us assume that we want to define a member that is common to all the objects and
accessed without using particular object.

i.e. the member belongs to the class as a whole rather than the objects created from the class.
Such members can be defined as follows:

static int cout;


static void get(float x, int a);

The members that are declared with the keyword static are called as static members. Since

Prepared by: M.VENKAT (MCA, M-Tech) Lecturer in Computer Science


Page no- 25

these members are associated with the class itself rather than individual objects, the static
variables and static methods are often referred to a class variables and class methods.
Static variable:

1. It is a variable which belongs to the class and not to object(instance)


2. Static variables are initialized only once, at the start of the execution. These variables
will be initialized first, before the initialization of any instance variables.
3. A single copy to be shared by all instances of the class.
4. A static variable can be accessed directly by the class name and doesn’t need any
object
The following is the syntax for accessing a static variable.
Syntax:
<class-name>.<variable-name>;

static method:

1. It is a method which belongs to the class and not to the object(instance)


2. A static method can access only static data. It cannot access non-static data (instance
variables)
3. A static method can call only other static methods and cannot call a non-static method
from it.
4. A static method can be accessed directly by the class name and doesn’t need any object

The following is the syntax for accessing a static variable

Syntax :

<class-name>.<variable-name>;
<class-name>.<method-name>;.

The following program illustrates the concept of static members in java.


class Result
{
static int a,b; // declaration of static variables
static void getc(int x,int c) // declaration of static method
{
a=x;
b=c;
}E 182
}
class Stat
{
public static void main(String ar[]) // calling static method with class name
{
Result.getc(10,20); // calling static variables with class name

Prepared by: M.VENKAT (MCA, M-Tech) Lecturer in Computer Science


Page no- 26

System.out.println(Result.a + " " + Result.b);


}
}
Output:

Note: main () method is static, since it must be accessible for an application to run, before any
instantiation takes place.

Q). Write about the keyword this?

The keyword 'this': 'this' is a keyword that refers to the object of the class where it is used. In
other words, 'this' refers to the object of the present class. Generally, we write instance
variables, constructors and methods in a class.

All these members are referenced by 'this'. When an object is created to a class, a default
reference is also created internally to the object, as shown in the Figure. This default reference
is nothing but 'this'. So 'this' can refer to all the things of the present object.

The keyword 'this' is a reference to class object

Let's understand the problem if we don't use this keyword


by the example given below:

Solution of the above problem by this keyword


class Student{  
int rollno;  
String name;  
class Student{  
float fee;  
int rollno;  
Student(int rollno,String name,float fee){  
String name;  
rollno=rollno;  
float fee;  
name=name;  
Student(int rollno,String name,float fee){  
fee=fee;  
this.rollno=rollno;  
}  
this.name=name;  
void display(){System.out.println(rollno+" "+name+" 
this.fee=fee;  
"+fee);}  
}  
}  
void display()
class TestThis1{  
{
public static void main(String args[]){  
System.out.println(rollno+" "+name+" "+fee);}  
Student s1=new Student(111,"ankit",5000f);  
}  
Student s2=new Student(112,"sumit",6000f);  
  
s1.display();  
class TestThis2{  
s2.display();  
public static void main(String args[]){  
}}  
Student s1=new Student(111,"ankit",5000f);  
In the above example, parameters (formal
Student s2=new Student(112,"sumit",6000f);  
arguments) and instance variables are same. So, we
s1.display();  
are using this keyword to distinguish local variable
and instance variable. s2.display();  
}}  
Output:

Prepared by: M.VENKAT (MCA, M-Tech) Lecturer in Computer Science


Page no- 27

Explain instance methods with example?

Instance methods: Instance methods are the methods which act upon the instance
variables. To call the instance methods, object is needed, since the instance variables are
contained in the object. We call the instance methods by using objectname.methodname().
The specialty of instance methods is that they can access not only instance variables but
also static variables directly.

There are two types of instance methods:


1. Accessor methods.
2. Mutator methods.

Accessor methods are the methods that simply access or read the instance variabiles. They
do not modify the instance variables.
Mutator methods not only access the instance variables but also modify them.

Example program of Accessor and mutator methods

class Person
{
private String name;
private int age;
public void setName(String name) //mutator methods to store data
{
this.name =name;
}
public void setAge(int age)
{
this.age= age;
}
public void setAge(int age)
{
this.age=age;
}
public String getName() // Accessor metods to read data
{
return name;
}
public int getAge()
{
return age();
}
}
class Methhods
{
public static void main(String args[])
{
Person p1=new Person();
p1.setName(“Raju”);
p1.setAge(20);
System.out.prinntln(“Name=”+p1.getName());
System.out.prinntln(“Age=”+p1.getAge());
}
}

Output:

Prepared by: M.VENKAT (MCA, M-Tech) Lecturer in Computer Science


Page no- 28

Explain about passing primitive data types to methods?

Primitive data types (or) fundamental data types represent single entities (or) single values.
For example, char, byte, short, int, long, float, double and boolean are called primitive data
types, because they store single values. They are passed to methods by value.

This means when we pass primitive data types to methods, a copy of those will be passed
to methods. Therefore, any changes made to them inside the method will not affect them
outside the method. In the following program, we pass two integer numbers 10 and 20 to
the swap method. Let us display the output to know whether they are interchanged or not.

Program:

//Primitive data types are passed to methods by value

class check
{
vold swap (int n1, int n2)
{
int temp;
temp=n1;
n1=n2;
n2=temp;
}
}

class PassPrimitive
{
public static void main(String args[])
{
int n1= 10, n2=20;
check ck= new check ();
System.out.println(n1+ " " +n2);
ck.swap(n1, n2);
System.out.println(n1+" " +n2);
}
}

Output:
C> javac PassPrimitive.java
C:>java PassPrimitive
10 20
10 20

Passing objects to Methods:


We can also pass class objects to methods, and return objects from the methods. For
example,
Employee myMethod(Employee obj)
{
Statements;
return obj;
}

Prepared by: M.VENKAT (MCA, M-Tech) Lecturer in Computer Science


Page no- 29

Here, myMethod() is a method that accepts Employee class object. So reference of


Employee class is declared as parameter in myMethod()). After doing some processing
on the object, if it returns the same object, we can write a statement like:
return obj;
Program : Write a program to interchange the values inside an object, since the same
object data is modified, we can see the data has been interchanged. Interchanging the
values should be done in a single object
class Employee
{
int id1, id2;
Employee (int id1, int id2)
{
this.id1 = id1;
this.id2=id2;
}
}

class Check
{
value swap(Employee obj)
{
int temp;
temp=obj.id1;
obj.id1 = obj.id2;
obj.id2=temp;
}
}
class PassObjects
{
public static void main(String args[])
{
Employee obj1 = new Employee(10, 20);
Check obj = new check();
System.out.println(obj1.id1+""+obj1.id2);
obj.swap(obj1);
System.out.println(obj1.id 1+"\t"+obj1.id2);
}
}
Output:
C: javac Pass Objects.java
Objects Pass Objects

10 20
2019

How passing arrays to methods? Explain.

Just like the objects are passed to methods, it is also Possible to pass arrays to methods and
return arrays from methods. In this case, an array name should be understood as an object
reference. For example,
int [] myMethod(int arr[])

Prepared by: M.VENKAT (MCA, M-Tech) Lecturer in Computer Science


Page no- 30

This is the way, we can pass a one dimensional array 'arr' to 'myMethod()'. We can also
return a one dimensional array of int type as shown in the preceeding statement.
int[] [] myMethod(int arr[][])
Here, we are passing and returning a two dimensional array of int type.
Example:
class Array
{
public int[] sortArr (int a [], int len)
{
for(i=0; i<len; i++)
for (j=i+1; j<len;j++)
{
if (a[i]>a[j])
{
temp = a[i];
a[i]=a[j];
a[j]=temp;
}
}
return a;
}
public static void main(String args[])
{
int a[]={10, 40, 30, 20, 50);
int b[]=obj.sortln(a,a.lengt);
System.out.println("sorted array elements are");
for(int i=0;i<b.length;i++)
System.out.println(b[i] +’’);
}
}

Output:
sorted array elements are
10 20 30 40 50

Java static block

A static block is a block of statement declared as “static”, some thing like tis:
static
{
Statement;
}

JVM execute a static block on a highest priority basis. This means JVM first goes to static
block even before it looks for the main() method in the program.
Example:
Class Test
{
Static
{
System.out.println(“Static block”);
}
public static void main(String args[])
{
System.out.println(“Static method”);
}

Prepared by: M.VENKAT (MCA, M-Tech) Lecturer in Computer Science


Page no- 31

}
Output:

What is Recursion? Explain with example?


Recursion: A method calling itself is known as 'recursive method' and that phenomenon is
called 'recursion'. It is possible to write recursive methods in Java.

Program: Write a program to find factorial value with using recursion.

//Factorial with Recursion

class Recursion
{
static long factorial(int num)
{
long result;
if (num==1)
return 1;
result =factorial (num-1)*num;
return result;
}
public static void main(String args[])
{
System.out.println("Factorial of 5:");
System.out.println(Recursion.factorial(5));
}
}
Output:
C:\>javac Recursion.java
C:\>java Recursion
Factorial of 5;
120

What are factory methods?

A factory method is a method that creates and returns an object to the class to which
it belongs. A single factory method replaces several constructors in the class by
accepting different options from the user, while creating the object.

To understand how to use a factory method, let us take an example program to


calculate the area of a circle.

Example a program for calculating and displaying area of a circle.

class Circle
{
public static void main(String arg[])
{
final double PI = (double)22/7;
double r= 15.5; //radius
double area = Pl*r*r;
System.out.println("Area = " + area);
}
}
Output:
C:>javac Circle.java
C:\> java Circle

Prepared by: M.VENKAT (MCA, M-Tech) Lecturer in Computer Science


Page no- 32

Area-755.0714285714286

Inheritance in Java
Inheritance in Java 

It 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

Parent (Properties)

Parent Properties Inherited to Child

Child (Parent Properties


+
(Child Properties) Now Child have
Parent
properties
+ His / her
own
properties.

Fig: Inheritance
 The class which is giving members (variables and methods) to some other class is
known as base class / super class / parent class.

 The class which is retrieving or obtaining members (variables and methods) is known
as derived class / sub class / child class.

 The inheritance allows subclasses to inherit all the variables and methods of their
parent classes. A Derived class contains its own properties (members) plus base
class properties (members).

Advantages of Inheritance

 Application development time is reduced.


 Application memory space is reduced.
 Redundancy (Repetition) of the code is reduced.
 Reusability.

Prepared by: M.VENKAT (MCA, M-Tech) Lecturer in Computer Science


Page no- 33

Syntax for INHERITING the features from base class to derived class:

class <sub_classname> extends <super_classname>


{
Variable declaration; Method declaration;
}

 The keyword extends signifies that the properties of the super_classname are
extended to the sub_classname.
 The subclass will now contain its own variables and methods as well those of
the super class.
 This kind of situation occurs when we want to add some more properties to an
existing class without actually modifying it and also improves functionality of
derived class.

Types of Inheritances (Reusable Techniques)


Based on getting the features from one class to some other class, java have the
following types of reusable techniques.
1. Single Inheritance (only one super class, one sub class)
2. Multilevel Inheritance ( Derived from derived class)
3. Hierarchical Inheritance (one super class, many sub classes)
4. Multiple Inheritance (several super classes)

1. Single Inheritance

In Single Inheritance single base class is derived to a single derived class. If one child
class is inheriting the properties of the parent class without any intermediate class,
then it is called as “Single Inheritance”.

A subclass acquires the properties from the super class is also called as “Single
inheritance”. For example C2 class is derived from C1 class; Now C2 access all the
properties of C1 and itself. It is shown in below.

Prepared by: M.VENKAT (MCA, M-Tech) Lecturer in Computer Science


Page no- 34

Fig: Single Inheritance


Example:

class c1
{
---------
}
class c2 extends c1
{
---------
}

The following program illustrates the concept of Single Inheritance.


Aim: Program to find the area of the room and the volume of a bed room.
Program
class Animal
{  
void eat()
{
System.out.println("eating...");
}  
}  

class Dog extends Animal
{  
void bark()
{
System.out.println("barking...");
}  
}  

class TestInheritance
{  
public static void main(String args[])
{  
Dog d=new Dog();  
d.bark();  
d.eat();  
}}
Output:

2. Multilevel Inheritance
Multilevel Inheritance contains one base class and one derived class, and multiple
intermediate base classes.

A Child class(Derived class) acquire the properties of Parent class(intermediate


class), and Parent class(intermediate class) acquire the properties of grandparent
class(Base class). It is also called multilevel inheritance.

Prepared by: M.VENKAT (MCA, M-Tech) Lecturer in Computer Science


Page no- 35

For example C2 class is derived from C1, C3 class is derived C2, and C4 class is
derived C3; Now C2 access C1 class members and itself only, C3 access C2 and C1
class members and itself only, and C4 can access C3,C2,C1class members and itself
only. It is shown in below.

Fig:- Multilevel inheritance:

Example:

class c1
class Animal {
---------
{  
---------
void eat() }
{ class c2 extends c1
System.out.println("eating..."); {
}   ---------
---------
}   }
class c3 extends c2
class Dog extends Animal{   {
void bark() ---------
{ ---------
}
System.out.println("barking..."); class c4 extends c3
}   {
}   ---------
---------
class BabyDog extends Dog }
{  
void weep()
{
System.out.println("weeping...");
}  
}  

class TestInheritance2
{  
public static void main(String args[])
{  
BabyDog d=new BabyDog();  
d.weep();  
d.bark();  
d.eat();  
}

Prepared by: M.VENKAT (MCA, M-Tech) Lecturer in Computer Science


Page no- 36

}  

Output:

3. Hierarchical Inheritance

Hierarchical Inheritance contains a single base class and multiple derived classes. In
hierarchical inheritance multiple subclasses acquire the properties of only single
super class, it is also called as hierarchical inheritance.

Fig: Hierarchical Inheritance

For example C2, C3, C4, classes are derived from C1 class; Now C2, C3, C4 classes can
access C1 class members and itself only. It is shown in below.

Syntax:
class c1
{
---------
---------
}
class c2 extends c1
{
---------
---------
}
class c3 extends c1
{
---------
---------
}
class c4 extends c1
{
---------
---------
}

Example:
class Animal
{  
void eat()
{System.out.println("eating...");}  
}  

class Dog extends Animal
{  
void bark()

Prepared by: M.VENKAT (MCA, M-Tech) Lecturer in Computer Science


Page no- 37

{
System.out.println("barking...");
}  
}  

class Cat extends Animal
{  
void meow()
{System.out.println("meowing...");}  
}  

class TestInheritance3
{  
public static void main(String args[])
{  
Cat c=new Cat();  
c.meow();  
c.eat();  
//c.bark();//C.T.Error  
}}
Output:

4. Multiple Inheritance

Multiple Inheritance contains multiple base classes and a single derived class. For
example C4 class is derived from C1, C2, and C3 Base classes; Now C4 can access C1,
C2, C3 members and itself. It is shown in below.

Fig: Multiple Inheritance


The concept of multiple inheritances is not supported in java directly but it can be
supported through the concept of interfaces. Because if class C1 and C2 contains
some variable, Now from which class the same variable is Inherited to C4 class. It
leads to confusion.

Super keyword
Subclass Constructor (‘super’ keyword)

Prepared by: M.VENKAT (MCA, M-Tech) Lecturer in Computer Science


Page no- 38

A Subclass constructor is used to construct the instance variables of both the subclass
and the super class. The subclass constructor uses the keyword super to invoke the
constructor method of the super class. The super keyword is used subject to the
following conditions.

 super may only be used within a subclass constructor method.


 The call to super class constructor must appear as the first statement within
the subclass constructor.
 The parameters in the super call must match the order and type of the
instance variables declared in the super class.

Write about the protected specifier?

The Protected Specifier: The private members of the super class are not available to sub
classes directly. But sometimes, there may be a need to access the data of super class in the
sub class.

For this purpose, protected specifier is used. Protected is commonly used in super class to
make the members of the super class available directly in its sub classes.

Example: Program to understand private members are not accessible in subclass, but
protected members are available in sub class.

//private and protected

class Access
{
private int a;
protected int b;
}

class Sub extends Access


{
public void get()
{
System.out.println(a); //error-a is private
System.out.println(b);
}
}

class Test
{
public static void main(String args[])
{
Subs= new Sub ();
s.get();
}
}

Output:

Prepared by: M.VENKAT (MCA, M-Tech) Lecturer in Computer Science


Page no- 39

javac Test java


Test.java:11: a has private access in Access
System.out.println(a);
1 error

Prepared by: M.VENKAT (MCA, M-Tech) Lecturer in Computer Science

You might also like