0% found this document useful (0 votes)
9 views

Unit 2 Java

Uploaded by

vinaydarling063
Copyright
© © All Rights Reserved
Available Formats
Download as RTF, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

Unit 2 Java

Uploaded by

vinaydarling063
Copyright
© © All Rights Reserved
Available Formats
Download as RTF, PDF, TXT or read online on Scribd
You are on page 1/ 20

UNIT -2

ARRAYS
An array represents a group of elements of same data type.It can store a group of elements.So, we
can store a group of int values or a group of float values or a group of strings in the array. But we can
not store some int values and some float values in the array.

In c/c++, by dafault , arrays are created on static memory unless pointers are used to create them. In
Java, arrays are created on dynamic memory by JVM( Java Virtual Machine)

EXAMPLE:- Suppose a class contains 50 students, and we want to store their roll numbers, we need
50 seperate variables for storing the roll numbers, as shown below

int rno;

int rno1;

int rno2;

int rno49;

TYPES OF ARRAYS:

In general arrays are partitioned into two types as shown in below:

* Single dimensional arrays ( or 1D arrays)

* Multi dimensional arrays ( or 2D, 3D,....arrays)

Single Dimensional Arrays (1D array)

The single dimensional or a one dimensional array (1D) represnts either a row or a column
of elements. For example, the marks obtained by a student in 5 different subjects can be
represented by using a 1D array.

we can decalre a one dimensional array and directly store elements at the time of
declaration

int marks [ ] = { 50, 60, 57, 64, 68 };


PROGRAM:

write a program to create a 1D array and read its elements by using a loop and display them one by
one.

class Arr1

int arr [ ] ={ 50, 60, 57, 64, 68 };

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

system.out.println( arr[i] );

OUTPUT:

c:\> java Arr1.java

c:\> java Arr1

50

60

57

64

68

Multi Dimensional Arrays (2D,3D,......arrays)

Multi dimensional arrays represents 2D,3D,.... which are a combination of several earlier
types of arrays. A two dimensional array is a combination of two or more (1D) one dimensional
arrays. Similarly, a three dimensional is acombination of two or more (2D) two dimensional arrays.
Two dimensional arrays (2D array)

A two dimensional array represnts several rows and columns of data. For example, the
marks obtained by a group of students in five different subjects can be represented by a 2D array

* 20 35 43 40 39

* 37 42 29 32 48

* 47 33 46 34 41

int marks [ ] [ ] ={{20, 35, 43, 40, 39},{37, 42, 29, 32, 48},

{47, 33, 46, 34, 41}};

PROGRAM:- write a java program to display the marks obtained by a group of students in five
different subjects by two dimensional array in matrix form using loops

class Students

public static void main ( String args [ ] )

int a [ ] [ ] ={ { 20, 35, 43, 40, 39 },{ 37, 42, 29, 32, 48 },

{ 47, 33, 46, 34, 41}};

system.out.println( " In matrix form");

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

for ( int j=0; j<5; j++ )

system.out.print ( a [i] [j]+"\t" );

system.out.println ( );

}
}

OUTPUT:

c:\> javac students.java

c:\>java students

20 35 43 40 39

37 42 29 32 48

47 33 46 34 41

Three dimensional arrays (3D array)

A three dimensional array is a combination of several (2D) two dimensional arrays. This
array is used to handle group of elements belonging to another group.For example, a college has 3
departments: Electronics Civil and Computers.Now, to represent the marks obtained by the students
of each department in 3 different subjects by 3D array

Department Of Electronics:

student1 marks : 60 62 66

student2 marks : 45 47 49

Department Of civil:

student1 marks : 50 54 58

student2 marks : 49 54 57

Department Of computers:

student1 marks : 66 68 72

student2 marks : 73 71 68

By using 3D array we can store all these marks, department-wise as shown below:

{{{60, 62, 66 }, {45,47,49}},

{50, 54, 58}, {49, 54, 57},


{66, 68, 72}, {73, 71,68}}};

program:

class Departments

public static void main(String args[])

int dept,student,marks,tot=0;

int arr[] [] []={{{60, 62, 66 }, { 45, 47, 49}},

{{50, 54, 58 }, {49, 54, 57 }},

{{66, 68, 72 }, {73, 71, 68 }}};

for (dept=0; dept<3; dept++)

system.out.println ("department " +(dept +1)+" :");

for (student=0; student<2; student++ )

