Unit2 Java
Unit2 Java
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.
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:
myCar.brand = "Toyota";
myCar.year = 2020;
void displayDetails()
{
System.out.println("Brand: " + brand);
System.out.println("Year: " + year);
}
}
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.
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
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.
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.
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.
class Calculator
{
int add(int a, int b)
{
return a + b;
}
Example:
// Default constructor
public Employee()
{
name = "Unknown";
id = 0;
}
// Parameterized constructor
public Employee(String empName, int empId)
{
name = empName;
id = empId;
}
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:
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:
public class Main
{
int 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;
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;
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: 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];
Output:
Maximum Element: 99
Minimum Element: 2
for(i=10,i<ROWS;i++)
{
for(j=10;j<COLUMNS;j++)
{
product[i][j] = i*j;
System.out.println(“ ” + product[i][j]);
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.
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;
}
}
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();
}
}
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
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.
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);
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.