You are on page 1of 26

Programming in Java

Declaring Arrays in Java

Arrays are used typically to group objects of the same type and they are referred to
the group of objects by a common name.
Arrays can be declared of any type either primitive or class.
The declaration of an array creates space for a reference.
Actual memory allocation is done dynamically either by a new statement or by an
array initializer.

Java array is an object which contains elements of a similar data type. Additionally, The
elements of an array are stored in a contiguous memory location. It is a data structure
where we store similar elements. We can store only a fixed set of elements in a Java array.
Programming in Java

Explanation: Creating Arrays


Consider the Array depicted in the Fig. It is containing 5 Different values of similar
datatype. Remember the first no. is positioned as 0 the next number is positioned at 1 and
so on. Hence the 5th Number is positioned as position No. 4.

MyArray An Array can contain values


of similar types and they
24 65 -7 10 89 occupy continuous are
[0] [1] [2] [3] [4] within the Memory

Basis on the nature of the Array we can categorize an Array of –


 Single Dimensional Array
 Multi Dimensional Array
Programming in Java
Creating a Single Dimensional Array

Every element is initialized at the time of array creation.


The following code snippet displays an array with initial values:
String[] names = {“Maged","Jen","Simon"}; or
String[] names={"James","Sandy","Martin"};

Whenever you initialize an Array Variable it will acquire a property called length so
that you can come to know about how many elements it is containing inside.

Another Example can be:-


int[] myArray = new int[6];
Programming in Java
Demo: Using Array

package Mypackage;

public class ArrayExample {


Here It is an
public static void main(String[] args) { Example of Single
// TODO Auto-generated method stub Dimensional Array
String[] names={"James","Sandy","Martin"};
for(int k=0;k < names.length; k++)
{
System.out.println("Name At Position "+k+"="+names[k]);
System.out.println(“Length of String = “ +names[i].length);
}
}}
Programming in Java
Multidimensional arrays can be termed as an arrays of
arrays.
The following code snippet displays a two-dimensional
array:
int[ ][ ] twoDim = new int [4][ ];
twoDim[0] = new int[5];
twoDim[1] = new int[5];
Programming in Java
Example of 2-D Array
package Mypackage;
import java.util.*;
public class TwoDArray {
public static void main(String[] args) {
// TODO Auto-generated method stub
int[][] matrix1=new int[2][3]; int[][] matrix2=new int[2][3];int[][] matrix3=new int[2][3];
int j=0,i=0;
System.out.println("Enter The Values In First Matrix"); Scanner sc=new Scanner(System.in);
for (i=0;i < 2; i++)
{
for(j=0; j< 3;j++)
{
matrix1[i][j]=sc.nextInt();
}
}
System.out.println("Enter The Values In First Matrix");
for (i=0;i < 2; i++)
{
for(j=0; j< 3;j++)
{
matrix2[i][j]=sc.nextInt(); matrix3[i][j]=matrix1[i][j]+matrix2[i][j];
} }
System.out.println("Resultant Matrix is");
for (i=0;i < 2; i++)
{
for(j=0; j< 3;j++)
{
System.out.print(matrix3[i][j]+"\t");
}
System.out.print("\n");
} }}
Programming in Java
Copying Arrays

The Java programming language provides an arraycopy() method in the System class,
which is used to copy arrays.
It is a method that only copy references and not objects, when dealing with arrays of
objects.
Let us understand the concept of arraycopy() method by using the following code.
Programming in Java
Copying Arrays : Use of arraycopy()
public class CopyExample {

public static void main(String[] args)


{
// TODO Auto-generated method stub'
String[] newlist=new String[12];
String[] namelist={"Deepika","Rahul","Sonal","Aman","Vineeta","Rajinder"};
System.arraycopy(namelist, 0, newlist, 0,namelist.length);
System.out.println("New Names Are");
for(int k=0; k< namelist.length;k++)
{
System.out.println(newlist[k]);
}
}}

arracopy() takes 5 Parameters Like – Source Array, Source Position, Destination


Array, Destination Position , No.of Elements to be copied.
Programming in Java
Java LinkedList
Java LinkedList class uses a doubly linked list to store the elements. It provides a linked-list
data structure. It inherits the AbstractList class and implements List and Deque interfaces.

import java.util.LinkedList;
public class LinkExample {
public static void main(String[] args)
{
LinkedList<String> cars = new LinkedList<String>();
cars.add("Volvo"); cars.add("BMW"); cars.add("Ford");
cars.add("Mazda");
System.out.println(cars);
}}
Programming in Java

Difference Between An ArrayList & A LinkedList


ArrayList LinkedList

1) ArrayList internally uses a dynamic array to LinkedList internally uses a doubly linked
store the elements. list to store the elements.

