0% found this document useful (0 votes)
1 views18 pages

Unit2 Java

The document provides an overview of classes, objects, and methods in Java, emphasizing the object-oriented nature of the language. It explains how to define classes, create objects, declare methods, and utilize access modifiers for visibility control. Additionally, it covers concepts such as method overloading, constructors, static members, and arrays, including one-dimensional and two-dimensional arrays.

Uploaded by

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

Unit2 Java

The document provides an overview of classes, objects, and methods in Java, emphasizing the object-oriented nature of the language. It explains how to define classes, create objects, declare methods, and utilize access modifiers for visibility control. Additionally, it covers concepts such as method overloading, constructors, static members, and arrays, including one-dimensional and two-dimensional arrays.

Uploaded by

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

UNIT – 2

Classes, Objects and Methods used in Java


 Java is a true Object Oriented language and therefore the underlying structure of all Java programs
is Classes.
 Classes create objects and objects use methods to communicate between them.
 In Java, the data items are called Fields and the functions are called Methods.

Defining a Class:
A Class is a user defined data type with a template that serves to define its properties. Once the class type
has been defined, we can create “variables” of that type using declarations that are similar to the basic
type declarations. In Java these variables are termed as instances of classes, which are the actual objects.
Basic form of class definition is,
class classname
{
variable declaration;
method declaration;
}
classname is a valid Java identifier.

Example:
class Car
{
String brand;
int year;
}
Note: Instance variables are also known as Member Variables or Fields.

Methods Declaration:
A class with only data fields has no life. The objects created by such a class cannot respond to any
messages. We must therefore add methods that are necessary for manipulating the data contained in the
class. 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
type methodname(parameter-list)
{
method-body;
}
Method declarations have four basic parts:
 The name of the method (methodname).
 The type of the value the method returns (type).
 The list of parameters (parameter list).
 The body of the method.

PARNASHREE S, SKPFGC Page 1


 The type specifies the type of value the method would return.
 The method name is a valid identifier.
 The parameter list is always enclosed in parenthesis, separated by commas.
 The body describes the operations to be performed on the data.

Example:
class Car
{
String brand;
int year;

void displayDetails()
{
System.out.println("Brand: " + brand);
System.out.println("Year: " + year);
}
}

Creating Objects:
An object or instance in java is essentially a block of memory that contains space to store all the instance
variables. Creating 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 of the specified
class and returns a reference to that object.

Example: Car myCar = new Car();

The variable myCar is now an object of the Rectangle class.


The method Car( ) is the default constructor of the class. We can create any number of objects of
Rectangle.

Accessing Class Members:


To access class members when we are outside the class, we must use the concerned object and the dot
operator as shown
Objectname.variablename;
Objectname.methodname(parameter-list);

Example:
myCar.brand = "Toyota";
myCar.year = 2020;

PARNASHREE S, SKPFGC Page 2


Example: Program to illustrate the Application of Classes and Objects.
class Car
{
String brand;
int year;

void displayDetails()
{
System.out.println("Brand: " + brand);
System.out.println("Year: " + year);
}
}

public class design


{
public static void main(String[] args)
{
Car myCar = new Car();
myCar.brand = "Toyota";
myCar.year = 2020;
myCar.displayDetails();
}
}

Output:
Brand: Toyota
Year: 2020

Constructors
All objects that are created must be given initial values. It would be simpler and more concise to initialize
an object when it is created. Java supports a special type of method called a Constructor that enables
an object to initialize itself when it is created.
 Constructors have the same name as the class itself.
 Constructors do not specify a return type, not even void. This is because they return the instance of
the class itself.

Consider a Rectangle class:


class Rectangle
{
int length,width;

PARNASHREE S, SKPFGC Page 3


Rectangle(int x, int y) // Defining constructor
{
length=x;
width=y;
}

int rectArea( )
{
return(length*width);
}
}

class RectangleArea
{
public static void main(String args[ ])
{
Rectangle Rect1=new Rectangle(15,10); // calling constructor
int area1=Rect1.rectArea( );
System.out.println(“Area1=” + area1);
}
}

