Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

IT Unit 1 CS and C++

Download as pdf or txt
Download as pdf or txt
You are on page 1of 9

Internet Technologies

Java is a high-level programming language originally developed by Sun Microsystems


and released in 1995. Java runs on a variety of platforms, such as Windows, Mac OS,
and the various versions of UNIX.
Why Use Java?
Java works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc.)
It is one of the most popular programming language in the world
It is easy to learn and simple to use
It is open-source and free
It is secure, fast and powerful
Java is an object oriented language which gives a clear structure to programs and
allows code to be reused, lowering development costs
As Java is close to C++ and C#, it makes it easy for programmers to switch to Java or
vice versa

Some of the key advantages of learning Java Programming:


Object Oriented − In Java, everything is an Object. Java can be easily extended
since it is based on the Object model.
Platform Independent − Unlike many other programming languages including C
and C++, when Java is compiled, it is not compiled into platform specific machine,
rather into platform independent byte code. This byte code is distributed over the web
and interpreted by the Virtual Machine (JVM) on whichever platform it is being run on.
Simple − Java is designed to be easy to learn. If you understand the basic concept of
OOP Java, it would be easy to master.
Secure − With Java's secure feature it enables to develop virus-free, tamper-free
systems.
Architecture-neutral − Java compiler generates an architecture-neutral object file
format, which makes the compiled code executable on many processors, with the
presence of Java runtime system.
Portable − Being architecture-neutral and having no implementation dependent
aspects of the specification makes Java portable..
Robust − Java makes an effort to eliminate error prone situations by emphasizing
mainly on compile time error checking and runtime checking.

Applications of Java Programming


Multithreaded − With Java's multithreaded feature it is possible to write programs
that can perform many tasks simultaneously.
Interpreted − Java byte code is translated on the fly to native machine instructions
and is not stored anywhere.
High Performance − With the use of Just-In-Time compilers, Java enables high
performance.
Distributed − Java is designed for the distributed environment of the internet.
Dynamic − Java is considered to be more dynamic than C or C++ since it is designed
to adapt to an evolving environment. Java programs can carry extensive amount of run-
time information that can be used to verify and resolve accesses to objects on run-time.
1|P ag e
When we consider a Java program, it can be defined as a collection of objects that
communicate via invoking each other's methods. Let us now briefly look into what do
class, object, methods, and instance variables mean.
Object − Objects have states and behaviors. Example: A dog has states - color, name,
breed as well as behavior such as wagging their tail, barking, eating. An object is an
instance of a class.
Class − A class can be defined as a template/blueprint that describes the
behavior/state that the object of its type supports.
Methods − A method is basically a behavior. A class can contain many methods. It is
in methods where the logics are written, data is manipulated and all the actions are
executed.
Instance Variables − Each object has its unique set of instance variables. An object's
state is created by the values assigned to these instance variables.

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.

Accessing Instance Variables and Methods


Instance variables and methods are accessed via created objects. To access an instance
variable, following is the fully qualified path −
/* First create an object */
ObjectReference = new Constructor();
/* Now call a variable as follows */
ObjectReference.variableName;
/* Now you can call a class method as follows */
ObjectReference.MethodName();

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

Creating, Initializing, and Accessing an Array


One-Dimensional Arrays :
The general form of a one-dimensional array declaration is
type var-name[];
OR
type[] var-name;
An array declaration has two components: the type and the name. type declares the
element type of the array. The element type determines the data type of each element
that comprises the array. Like an array of integers, we can also create an array of other
primitive data types like char, float, double, etc. or user-defined data types (objects of a
class). Thus, the element type for the array determines what type of data the array will
hold.

Instantiating an Array in Java


When an array is declared, only a reference of array is created. To actually create or give
memory to array, you create an array like this: The general form of new as it applies to
one-dimensional arrays appears as follows:
var-name = new type [size];
Here, type specifies the type of data being allocated, size specifies the number of
elements in the array, and var-name is the name of array variable that is linked to the
array. That is, to use new to allocate an array, you must specify the type and number
of elements to allocate.
Example:
int intArray[]; //declaring array
intArray = new int[20]; // allocating memory to array

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;

Java ArrayList class


In Java, ArrayList is a class of Collections framework. It implements List<E>,
Collection<E>, Iterable<E>, Cloneable, Serializable, and RandomAccess interfaces. It
extends AbstractList<E> class.
We can create an instance of ArrayList by using the following statement:
ArrayList<Type> arrayList=new ArrayList<Type>();
ArrayList is internally backed by the array in Java. The resize operation in ArrayList
slows down the performance as it involves new array and copying content from an old
array to a new array. It calls the native implemented method System.arraycopy(sec,
srcPos, dest, destPos, length) .
5|P ag e
We cannot store primitive type in ArrayList. So, it stores only objects. It automatically
converts primitive type to object. For example, we have create an ArrayList object,

ArrayList <Integer> list=new ArrayList<Integer>(); //object of ArrayList


arrayObj.add(12); //trying to add integer primitive to the ArrayList
The JVM converts it into Integer object through auto-boxing.
ArrayList arrayObj=new ArrayList()//object of ArrayList
arrayObj(new Integer(12)); //converts integer primitive to Integer object and added to
ArrayList object
Similarities
a) Array and ArrayList both are used for storing elements.
b) Array and ArrayList both can store null values.
c) They can have duplicate values.
d) They do not preserve the order of elements.

The following table describes the key differences between array and ArrayList:

Java Array Java ArrayList


An array is a dynamically-created The ArrayList is a class of Java
object. It serves as a container that Collections framework. It contains
holds the constant number of values popular classes like Vector,
of the same type. It has a contiguous HashTable, and HashMap.
memory location.
Array is static in size. ArrayList is dynamic in size.
An array is a fixed-length data ArrayList is a variable-length data
structure. . structure. It can be resized itself
when needed
It is mandatory to provide the size of We can create an instance of
an array while initializing it directly ArrayList without specifying its size.
or indirectly. Java creates ArrayList of default
size.
It performs fast in comparison to ArrayList is internally backed by the
ArrayList because of fixed size. array in Java. The resize operation in
ArrayList slows down the
performance.
Array can be multi-dimensional. ArrayList is always single-
dimensional.

In the following example, we have simply created an array of length four.


public class ArrayExample
{
public static void main(String args[])
{
//creating an array of integer type
int arr[]=new int[4];
//adding elements into array
6|P ag e
arr[0]=12;
arr[1]=2;
arr[2]=15;
arr[3]=67;
for(int i=0;i<arr.length;i++)
{
System.out.println(arr[i]);
}
}
}
Output:
12
2
15
67
Example of ArrayList in Java
In the following example, we have created an instance of ArrayList and performing
iteration over the ArrayList.
import java.util.*;
public class ArrayListExample
{
public static void main(String args[])
{
//creating an instance of ArrayList
List<Float> list = new ArrayList<Float>();
//adding element to arraylist
list.add(12.4f);
list.add(34.6f);
list.add(56.8f);
list.add(78.9f);
//iteration over ArrayList using for-each loop
for(Float f:list)
{
System.out.println(f);
}
}
}
Output:
12.4
34.6

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

You might also like