system.out.print("student " +(student+1)+"marks:");

for(marks=0;marks<3;marks++)

system.out.print(arr[dept][student][marks]+" ");

tot +=arr[dept][student][marks];

system.out.println("total: "+ tot);

tot=0;

}
system.out.println();

OUTPUT:

c:\> javac departments.java

c:\> java departments

department 1:

student 1 marks: 60 62 66 total:188

student 2 marks: 45 47 49 total:141

department 2:

student 1 marks: 50 54 58 total:162

student 2 marks: 49 54 57 total:160

department 3:

student 1 marks: 66 68 72 total:206

student 2 marks: 73 71 68 total:212

ARRAY NAME.LENGTH:

To know the size of the array, We use the property 'length' of an array.
arrayname.length returns an integer value that represents the size of an array.

For example, take an array arr[ ] having size 10 and contains three elements in it.

int arr [ ] = new int [10];

arr [0]=30, arr[1]=45, arr[2]= 55;

Now, The array.length gives 10. a nd the array arr[ ] contained 3 elements, but length
propery won't give the number of elements of the array it gives only its size.

JAGGED ARRAYS:
A jagged array is an array that contains a group of arrays within it. If we create an
array in java the reamaining arrays will become its elements.It is an unique feature in java.

Jagged array can store single dimensional (1D)arrays or multi-dimensional


(2D,3D,etc) arrays and also can store arrays of any size. Jagged array is also called as 'irregular
multidimensional arrays'. it is very useful when we deals with a group of arrays having different sizes.

STRINGS
A string is said to be a sequence of characters placed in double quotes (" ") whatever the type
we may given ( integer, float ,char) all are taken as strings. so a string represents a group of
characters.

String is a class in java.lang package. But in java, all classes are considered as data types.
so we can take string as a data type also.

ex: string s ="java";

Here, s is a variable of the data type 'String'.

A string can be created by assigning a group of characters to a string type variable.

String s; // declaring variable

: s ="Hello"; // assigning charcter to it

while combined these two statements and can be wriiten as

String s = "Hello";

Jvm creates an object to store the string "Hello" in that object. Creating an object refers to allocating
some memory inorder to s2.Stringstore the data.

String class methods:

The string class contains many methods...some methods are as follows.

 String cancat(String s): Concat stands for concatenates.cancat is a method which is used to
join the two strings.

ex: String s3= s1.cancat(s2);

s1 also a string which can merge with s2 and finally stored in s3.
 int length ():This method returns the length or number of characters in the string. ex..
s1.length() gives the number of characters in the String s1.

 char charAt(int i): This method returns the characters in the specified location i. suppose we
call this methd as s1.charAt(5).then it gives the 5th character of the string s1.

 int compareTo(string s):This method is useful to compare two strings and to say which is
bigger and which is smaller. ex... s1.compareTo(s2). now thismethod compare s1 string with
string s2 and display the result .here it should consider case sensitive i.e. Box is different with
box.

 int compareToIgnorecase(String s): It is as same as intcompareTo() method but it ignores the


case sensitive. it can not consider the difererence betweeb Box and box strings.

 boolean equals(String s):This method returns true if both Strinhs are equal ..else return false.
Ex..s1.equals(s2);"

 String replace(char c1, char c2): this method replaces allthe occurrencesof charector c1 by
new character c2.ex. s1="hello" and we are using as s1.replace('l','x'); then the result is
hexxo.. Here 'l'will be replaced by 'x'.

 String trim(): this method removes the places at the begging and ending of the String

 void getChars(int i1,int i2,char arr[ ],int i3 ): this method copies characters into string into a
character array.

 String [ ] split (delimiter):This method is used to break a string into peices at places
represented by the delimiter. for example the delimiter is a comma[ , ],the is cut into peices
where ever it found comma .

consider the following program

import java.lang.*;

class Demostr