Output:
Area1 = 150

Access modifiers (Visibility Control)


In Java, Access modifiers help to restrict the scope of a class, constructor, variable, method, or data
member. It provides security, accessibility, etc. to the user depending upon the access modifier used with
the element.
It is possible to inherit all the members of a class by a subclass using the keyword extends. The variables
and methods of a class are visible everywhere in the program. However, it may be necessary in some
situations to restrict the access to certain variables and methods from outside the class.
For example, we may not like the objects of a class directly alter the value of a variable or access a
method. We can achieve this in Java by applying visibility modifiers to the instance variables and
methods. The visibility modifiers are also known as Access modifiers.
Java provides three types of visibility modifiers: public, private and protected. They provide different
levels of protection as described below.

Public Access: Any variable or method is visible to the entire class in which it is defined.
Example: public int number;
public void sum( ){………….….}
A variable or method declared as public has the widest possible visibility and accessible everywhere.

PARNASHREE S, SKPFGC Page 4


Friendly Access: When no access modifier is specified, the member defaults to a limited version of public
accessibility known as “friendly” access.
The difference between public access and friendly access is that the public modifier makes fields visible
in all classes, regardless of their packages while the friendly access makes fields visible only in the same
package, but not in other packages. A package is a group of related classes stored separately. A package in
Java similar to a source files in C.

Protected Access: The visibility level of a “protected” field lies in between the public access and friendly
access. That is, the protected modifier makes the fields visible not only to all classes and subclasses in
same package, but also to subclasses in other package.

Private Access: Private Fields enjoys the highest degree of protection. They are accessible only within
their own class. They cannot be inherited by subclasses and therefore not accessible in subclasses. A
method declared as private behaves like a method declared as final. It prevents the method from being
subclassed.

Private Protected Access: A field can be declared with two keywords private and protected together
like: private protected int codenumber;
This gives a visibility level in between the “protected” access and “private” access. This modifier makes
the fields visible in all subclasses regardless of what package they are in. These fields are not accessible
by other classes in the same package.

Visibility of fields in a class:

access modifier Public protected Friendly private private


(default) protected
access
location

Same class Yes yes Yes yes yes

Subclass in same package Yes yes Yes yes No

Other classes in same Yes yes Yes no no


package
Subclass in other packages Yes yes No yes no
Non-subclasses in other Yes No No no no
packages

PARNASHREE S, SKPFGC Page 5


1. Use public, if the field is to be visible everywhere.
2. Use protected, if the field is to be visible everywhere in the current package and also subclasses in
other packages.
3. Use default, if the field is to be visible everywhere in the current package only.
4. Use private protected, if the field is to be visible only in subclasses, regardless of packages.
5. Use private, if the field is not to be visible anywhere except in its own class.

Method Overloading
It is possible to create methods that have the same name, but different parameter lists and different
definitions. This is called Method Overloading. Method Overloading is used when objects are required
to perform similar tasks but using different input parameters.
When we call a method in an object, Java matches up the method name first and then the number and
type of parameters to decide which one of the definitions to execute. This process is known as
Polymorphism.

Example: Write a java program to demonstrate method overloading.

class Calculator
{
int add(int a, int b)
{
return a + b;
}

int add(int a, int b, int c)


{
return a + b + c;
}
}

public class overloading


{
public static void main(String[] args)
{
Calculator calc = new Calculator();
System.out.println("Sum of 10 and 20: " + calc.add(10, 20));
System.out.println("Sum of 10, 20, and 30: " + calc.add(10, 20, 30));
}
}
Output:
Sum of 10 and 20: 30
Sum of 10, 20, and 30: 60

PARNASHREE S, SKPFGC Page 6


Overloading Constructor
We can define multiple constructors within a class and each of them can have different types of
parameters. With the help of constructor overloading, objects of the class can be created with different
kinds of information, we want to add to it.
Need of Constructor Overloading:

This can be useful in many ways such as,


 It provides flexibility in object creation.
 It enables you to initialize objects in different ways depending on the information available or
needed at the time of creation.
 It also helps in making the code simpler.

Example:

public class Employee


{
String name;
int id;

// Default constructor
public Employee()
{
name = "Unknown";
id = 0;
}

// Parameterized constructor
public Employee(String empName, int empId)
{
name = empName;
id = empId;
}

public void display()


{
System.out.println("Name: " + name + ", ID: " + id);
}

public static void main(String[] args)


{
Employee emp1 = new Employee(); // Default constructor
Employee emp2 = new Employee("John", 101); // Parameterized constructor
emp1.display();
emp2.display();
}
}
PARNASHREE S, SKPFGC Page 7
Output:
Name: Unknown, ID: 0
Name: John, ID: 101

Static Members
A class basically contains two sections. One declares variables and the other declares 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 a particular object. That is, 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 count;


static int max(int x, int y);

The members that are declared static as shown above are called static members. The static
variables and static methods are often referred to as class variables and class methods in order to
sdistinguish them from their counterparts, instance variables and instance methods.

Example: Defining and using static members


class Mathoperation
{
static float mul(float x, float y)
{
return x*y;
}
static float divide(float x, float y)
{
return x/y;
}
}
class MathApplication
{
public static void main(String args[ ])
{
float a=Mathoperation.mul(4.0F,5.0F);
float b=Mathoperation.divide(a,2.0F);
System.out.println("b=" + b);
}
}
Output: b = 10.0

PARNASHREE S, SKPFGC Page 8


this keyword
The this keyword refers to the current object in a method or constructor. The most common use of
the this keyword is to eliminate the confusion between class attributes and parameters with the same
name (because a class attribute is shadowed by a method or constructor parameter). If you omit the
keyword in the example below, the output would be "0" instead of "5".

this can also be used to:

 Invoke current class constructor


 Invoke current class method
 Return the current class object
 Pass an argument in the method call
 Pass an argument in the constructor call

Example:
public class Main
{
int x;

// Constructor with a parameter


public Main(int x)
{
this.x = x;
}

// Call the constructor


public static void main(String[] args)
{
Main myObj = new Main(5);
System.out.println("Value of x = " + myObj.x);
}
}

Arrays
An array is a group of contiguous or related data items share a common name. A particular value is
indicated by writing a number called index number or subscript in brackets after the array name.
For example: Salary[10]; represents the salary of the 10th employee.
While the complete set of values is referred to as an array, the individual values are called elements.
Arrays can be of any variable type.

One-Dimensional Arrays:
A list of items can be given one variable name using only one subscript and such a variable is called a
single-subscripted variable as a one-dimensional array.
PARNASHREE S, SKPFGC Page 9
Creating an Array:
Creation of an array involves three steps:
 Declare the array.
 Creating memory locations.
 Putting values into the memory locations.

Declaration of Arrays:
Arrays in Java may be declared in two forms:
Form1:

type arrayname[ ];
Form2:
type[ ] arrayname;

Examples: int number[ ];


float average[ ];
int[ ] counter;
float[ ] marks;
Remember, we do not enter the size of the arrays in the declaration.

Creation of Arrays:
After declaring an array, we need to create it in the memory. Java allows us to create arrays using new
operator only, as shown below:
arrayname = new type[size];

Examples:
number = new int[5];
average = new float[10];
These lines create necessary memory locations for the arrays number and average and designate them as
int and float respectively. Now, the variable number refers to an array of 5 integers and average refers to
an array of 10 floating point values.

It is possible to combine the two steps-declaration and creation-into one as shown below:
int number[ ]=new int[5];

Initialization of Arrays:
The final step is to put values into the array created. This process is known as initialization. This is done
using the array subscripts as shown below:
arrayname[subscript]=value;
Example:
number[0]=35;
number[1]=40;

PARNASHREE S, SKPFGC Page 10


