Java - Unit - 2

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 16

UNIT – II

Arrays, Strings in Java


Array:
 An array can be defined as an infinite collection of homogeneous (similar type)
elements.
 Arrays are always stored in consecutive memory locations.
 Arrays can be stored in multiple ways:
1024 1026 1028 1030 1302 1304 --Address
1 2 3 4 5 6
0 1 2 3 4 5 -- Index / Position
Declaration of Array:
datatype varname [ size]
int num [5]
Datatype varname [expression] = {values}
int num [6] = {1,2,3,4,5,6}
char a [5] = {‘a’, ‘b’, ‘c’, ‘d’, ‘e’}
Initialization of 2D array;
datatype varname [rows][columns] = {values};
int num [3][2] = {1,2,3,4,5,6}
1 2 num [0,0] = 1 num [1,1] = 4
3 4  num[0,1] = 2 num[2,0] = 5
5 6 num [1,0] = 3 num [2,2] = 6

Example:
class Testarray
{
public static void main (String args [])
{
int [] = new int [5];
a [0] = 10;
a [1] = 20;
a [2] = 30;
a [3] = 40;
a [4] = 50;
for(int i=0; i<a.length;i++);
{
System.out.println(a[i]);
}
}
}
Output:
10
20
30
40
50

TWO DIMENTIONAL ARRAY.