{ public static void main(String arrgs[ ] )

{ //create strings in 3 arrays

String s1=" this book is java book";

String s2=new String (" i like this book");

char arr[] = { 'k','i','s','t'};


String s3= new String(arr);

// to display all the strings

System.out.println(s1);

System.out.println(s2);

System.out.println(s3);

// to find length of the first string

System.out.println("length of the first string s1=" + s1.length() );

// to concatinate two strings

System.out.println(s1 +"from "+s3);

Immutability Of Strings:
We can divide objects broadly as mutable objects and immutable objects. mutable
objects are those objects whose contents can be modified. The objects which can not be modified
after creation are called immutable objects.

1:write a program to test the immutability of strings,

class Xyz

public static void main (String args [ ])

String s1 = "dell";

String s2 ="computers";

s1 =s1+s2;

system.out.println(s1);
}

STRING BUFFER AND STRING BUILDER


we already know that strings are immutable and connot be modified.To overcome this feature we
got another class 'stringbuffer' which means the data can be modified.It menas stringbuffer class
objects are mutable, and there are some methods in this class which we can directly manipulate the
data inside the object.

We have some classes whose objects are mutable. They are


character,Byte,Integer,Float,Double,Long....called as wrapper classes created as immutable. some
other classes like Class,BigInterger,BigDecimal.

Creating StringBuffer Objects:

A stringBuffer object can be created by passing a string to the object, using a new
operator

StringBuffer sb = new StringBuffer ("HAI");

Here, we passed a string "HAI" to the StringBuffer object 'sb'. then the statment will
be like :

system.out.println (sb);

Displays "HAI".

StringBuffer Class Methods:

There are mainly four methods available in StringBuffer Class. which are given below :

1) StringBuffer append (x)

2) StringBuffer insert ( int i, x)

3) StringBuffer delete (int i, int j)

4) StringBuffer reverse( )

StringBufferappend(x):x represnts any type like boolean,byte,int,long,float,double,char,character


array,String or another StringBuffer.It will be added to StringBuffer object, For example,

StringBuffer sb = new StringBuffer("Tech");


sb.append("Mahindra");

Preceeding these two statments produce, "TechMahindra" as the String "Mahindra" is added to the
end "Tech".

StringBuffer insert(int i, x): Here also x represents any type like boolean,byte,double,String or
another StringBuffer. x will be inserted into StringBuffer at the position represented by i.

For example:

StringBuffer sb = new StringBuffer ( "Talented person");

sb.insert (8, "young");

Now, the StringBuffer object contains "Talented person". Counts from 0, then the string
"Talented" has 7 characters. So, sb.insert(7, "young") will insert the String, "young" at 7 th position,
and the output we get is "Talentedyoung person" in sb.

StringBuffer delete(int i, int j): This method deletes the characters from i th postion to j-1th position in
the StringBuffer.

For example:

String BufferReader = new StringBufferReader(“Tech mahedra”);

sb.delete (0,4) deletes the characters from the begining to 3 rd character ("Tech") and the
remaining String in 'sb' will be "Mahindra".

StringBuffer reverse (): This method reverses the sequence of the characters in the StringBuffer.If the
StringBuffer contains "xyz", It becomes "zyx".

// write a program how to use some of the StringBuffer class methods.

import java.io.*;

class Full

public static void main(String args[ ])

throws IOException

StringBuffer sb= new StringBuffer();


BufferedReader br= new BufferedReader

(new InputStreamReader(system.in));

system.out.print("Enter Surname:");

String sur= br.readLine();

system.out.print("Enter Midname:");

String Mid= br.readLine();

system.out.print("Enter Lastname:");

String Last= br.readLine();

sb.append(Sur);

sb.aappend(Last);

system.out.println("Name=" + sb);

Int n=Sur.length();

sb.insert (n,mid);

system.out.println("Fullname= "+ sb);

system.out.println("In reverse= "+ sb.reverse( ) );

OUTPUT:

c:\> javac Full.java

c:\> java Full

Enter surname: venkata

Enter midname:phani

Enter lastname:kumar

Name = phanikumar
Full name = venkataphanikumar

In reverse = ramukinahpataknev

// Write a program for testing a string wheather it is a palindrome or not.

import java.io.*;

class Palindrome

public static void main(String[args]) throws IoException

BufferedReader br = new BufferedReader(new

InputStreamReader(system.in));

system.out.print("Enter a String: ");

String str = br.readLine( );

String temp = str;

StringBuffer sb = new StringBuffer(str);

sb.reverse( );

str = sb. toString( );

if(temp.equalsIgnoreCase(str))