We can also initialize arrays automatically in the same way as the ordinary variables when they are
declared below as shown below:
type arrayname[ ]={list of values};

Example: int number[ ] ={35,40,20,57,19};

Array Length: In Java, all arrays store the allocated size in a variable named length. We can access the
length of the array ‘a’ using a.length.

Example: int asize = a.length;


This information will be useful in the manipulation of arrays when their sizes are not known.

Example: Program to find maximum and minimum element in one dimensional array of numbers.
public class MinMaxArray
{
public static void main(String[] args)
{
int[] numbers = {10, 20, 4, 45, 99, 2, 67};
int max = numbers[0];
int min = numbers[0];

for (int i = 1; i < numbers.length; i++)


{
if (numbers[i] > max)
{
max = numbers[i];
}
if (numbers[i] < min)
{
min = numbers[i];
}
}

System.out.println("Maximum Element: " + max);


System.out.println("Minimum Element: " + min);
}
}

Output:
Maximum Element: 99
Minimum Element: 2

PARNASHREE S, SKPFGC Page 11


Two-Dimensional Arrays:
Two-Dimensional Arrays are stored in memory as shown in fig. as with the single dimensional arrays,
each dimension of the array is indexed to zero to its maximum size minus one; the first index selects the
row and the second index selects the column within that row.

Representation of a two-dimensional array in memory

We may create a two-dimensional array like this:


int myArray [ ] [ ];
myArray = new int [3] [4];
or
int myArray [ ] [ ] = new int [3] [4];

// Example: Program to illustrate the application of Two-Dimensional Arrays.


class MulTable
{
final static int ROWS = 20;
final static int COLUMNS = 20;
public static void main(String args[ ])
{
int product[ ] [ ] = new int[ROWS][COLUMNS];
int row, column;
System.out.println(“MULTIPLICATION TABLE”);
System.out.println(“ ”);
int i,j;

for(i=10,i<ROWS;i++)
{
for(j=10;j<COLUMNS;j++)
{
product[i][j] = i*j;
System.out.println(“ ” + product[i][j]);

PARNASHREE S, SKPFGC Page 12


}
System.out.println(“ ”);
}
}
}

Array of Objects
In Java, an array of objects is used to store multiple instances of a class within a single array. This allows
us to easily manage a collection of objects when working with large datasets or collections.

Creating an Array of Objects in Java


In Java, we can create an array of objects just like any other array. The only difference is that the array
elements are references to objects rather than primitive types.
Declaration: To declare an array of objects, specify the class name followed by square brackets [].
Class_Name[ ] objectArrayReference;
Ex: Student[] students;

Alternatively, we can also declare an Array of Objects as,


Class_Name objectArrayReference[ ];
Ex: Student students[];

Instantiation: After declaring the array, instantiate it using the new keyword, specifying the size of the
array.
Class_Name obj[ ]= new Class_Name[Array_Length];
students = new Student[3]; // An array of 3 Student objects
Initialization: Each element of the array must be initialized individually via constructor.

Example: Program to create ‘Student’ class with Reg.no, name and marks of 3 subjects. Calculate
the total marks of 3 subjects and create an array of 3 student objects and display the results.

import java.util.Scanner;
class Student
{
int regNo;
String name;
int marks1, marks2, marks3;

int getTotalMarks()
{
return marks1 + marks2 + marks3;
}
}

PARNASHREE S, SKPFGC Page 13


public class Result
{
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
Student[] students = new Student[3]; // Array to store 3 students

for (int i = 0; i < 3; i++)


{
students[i] = new Student(); // Initialize the student object
System.out.println("Enter details for Student " + (i + 1));

System.out.print("Enter Registration Number: ");


students[i].regNo = scanner.nextInt();
scanner.nextLine(); // Clear buffer

System.out.print("Enter Name: ");


students[i].name = scanner.nextLine();

System.out.print("Enter Marks for Subject 1: ");


students[i].marks1 = scanner.nextInt();
System.out.print("Enter Marks for Subject 2: ");
students[i].marks2 = scanner.nextInt();

System.out.print("Enter Marks for Subject 3: ");


students[i].marks3 = scanner.nextInt();
System.out.println();
}

System.out.println("Student Results:");
for (int i = 0; i < 3; i++)
{
System.out.println("Student " + (i + 1) + ": " + students[i].name);
System.out.println("Registration No: " + students[i].regNo);
System.out.println("Total Marks: " + students[i].getTotalMarks());
System.out.println();
}
scanner.close();
}
}