Import java lang.*;
Class Two
{
public static void main(String args[])
{
Int r,c;
Int x[ ] [ ] ={{10,20,30},{40,50,60}};
System.out.println(“Two dimensional elements”);
for(r=0; r<=1; r++)
{
for (c=0; c <=2; c++)
{
System.out.println(x[r] [c]);
}
System.out.println( ); //It goes to next line
}
Introduction to java.util.Array Class:
The java. util.Arrays class contains a static factory that allows arrays to be viewed as lists.
Following are the important points about Arrays.
1. This class contains various methods for manipulating arrays (such as sorting and
searching).
2. The methods in this class throw a NullPointerException if the specified array reference
id null.
Class Declaration
Following is the declaration for java.util.Arrays class:
public class Arrays extends Object

Difference between string and buffer class:


String String Buffer

String class uses string objects for storing the String buffer class creates an object and stores
values value in it
These values are immutable (i.e.,) these string These values can be changed at any point of time.
object values cannot be changed once declared Hence the String Buffer class object are mutable.

This class is available in java.lang.package This class is also available in java.lang.package


Syntax:
StringBuffer reference variable = new StringBuffer(“String”);
StringBuffer SB = new StringBuffer(“Welcome”);

//program for StringBuffer


Import java.lang.*
class SB
{
public static void main (String args [])
{
StringBuffer str = new StringBuffer(‘Welcome”);
system.out.println(str);
}
}
Output:
Welcome

Wrapper Class:

 Wrapper Class: As java is purely OOP language, every entity should be measured in
terms of object. Wrapper class is a mechanism to convert primitive datatype in objects
and objects into primitive datatype.
 We have wrapper class in java.lang.
Primitive datatypes Wrapper class
byte Byte
short Short
int Int
long Long
float Float
double Double
char Char
boolean Boolean

Conversion is of two types:

 Java allows automatic conversion between the primitives and their respective wrapper
objects through auto-boxing and unboxing.

Auto Boxing

 Auto-boxing is the automatic conversion of a primitive datatypes to wrapper objects.


For example, we can assign a primitive type to an object type.
 Similarly, Unboxing allows converting wrapper objects into primitive datatypes. For
example, we can create an instance of a wrapper object and covert it to a primitive
automatically.
Converting primitive datatypes into objects

Import java lang.*;


class wrapper
{
public static void main(String args[ ])
{
Int a=100; //integer primitive datatype
Integer obj1=new integer(a); //boxing process with constructor
//a value get stored in obj 1
(or)
Integer obj2=integer value of(a);
//using value of( )method
(or)
Integer obj3=a; //another way of converting
// autoboxing
System.out.println(obj1+ “ “ +obj2+ “ “ +obj3);
}
}
Explaination of the above program
// we can use any one of above methods to convert primitive datatypes into
objects.

2) Convert objects to primitive type


Import java lang.*
Class wrapper class
{
public static void main (String args[])
{
Int a =100;
Integer obj = new integer (a); // in this method value of a is stored in obj;
Int x =obj. intvalue();// using int value( )method
Int y=obj; // direct
System.out.println(a+” “+x “ “+y “ “ +obj)
}
}

Inheritance, Interfaces and packages in JAVA


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 super class (base class, parent class).

In Java, it is possible to inherit attributes and methods from one class to another. We group the
"inheritance concept" into two categories:

 Subclass (child) - the class that inherits from another class

 Superclass (parent) - the class being inherited from

To inherit from a class,we use the extends keyword.

In the example below, the Car class (subclass) inherits the attributes and methods from
the Vehicle class (superclass):

Syntax:

class subclass_name extends superclass_name

______________

______________

_______________

Example program on inheritance(multiple inheritance):

Class Parent1

Void fun()
{

System.out.println(“parent1”);

Class Parent2

Void fun()

System.out.println(“parent2”);

Class Text extends Parent1,Parent2

public static void main(String args[])

Text t = new Text();

In the above program class Text inherits the properties of parent1 and parent2.

Abstract Class in Java

A class which contains the abstract keyword in its declaration is called Abstract class.

Syntax:

Abstract class A

------
------------

}
In java, the following some important observations about abstract classes are as follows:
1. We cannot create object for abstract class, but we can create reference variable for
abstract class.
2. Constructors are allowed.
3. We can have an abstract class without any abstract method.
4. An abstract method has no body.
5. We can use the abstract keyword for declaring top-level classes (Outer class) as well as
inner classes as abstract
6. If a class contains at least one abstract method then compulsory should declare a class as
abstract .

Program on Abstract class

abstract class A
{
abstract void display ( );
Class B extends A
{
Void display ( )
{
System.out.println(“class A”)
}
}
Class abstract
public static void main(tring args[ ])
{
B obj =new B ( );
Obj.display( );
}
}

o/p – class A

METHOD OVERRIDING:

1.The process of redefining a parent class’s method in a subclass is known as method


overriding.

2. It is implemented with the help of inheritance.


3. Method name should be same in both super class and sub class.
4. Return type, scope, parameter should be same in both super class and subclass.
5. Methods declared as final cannot be overridden.
6. static methods cannot be overridden.
7. It also called Runtime polymorphism(or) dynamic(or)late binding.

Note :
1. In C++, we need virtual keyword to achieve overriding or Run Time Polymorphism. In Java,
methods are virtual by default.

program on overriding
class Parent {
void display()
{
System.out.println(“Parent Method”);
}
}
class child extends Parent
{
void display()
{
super.display();
System.out.println(“child method”);
}
}
class override
{
public static void main(String args[])
{
child obj=new child();
obj.display();
}
}
Output:
Child method.
Explaination of above program:
1.Whatever methods are there in parent class it can be by default get to child by inheritance
method.
2.If the child is not satisfied with the methods implementation available in parent class,it may
allow to re-define according to its requirement which is called overriding(child class) and
parent class method is overridden method.
3.If we create obj for child class then only child method will be displayed.
4. If we create obj for parent class then parent method will be displayed.
5.super keyword is used to access the method of parent class in child class if both are sharing
same method name.
6.This is called runtime polymorphism.
7.This is called dynamic binding.
8.Or else instead of using super keyword we can create obj for both parent and child class
like
child obj=new child();
obj.display();
Parent obj1=new Parent();
Obj1.display();
}
Interfaces in Java

1. Interface is just like a class which contain only abstract method (so we cannot create obj for it since it
has abstract method).

2.To achieve interface java provides a keyword called implements.

3. Interface methods are by default public and abstract.

4. Interface variables are by default public, static and final.

5. Interface method must be overridden inside Implementing classes.

6. Iterface main intention is to achieve multiple inheritance.

// PROGRAM ON INTERFACE

Interface A

Void Adisplay ( );//abstract method…we need not write abstract keyword for interface,since interface
contains abstract methods

Void Ashow ( );//these are abstract methods since it has no definition(body) only declaration.

Interface B

Void Bdisplay ( );