system.out.println(temp+ "is palindrome);

else system.out.println(temp+ " is not a palindrome");

OUTPUT:

c:\> javac palindrome.java

c:\> java palindrome


Enter a String: Malayalam

Malayalam is palindrome

INTRODUCTION TO OOPS
Oops stands for Object Oriented Programming Language.Java uses the concepts of classes and
objects to develop a program ..so java is said to be a fully object oriented programming language
where as c++ is not fullfledged object oriented programming because with out using concept of class
and object we will develop a program in c++.

in object oriented approach the main module is divided into several modules and these are
represented as classes. Each class can perform some task for which several methods are written in a
class.. This approach is called object oriented approach.

FEATURE OF OOPS :

1. Object

2. Class

3. Method

4. Data abstraction

5. Encapsulation

6. Inheritance

7. Polymorphism

8. Dynamic binding

9. Message passing

10. Delegation

11. Genericity

1.Object: Objects are primary run-time entities in object oriented programming. They may
stand for a thing that makes sense in a specific application. Programming issues are analyzed in
terms of objects and type of transmission between them. Objects occupy space in the memory.
Every object has its own properties or features. An object is a specimen of a class. It has its own
name and also specific behaviour depends on the member function of that class.
The properties of the object is
* It is individual.

* It points to a thing either physical or logical that is identifiable by the user.

* It holds data as well as operation method that handles data.

* Its scope is limited to the block where it is defined.

Ex:- Computer, Book, Fan ,Watch etc,

2.Class: A class is the accomplishment of abstract data type. In other words, A class is a
grouping of objects having the identical properties,common behaviour and shared relationship.
Objects are nothing but variables of type class. Once a class has been declared, the programmer can
create any number of objects using that class. A class is a model for creating an object.

Example:
Class :Car

properties: company, model, colour, capacity

Action: speed(),break(),average()

EX: class A
{ int A;

Float B;

char c;

get();

show();

};

By default all the member variables of a class are private data tyep and member functions of class
are public data type.Once we define a variable in the private data type,the scope that variable is to
the particular class only.
3.Method:- An operation required for an object or an entity when coded in a class is called a
method. The operation that are required for an object are to be defined in a class.All objects in a
class perform common actions or operations.

EX: Class A
{

int a;

float b;

char c;

method1 ()

method2 ()

};

4.Data Abstraction:-Abstraction refers to the procedure of representing essential features


without including the background details.Data abstraction is the procedure of identifying propeties
and methods related to a specific entity as applicable to the application.

For exmaple: Computer

5.Encapsulation:- C++ supports the features of encapsulation using classes.The package of


data and functions into a single component is known as encapsulation.The data is not
accessible by outside function.only those functions that are able to access the data are define within
the class.with encapsulation data hiding can be accomplished. By data hiding an object can be used
by the user without knowing how it works internally.

EX: Class A
{

private:

int a;

float b;

char c;

public:

show ();

display ();

};

6.Inheritanace:- Inheritance is the method by which objects of one class can get the
properties of another class. In object oriented programming,inheritance provides the thought of
reusability. The programmer can add new properties to the existing class without changing it. This
can be achieved by deriving a new class from the existing one. The new class will process the feature
of the both classes.

In the above example, Red,Yelow and blue are the main colours. Orange colour is created from the
combination of Red and Yellow. Green colour is created from Yellow and Blue. likewise Violet colour
is created from Red and Blue. Orange colour has attributes of Red and Yellow which produces a new
effect. Thus, many combinations are possible.

7.Polymorphism:- Polymorphism is Greek word. It is nothing but the combination of two


words "Poly" and "Morphism". Poly means 'Many'. Morphism means

'Forms'. So, polymorphism is many forms. Polymorphism accomplishes an important part in allowing
of objects of different classes to share the same external interfaces. The basic concept of
polymorphism is an object acts different types in different locations.

8.Dynamic Binding:- Binding means connecting one program to another program that is to
be executed in reply to the call.Dynamic binding is also called Late binding. The code present is
specified progarm is unknown till it is executed. It is analogus polymorphism.
9.Message passing:- An Object oriented programming includes objects which
communicates with each other. To behave like that object should be following steps.

1. Declaring classes that define objects and their actions.

2. Declaring objects from classes.

3. Implementing relation between objects.

10.Delegation:- In object oriented proramming language,two classes can be joined either by


inheritance or delegation, Which provide reusability of the class. When object of one class is used as
data member of another class, such composition of object is known as Delegation.

In other words, an object of class acts as a data member in another class is said to be Delegation.

11.Genericity:- The software compponents of a program have more than one version
depending on the data type of arguments. This feature allows declaration of variables without
specifying exact data type. The compiler can identify the data type at run time. This feature is said to
be generic feature.

**************************

You might also like