PARNASHREE S, SKPFGC Page 14


Output:
Enter details for Student 1
Enter Registration Number: BC914
Enter Name: shruthi
Enter Marks for Subject 1: 45
Enter Marks for Subject 2: 76
Enter Marks for Subject 3: 88

Enter details for Student 2


Enter Registration Number: BC655
Enter Name: Deepika
Enter Marks for Subject 1: 54
Enter Marks for Subject 2: 98
Enter Marks for Subject 3: 76

Enter details for Student 3


Enter Registration Number: BC546
Enter Name: Saba
Enter Marks for Subject 1: 546
Enter Marks for Subject 2: 45
Enter Marks for Subject 3: 43

Student Results:
Student 1: Shruthi
Registration No: BC914
Total Marks: 209

Student 2: Deepika
Registration No: BC655
Total Marks: 228

Student 3: Saba
Registration No: BC546
Total Marks: 634

PARNASHREE S, SKPFGC Page 15


Strings
String manipulation is the most common part of many Java programs. Strings represent a sequence of
characters. The easiest way to represent a sequence of characters in Java is by using a character array.

Example:
char charArray[ ] = new char[4];

charArray[0] = ‘J’;
charArray[1] = ‘a’;
charArray[2] = ‘v’;
charArray[3] = ‘a’;
Copying one character array into another might require a lot of book keeping effort. Fortunately, Java is
equipped to handle these situations more efficiently.
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. Java strings, as compared to C strings, are more
reliable and predictable. This is basically due to C’s lack of bound-checking. A Java string is not a
character array and is NULL terminated. Strings may be declared and created as follows:
String stringName;
stringName = new String(“string”);

Example:
String firstName;
firstName = new String(“parna”);
These two statements may be combined as follows:
String firstName = new String(“parna”);

 Like arrays, it is possible to get the length of string using the length method of the string class.
int m = firstName.length( );
 Java strings may be concatenated using + operator.
Example:
String fullName = name1 + name2;
String city1 = “new” + “delhi”;
Where name1 and name2 are java strings containing string constants.

String Arrays: We can also create and use arrays that contain strings. The statement
String itemArray[ ] = new String[3];
will create an itemArray of size 3 to hold three string constants. We can assign the strings to the
itemArray element by element using three different statements or more efficiently using a for loop.

String Method: The String class defines a number of methods that allow us to accomplish a variety of
string manipulation tasks. Table lists some of the most commonly used methods, and their tasks. Program
shows the use of the method compareTo( ) to sort an array strings in alphabetical order.

PARNASHREE S, SKPFGC Page 16


Some most commonly used string methods:

Example: Java program to check whether the given string is palindrome or not.
import java.util.Scanner;
public class Palindrome
{
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);

// Ask for input


System.out.print("Enter a string: ");
String str = scanner.nextLine();

// Reverse the string and check if it's equal to the original


String reversed = new StringBuilder(str).reverse().toString();

if (str.equals(reversed))
{
System.out.println("The string is a palindrome.");
}
else
{
System.out.println("The string is not a palindrome.");
}
scanner.close();
}
}
PARNASHREE S, SKPFGC Page 17
Output:
Enter a string: sps
The string is a palindrome.

StringBuffer Class
StringBuffer is a peer class of String. While String creates strings of fixed_length, StringBuffer creates
strings of flexible length that can be modified in terms of both length and content. We can insert
characters and substrings in the middle of a string, or append another string to the end.

Commonly used StringBuffer methods

PARNASHREE S, SKPFGC Page 18

You might also like