2) Manipulation with ArrayList is slow because


it internally uses an array. If any element is Manipulation with LinkedList is faster than
removed from the array, all the bits are shifted ArrayList because it uses a doubly linked list,
in memory. so no bit shifting is required in memory.
LinkedList class can act as a list and
3) An ArrayList class can act as a list only queue both because it implements List and
because it implements List only. Deque interfaces.
4) ArrayList is better for storing, sorting and
accessing data. LinkedList is better for manipulating data.

ArrayList is also having a default constructor


ArryaList()
Programming in Java
Java Hashmap

import java.util.HashMap;

public class Main {


public static void main(String[] args) {
HashMap<String, String> capitalCities = new HashMap<String, String>();
capitalCities.put("England", "London");
capitalCities.put("Germany", "Berlin");
capitalCities.put("Norway", "Oslo");
capitalCities.put("USA", "Washington DC"); Run The Code And Try
System.out.println(capitalCities); To Understand its
}
Working Seeing the
}
Output
Programming in Java
Java Math class And Important Methods

Important Math Functionalities


Math.min(x,y) Evaluates the Minimum Between Two Numbers x & y
Math.max(x,y) Evaluates the Maximum Between Two Numbers x & y
Math.sqrt(x) Evaluates the Square Root of a No.
Math.abs(x) Returns the Absolute Value of a Number
Math.random() Return a Random Number Between 0.0 and 1.0 (exclusive)
Math.pow(x, y) Returns X to the power of Y
Math.round(x) Find the Closest Integer value from a decimal Value
Programming in Java
Java Math Class Functionalities

public class JavaMathExample1


{
public static void main(String[] args)
{
double x = 28; double y = 4;
// return the maximum of two numbers
System.out.println("Maximum number of x and y is: " +Math.max(x, y));
// return the square root of y
System.out.println("Square root of y is: " + Math.sqrt(y));
//returns 28 power of 4 i.e. 28*28*28*28
System.out.println("Power of x and y is: " + Math.pow(x, y));
// return the logarithm of given value
System.out.println("Logarithm of x is: " + Math.log(x)); System.out.println("Logarithm of y is: " + Math.log(y));

// return the logarithm of given value when base is 10


System.out.println("log10 of x is: " + Math.log10(x));
System.out.println("log10 of y is: " + Math.log10(y));

// return the log of x + 1


System.out.println("log1p of x is: " +Math.log1p(x));
// return a power of 2
System.out.println("exp of a is: " +Math.exp(x));
// return (a power of 2)-1
System.out.println("expm1 of a is: " +Math.expm1(x));
} }
Programming in Java
Using the Enhanced for Loop

An enhanced for loop is used to make array iteration easier.


The following code snippet displays an enhanced for loop that iterates over the array:
public void printElements(int[] list) {
for ( int element : list ) {
System.out.println(element);
}
}
Programming in Java
Some Important String Methods:-
No. Method Description
1 char charAt(int index) returns char value for the particular index
2 int length() returns string length
3 static String format(String format, Object... args) returns a formatted string.
4 static String format(Locale l, String format, Object... args) returns formatted string with given locale.
5 String substring(int beginIndex) returns substring for given begin index.
6 String substring(int beginIndex, int endIndex) returns substring for given begin index and end index.
7 boolean contains(CharSequence s) returns true or false after matching the sequence of char
value.
8 static String join(CharSequence delimiter, CharSequence... elemen returns a joined string.
ts)
9 boolean equals(Object another) checks the equality of string with the given object.
10 boolean isEmpty() checks if string is empty.
11 String concat(String str) concatenates the specified string.
12 String replace(char old, char new) replaces all occurrences of the specified char value.
13 static String equalsIgnoreCase(String another) compares another string. It doesn't check case.
14 String[] split(String regex) returns a split string matching regex.
15 String[] split(String regex, int limit) returns a split string matching regex and limit.
16 int indexOf(int ch) returns the specified char value index.
17 String toLowerCase() returns a string in lowercase.
18 String toUpperCase() returns a string in uppercase.
19 String trim() removes beginning and ending spaces of this string.
20 static String valueOf(int value) converts given type into string. It is an overloaded method.
Programming in Java

Inheritance:

Inheritance can be defined as the process where one class acquires the properties (methods
and fields) of another. With the use of inheritance the information is made manageable in a
hierarchical order.

The class which inherits the properties of other is known as subclass (derived class, child
class) and the class whose properties are inherited is known as superclass (base class,
Child parent class). We use extends keyword to implement inheritance. Following is the syntax of
Class/Subclass extends keyword.
class A extends B
{
Parent Class/ Super Class
}
Programming in Java

Inheritance:

In the above example A will be parent or the super class and B is the extended or the sub
class. In such a situation class B can inherit the public or protected or private-protected
members of the class A – however the private members will not be accessible. Inheritance
gives us the more power of code reusability and it is a common practice that we try to keep
the common information within the super class or the parent class.
Majorly Inheritance can be applied in many forms – namely they are Single Inheritance,
Multiple Inheritance, and Multilevel Inheritance- however Java only supports only Single
Inheritance & Multilevel Inheritance using classes. Multiple Inheritance is indirectly
supported in Java with another technique called interface. Now let us discuss about the
various types of inheritance:-
Programming in Java

Inheritance:
Single Inheritance: Single Inheritance occurs when there is only a parent class or the super
class and based on that class another sub class is formed. For e.g. –
class X
{
}
Now using the above class X say we are creating another class called Y like below-
class Y extends X
{}
- here it is an example of Single Inheritance as there is a single super class (X) and there is a
single sub class (Y).
Programming in Java
Inheritance:
Multilevel Inheritance: Multilevel Inheritance occurs when there is only a parent class or
the super class and based on that class another sub class is formed but the super class itself
is a sub class. For e.g. –
class X
{
}
Now using the above class X say we are creating another class called Y like below-
class Y extends X
{
} - here it is an example of Single Inheritance as there is a single super class (X) and there is
a single sub class (Y).
class Z extends Y { }
- here class Z is also a sub class but it is formed based on another class Y which itself is a
sub class of X. So in this case it will be considered as a multilevel inheritance.
Programming in Java
Inheritance:

Multiple Inheritance: As already mentioned Java does not support Multiple Inheritance-
however Multiple Inheritance occurs when a sub class is created using more than 1 parent
classes. In some other languages like C++ it supports Multiple Inheritance. However Java
Supports Multiple Inheritance with the help of interface.

Trainer Will Give Demonstration of Single & Multi Level Inheritance with some
suitable Examples.
Programming in Java
Interface:
An interface is a something like a class that is used to group related methods with empty
bodies. Remember in an interface we can only define some methods but all the methods
will remain empty. Later on we can create a class by using an interface and in that class we
can define the executable codes within the functions or methods. An interface can be
created as follows :-
interface myinterface
{
public void Show();
public void ShowHeading();
}
So in the above case interface keyword is used to create an interface. Now if we want to
use the interface by using another class we have to use a keyword called implements. For
e.g.-
Programming in Java
Interface:
public class newclass implements myinterface
{ int x,y,z;
public newclass() { x=7; y=10; } // Implementing Constructor
public void Show()
{ z=x+y;
System.out.println(“Total = “+String.valueOf(z));
}
public void ShowHeading() // Implementing the Second Function of the interface
{ System.out.println(“Showing Calculation”); }
public static void main(String[] args)
{
newclass n1=new newclass(); n1.ShowHeading();
n1.Show();
} } // End of class
Also it is important to note that once you have implemented an interface then all the
methods declared within that interface must be defined within the class which is using the
same interface. Otherwise there will be compilation error.
Programming in Java
Interface:

Notes on Interfaces:
 Interfaces cannot be used to create objects.
 Interface methods do not have a body - the body is provided by the "implement" class
 On implementation of an interface, you must override all of its methods
 Interface methods are by default abstract and public
 Interface attributes are by default public, static and final
 An interface cannot contain a constructor (as it cannot be used to create objects)
Why And When To Use Interfaces?
 To achieve security - hide certain details and only show the important details of an
object (interface).
 Java does not support "multiple inheritance" (a class can only inherit from one
superclass). However, it can be achieved with interfaces, because the class
can implement multiple interfaces. 
 To implement multiple interfaces, separate them with a comma (see example below).
Programming in Java
Interface:
interface FirstInterface {
public void myMethod(); // interface method
}
interface SecondInterface {
public void myOtherMethod(); // interface method
}
class DemoClass implements FirstInterface, SecondInterface {
public void myMethod() {
System.out.println("Some text..");
}
public void myOtherMethod() {
System.out.println("Some other text...");
}}
class Demo {
public static void main(String[] args) {
DemoClass myObj = new DemoClass();
myObj.myMethod(); myObj.myOtherMethod();
}}
Programming in Java
Lab Assignment:
1. Implement an Interface with two member functions called –pyramid() and flag() and
use these two methods in a different class. The pyramid() will produce the output as –
1
22
333
4444
Where as the flag() will produce the output as-
******
*****
****
***
**
*
2. Implement an interface and with a member function arrange() and Fibonacci(int) -
describe It in a class so that you can input some numbers in an array and arrange them in
ascending order. The other Function Fibonacci() will be able to generate all the Fibonacci
series till the number sent as a parameter.
Programming With Java

End of Day 4

You might also like