IT Unit 1 CS and C++
IT Unit 1 CS and C++
IT Unit 1 CS and C++
Classes in Java
A class is a blueprint from which individual objects are created.
Following is a sample of a class.
Example
public class Dog {
String breed;
int age;
String color;
void barking() {
}
void hungry() {
}
void sleeping() {
}
}
A class can contain any of the following variable types.
Local variables − Variables defined inside methods, constructors or blocks are called
local variables. The variable will be declared and initialized within the method and the
variable will be destroyed when the method has completed.
Instance variables − Instance variables are variables within a class but outside any
method. These variables are initialized when the class is instantiated. Instance variables
can be accessed from inside any method, constructor or blocks of that particular class.
Class variables − Class variables are variables declared within a class, outside any
method, with the static keyword.
A class can have any number of methods to access the value of various kinds of
methods. In the above example, barking(), hungry() and sleeping() are methods.
Following are some of the important topics that need to be discussed when looking into
classes of the Java Language.
2|P ag e
Creating an Object
As mentioned previously, a class provides the blueprints for objects. So basically, an
object is created from a class. In Java, the new keyword is used to create new objects.
There are three steps when creating an object from a class −
Declaration − A variable declaration with a variable name with an object type.
Instantiation − The 'new' keyword is used to create the object.
Initialization − The 'new' keyword is followed by a call to a constructor. This call
initializes the new object.
Import Statements
In Java if a fully qualified name, which includes the package and the class name is
given, then the compiler can easily locate the source code or classes. Import statement is
a way of giving the proper location for the compiler to find that particular class.
For example, the following line would ask the compiler to load all the classes available
in directory java_installation/java/io −
import java.io.*;
Arrays in Java
An array is a group of like-typed variables that are referred to by a common name.
Arrays in Java work differently than they do in C/C++. Following are some important
points about Java arrays.
In Java all arrays are dynamically allocated.
Since arrays are objects in Java, we can find their length using the object property
length. This is different from C/C++ where we find length using sizeof.
A Java array variable can also be declared like other variables with [] after the data
type.
The variables in the array are ordered and each have an index beginning from 0.
Java array can be also be used as a static field, a local variable or a method parameter.
The size of an array must be specified by an int value and not long or short.
The direct superclass of an array type is Object.
Every array type implements the interfaces Cloneable and java.io.Serializable.
Array can contain primitives (int, char, etc.) as well as object (or non-primitive)
references of a class depending on the definition of the array. In case of primitive data
3|P ag e
types, the actual values are stored in contiguous memory locations. In case of objects of
a class, the actual objects are stored in heap segment.
Java Arrays
Advantages
o Code Optimization: It makes the code optimized, we can retrieve or sort the data
efficiently.
o Random access: We can get any data located at an index position.
Disadvantages
Size Limit: We can store only the fixed size of elements in the array. It doesn't grow its
size at runtime. To solve this problem, collection framework is used in Java which
grows automatically
Arrays of Objects
An array of objects is created just like an array of primitive type data items in the
following way.
Student[] arr = new Student[7]; //student is a user-defined class
4|P ag e
The studentArray contains seven memory spaces each of size of student class in which
the address of seven Student objects can be stored.The Student objects have to be
instantiated using the constructor of the Student class and their references should be
assigned to the array elements in the following way.
Student[] arr = new Student[5];
Cloning of arrays
When you clone a single dimensional array, such as Object[], a “deep copy” is
performed with the new array containing copies of the original array’s elements as
opposed to references.
// Java program to demonstrate
// cloning of one-dimensional arrays
class Test
{
public static void main(String args[])
{
int intArray[] = {1,2,3};
int cloneArray[] = intArray.clone();
// will print false as deep copy is created
// for one-dimensional array
Java Array
An array is a dynamically-created object. It serves as a container that holds the constant
number of values of the same type. It has a contiguous memory location. Once an array
is created, we cannot change its size. We can create an array by using the following
statement:
int array[]=new int[size];
The above statement creates an array of the specified size. When we try to add more
than its size, it throws ArrayIndexOutOfBoundsException. For example:
int arr[]=new int[3]; //specified size of array is 3
//adding 4 elements into array
arr[0]=12;
arr[1]=2;
arr[2]=15;
arr[3]=67;
The following table describes the key differences between array and ArrayList:
56.8
78.9
Java ArrayList
The ArrayList class is a resizable array, which can be found in the java.util package.
Example
Create an ArrayList object called cars that will store strings:
7|P ag e
import java.util.ArrayList; // import the ArrayList class
ArrayList<String> cars = new ArrayList<String>(); // Create an ArrayList object
If you don't know what a package is, read our Java Packages Tutorial.
Add Items
The ArrayList class has many useful methods. For example, to add elements to the
ArrayList, use the add() method:
Example
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
ArrayList<String> cars = new ArrayList<String>();
cars.add("Volvo");
cars.add("BMW");
cars.add("Ford");
cars.add("Mazda");
System.out.println(cars);
}
}
Access an Item
To access an element in the ArrayList, use the get() method and refer to the index
number:
Example
cars.get(0);
Remember: Array indexes start with 0: [0] is the first element. [1] is the second element,
etc.
Change an Item
To modify an element, use the set() method and refer to the index number:
Example
cars.set(0, "Opel");
Remove an Item
To remove an element, use the remove() method and refer to the index number:
Example
cars.remove(0);
To remove all the elements in the ArrayList, use the clear() method:
Example
cars.clear();
ArrayList Size
To find out how many elements an ArrayList have, use the size method:
Example
8|P ag e
cars.size();
Loop Through an ArrayList
Loop through the elements of an ArrayList with a for loop, and use the size() method to
specify how many times the loop should run:
Example
public class Main {
public static void main(String[] args) {
ArrayList<String> cars = new ArrayList<String>();
cars.add("Volvo");
cars.add("BMW");
cars.add("Ford");
cars.add("Mazda");
for (int i = 0; i < cars.size(); i++) {
System.out.println(cars.get(i));
}
}
Sort an ArrayList
Another useful class in the java.util package is the Collections class, which include the
sort() method for sorting lists alphabetically or numerically:
Example
Sort an ArrayList of Strings:
import java.util.ArrayList;
import java.util.Collections; // Import the Collections class
public class Main {
public static void main(String[] args) {
ArrayList<String> cars = new ArrayList<String>();
cars.add("Volvo");
cars.add("BMW");
cars.add("Ford");
cars.add("Mazda");
Collections.sort(cars); // Sort cars
for (String i : cars) {
System.out.println(i);
}
}
}
9|P ag e