Void Bshow ( );

Class AB implements A,B //Advantage of interface is we can inherit from two base clases but it is not
possible to inherit two base classes in inheritance

Public void Adisplay ( )

System.out.println(“A display”);

Public void Ashow ( )

System.out.println(“A show “);

}
Public void Bdisplay ( )

System.out.println(“B display “);

Public void Bshow ( )

System.out.println(“B show “);

Class interface AB

Public static void main(string args[ ]);

AB obj =new AB( );

Obj.Adisplay ( );

Obj.Ashow( );

Obj.Bdisplay( );

Obj.Bshow( );

o/p A display

A show

B display

B show

 Syntax:

interface {
// declare constant fields
// declare methods that abstract
// by default.
}
Implementation: To implement an interface we use the keyword implements
Comparable and comparator
Comparable comparator
1.It is meant for default natural 1.meant for customised sorting order
Sorting order
2.It is present in java.lang package 2.It is present in java.util package

3.It contains only one method 3.Two methods


CompareTo( ) compare( )
4.All wrapper class and string class equals( )
Implements comparable interface 4.The only implemented class of
Comparator are
1) Collator
2)Rule based collator
These are used in graphic based
Creating and Defining Packages:
1.package in java is a mechanism to encapsulate a group of classes,sub packages and
interfaces.
2.package can be considered as data encapsulation or data hiding.
3.as we need to do is put related classes into packages . after that we can simply write an
import class from existing package and use it in our program
4.A package is a container of a group of related classes where some of the classes are
accessible are exposed and other are kept for internal purpose
Example program on package
Package Robo
Public class one
{
Public void chitti( )
{
System.out.println( “Hai”);
}
}
Import Robo.*;
Class sana
{
Public static void main(string args[ ])
{
One obj=new one( );
Obj.chitti( );
}
}
Save it sana.java

Inner Classes In Java

Inner class:

It is a class which is defined within another class or interface are known as inner class or nested class.

//syntax

class outer

_____________;

_____________;
class Inner

_______________;

_______________;

Non-static inner class:

The inner class declared without static keyword is known as Non-static inner class.

Non-static inner class can be declared with Non-static member.

If it is static inner class we can declare with static member.

Types of Non Static Inner classes:

 Member Inner class

 Local inner class

 Anonymous Inner Class

Member Inner class:

It is created inside a class but outside a method.

Example program:

package pack1;

public class OuterExample

int a=67;private int b=80;static int c=12;//Member inner class

class InnerExample//This inner classcan access all members of outer classes like int,private,static.

public void doSum()

System.out.println("Sum is "+(a+b+C));

}
}

public static void main(String[] args)

//Outer object (To create inner class object first we need outer class object)

OuterExample Outer=new OuterExample();

//Inner object

OuterExample.InnerExample ob=Outer.new InnerExample();

Ob.doSum();

Local Inner class:

A class created within a method is known as local inner class.

EXAMPLE PROGRAM ON LOCAL INNER CLASS:

Class Outer

Void main()

class Inner

System.out .println(“Inner class”);

Anonymous Inner Class


An inner class declared without a class name is known as an anonymous inner class.
It is the class created for extending class or implementing interface.
The syntax of an anonymous inner class is as follows.
Syntax
AnonymousInner inner = new AnonymousInner() {
public void my_method() {
........
........
}
};

Example

Abstract class AnonymousInner{


Public abstract void myMethod();
{
Public class Outer_class{
Public static void main(String args[])
{
AnonymousInner inner =newAnonymousInner();
{
Public void myMethod()
{
System.out.println("This is an example of anonymous inner class");
}
};
inner.mymethod();
}
}
Output
This is an example of anonymous inner class

If you compile and execute the above program, you will get the following result.
If you compile and execute the above program, it gives you the following result.

Static inner class:


1) We have to declare static method in inner class.

2) To access inner class members we have to create object for Inner class.

3) with the help of object we can access static inner class.


4) A static inner class can not access the interface variables and methods of outer class.

Program on Static inner class:

class Outer

static class Inner

void display()

System.out.println("static class");

public static void main(String[] args)

Outer.inner obj=new Outer.inner();

obj.display();

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy