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

JAVA

The document provides an overview of inheritance in Java, detailing its types such as single, multiple, hierarchical, multilevel, and hybrid inheritance. It explains the concepts of method overriding, the use of 'this' and 'super' keywords, abstract classes and methods, and interfaces, including their properties and differences from classes. Additionally, it includes example programs demonstrating these concepts and string manipulation methods in Java.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views

JAVA

The document provides an overview of inheritance in Java, detailing its types such as single, multiple, hierarchical, multilevel, and hybrid inheritance. It explains the concepts of method overriding, the use of 'this' and 'super' keywords, abstract classes and methods, and interfaces, including their properties and differences from classes. Additionally, it includes example programs demonstrating these concepts and string manipulation methods in Java.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 42

INHERITANCE IN JAVA

The mechanism of deriving a new class from a old class is called


inheritance.

NOTE:

❖ Old class is also called as base class or super class or parent class
❖ New class is also called as derived class or sub class or child class
❖ Inheritance allows subclasses to inherit all the variables and methods from
their super class

Types of inheritance in java

1) Single inheritance:
it contains only one super class
2) Multiple inheritance:
it contains more than one super class
3) Hierarchical inheritance:
it contains one super class many sub classes
4) Multilevel inheritance:
derived from a derived class
5) Hybrid inheritance:
combination of both multilevel and hierarchical inheritance.

Page | 1
NOTE:
1) Java supports the concept of reusability.java classes can be used in many
ways .this is basically done by creating new classes, reusing the properties
of the existing class.
2) Java does not support multiple inheritance.

Defining a sub class

class subclassname extends superclassname


{
variable declaration;
method declaration;
}

NOTE:
1) The keyword extends specifies the properties of superclassname are
extended to subclassname.
2) The subclass contains its own variables and methods as well as the
properties(variables,methods) that are inherited from superclass.

subclass constructor
1) subclass constructor is used to construct the variables of both superclass
and subclass.
2) subclass constructor uses super keyword to invoke the constructor
method of superclass
3) the super keyword is used under following conditions
a) super keyword is used within the subclass constructor
b) to call the superclass constructor super keyword must appear as the
first statement within the subclass constructor
c) the parameters in super keyword must match the order and type of
the instance variables declared in superclass.

Page | 2
write a program to demonstrate single inheritance

class A
{
public void methodA()
{
System.out.println("Base class method");
}
}

class B extends A
{
public void methodB()
{
System.out.println("Child class method");
}
}
class Test
{
public static void main(String args[])
{
B obj = new B();
obj.methodA(); //calling super class method
obj.methodB(); //calling sub class method
}
}

OUTPUT:
Base class method
Child class method

Page | 3
write a program to demonstrate Multi level inheritance.

class Firstclass
{
void Firstmethod()
{
System.out.println("Message from Firstclass");
}
}

class Secondclass extends Firstclass


{
void Secondmethod()
{
System.out.println("Message from Secondclass");
}
}

class Thirdclass extends Secondclass


{
void Thirdmethod()
{
System.out.println("Message from Thirdclass");
}
}

class Fourthclass extends Thirdclass


{
void Fourthmethod()
{
System.out.println("Message from Fourthclass");
}
}

Page | 4
class Test

{
public static void main(String args[])

{
Fourthclass fc = new Fourthclass();
//creating object for Fourthclass

fc.Firstmethod();
fc.Secondmethod();
fc.Thirdmethod();
fc.Fourthmethod();

System.out.println("All methods are Displayed");


}
}

OUTPUT:

Message from Firstclass


Message from Secondclass
Message from Thirdclass
Message from Fourthclass
All methods are Displayed

METHOD OVERRIDING

when a method in subclass has the same name and type signature as a
method in its superclass then the method in its subclass is said to override the
method in superclass. This is called method overriding.

when a overridden method is called from a subclass ,it always refer to the
version of that method defined by the subclass.the version of the method
defined by superclass will be hidden.

Page | 5
write a program to demonstrate method overriding (OR) write a
program using SUPER keyword (OR) write a program using THIS
keyword

class Super
{
int x;
Super(int x)
{
this.x=x;
}

void display()
{
System.out.println("Super x=" +x);
}
}
class Sub extends Super
{
int y;
Sub(int x,int y)
{
super(x);
this.y=y;
}

void display()
{
System.out.println("Super x=" +x);
System.out.println("Sub y =" +y);
}
}

Page | 6
class OverrideTest
{
public static void main(String args[])
{
Sub s1=new Sub(100,200);
s1.display();
}
}

OUTPUT:
Super x=100
Sub y=200

Differences between method overloading and method overriding

No. Method Overloading Method Overriding

1) Method overloading is used to increase the Method overriding is used to provide


readability of the program. the specific implementation of the method
that is already provided by its super class.

2) Method overloading is performed within class. Method overriding occurs in two classes
that have IS-A (inheritance) relationship.

3) In case of method overloading, parameter must In case of method overriding, parameter


be different. must be same.

4) Method overloading is the example of compile Method overriding is the example of


time polymorphism. run time polymorphism.

5) In java, method overloading can't be performed Return type must be same or


by changing return type of the method covariant in method overriding.
only. Return type can be same or different in
method overloading. But you must have to
change the parameter.

Page | 7
this keyword

1. this keyword is always a reference to the object on which the method is


invoked.

2. this keyword can be used inside any method to refer the current object.

3. this keyword reference is used to refer both instance variables and


methods of current object.

write a program to demonstrate this keyword.

class Student
{
int id;
String name;
Student(int id,String name)
{
this.id = id;
this.name = name;
}
void display()
{
System.out.println(id+" "+name);
}
}
class Test
{
public static void main(String args[])
{
Student s1 = new Student(1,"Karan");
Student s2 = new Student(2,"Aryan");
s1.display();
s2.display();
}
}

Page | 8
OUTPUT:
1 Karan
2 Aryan

write a program to demonstrate super keyword.


class A
{
A (String str)
{
System.out.println("Base Class Constructor " + str);
}
}

class B extends A
{
B(String str)
{
super(str);
System.out.println("Sub Class Constructor " + str);
}
}

class Mainclass
{
public static void main(String args[])
{
B obj = new B ("called");
}
}
OUTPUT:
Base Class Constructor called
Sub Class Constructor called

Page | 9
ABSTRACT CLASSES AND METHODS
Abstract class:
1. An abstract class is a class that is declared abstract.
2. Abstract classes may or may not include abstract methods.
3. Abstract classes cannot be instantiated, but they can be subclassed.

syntax:

public abstract classname


{
//field declaration;
// abstract method declaration;
// non-abstract method declaration;
}

Abstract Method:

1. The methods which have only declaration and no method body in the class
is called as abstract method.
2. The abstract method is declared by using the keyword abstract.
3. The abstract methods should be defined in subclass

Ex: abstract void area();

Page | 10
write a program to demonstrate Abstract classes and Abstract methods
(or) program to demonstrate Abstract keyword.

abstract class Shape


{
abstract void draw();
}
class Rectangle extends Shape
{
void draw()
{
System.out.println("Drawing Rectangle");
}
}
class Triangle extends Shape
{
void draw()
{
System.out.println("Drawing Triangle");
}
}
class AbstractDemo
{
public static void main(String args[])
{
Shape s1=new Rectangle();
s1.draw();
Shape s2=new Triangle();
s2.draw();
}
}
OUTPUT:
Drawing Rectangle
Drawing Triangle

Page | 11
final classes,methods and final variables

final class: it is a class that cannot be subclassed


final method: it is a method that cannot be overridden by any subclasses.
final variable: it is a variable that cannot change its value.

write a program to demonstrate final variable and final method (or)


write a program using final keyword.

A)Finalvariable

public class Finalvariable


{
public static void main(String args[])

{
final int hoursinday=24;
System.out.println("Hours in 5 days="+hoursinday * 5);
}
}

OUTPUT:

Hours in 5 days=120

Page | 12
B)Finalmethod

class A
{
final void math() //final method
{
System.out.println("this is final method");
}
}

class B extends A
{
void math()
{
System.out.println("illegal");
}
}
class Finalmethod
{
public static void main(String args[])
{
B obj=new B();
obj.math();
}
}

OUTPUT:

D:\mpcs>javac Finalmethod.java
Finalmethod.java:12: math() in B cannot override math() in A; overridden
method
is final
void math()
^
1 error

Page | 13
INTERFACES IN JAVA

❖ java does not support multiple inheritance.that is java is having more


than one class
❖ java provides an alternate approach known as interfaces to support the
concept of multiple inheritance
❖ java class cannot be a sub class of more than one superclass,but it can
implement more than one interface.

Definition of interface
❖ interface is a kind of class which contain variables and methods
❖ difference is that interfaces define only abstract methods and final
keywords
❖ interfaces do not specify any code to implement these methods and
datafields contains only constants
❖ so it is the responsibility of class that implements an interface to define
the code by implementation of these methods

General form of interface


interface interfacename
{
variable declaration;
method declaration;
}

Properties of interface
❖ all the methods of interface are static and abstract by default
❖ we cannot create an object in interface
❖ an interface can extend another interface.
❖ an interface cannot implement another interface
❖ we can write a class inside an interface
❖ interface may have variables which are public,static,final by default
❖ all the abstract methods of interface should be implemented in its
implementation class

Page | 14
Difference between class and interface

class interface
we can create an object in class we cannot create object in interface
class is declared by keyword class interface is declared by keyword
interface
class has no multiple inheritance interface support multiple inheritance
class contains all types of variables interface contains only final variables
class interface contains only abstract
{ methods and final fields
variable declaration;
method declaration;
}

Extending Interfaces

❖ Like classes interfaces can also be extended that is an interface can be


subinterfaced to other interface
❖ The new sub interface will inherit all the members of the super interface in
the manner similar to sub classes. this can be achieved using the keyword
extends as shown below

interface name2 extends name1


{
body of name2;
}
NOTE:
we can extends more than one interface that are seperated by comma(,)

interface name3 extends name2,name1


{
body of name3;
}

Page | 15
Implementing Interfaces

❖ interfaces are used as superclasses whose properties are inherited by


classes.
❖ it is necessary to create a class that inherits the given interface.
❖ this can be done as follows

class classname implements interfacename


{
body of classname;
}

Note: Here the class classname implements the interface interfacename.


we can implements more than one interface that are seperated by comma(,)

class classname extends superclassname implements interface1,interface2......


{
body of classname;
}

Note: the above code shows that class can extend another class implementing
interfaces.

Page | 16
Understanding relationship between classes and interfaces

As shown in the figure given below, a class extends another class, an interface
extends another interface but a class implements an interface.

write a java program for implementing interfaces.

interface Printable
{
void print();
}

interface Showable extends Printable


{
void show();
}

class InterfaceTest implements Showable

{
public void print()
{
System.out.println("Hello");
}

public void show()


{
System.out.println("Welcome");
}
}

Page | 17
class Test
{
public static void main(String args[])
{
InterfaceTest obj = new InterfaceTest();
obj.print();
obj.show();
}
}

OUTPUT:
Hello
Welcome

write a program for extending interfaces.


ABOVE PROGRAM (IMPLEMENTING INTERFACES)

Multiple inheritance in Java by interface

If a class implements multiple interfaces, or an interface extends multiple


interfaces i.e. known as multiple inheritance.

Page | 18
Write a program to demonstrate multiple inheritance.

interface Printable
{
void print();
}

interface Showable
{
void show();
}
class InterfaceTest implements Printable,Showable
{
public void print()
{
System.out.println("Hello");
}
public void show()
{
System.out.println("Welcome");
}
}
class Test
{
public static void main(String args[])
{
InterfaceTest obj = new InterfaceTest();
obj.print();
obj.show();
}
}
OUTPUT:
Hello
Welcome

Page | 19
STRING METHODS IN JAVA
(STRING HANDLING (OR) STRING MANIPULATION FUNCTIONS)

Creating a String

There are two ways to create String object:


❖ By string literal
❖ By new keyword

❖ Java String Literals

Java has a shorter way of creating a new String:


String myString = "Hello World";

Instead of passing the text "Hello World" as a parameter to the String


constructor, you can just write the text itself inside the double quote characters.
This is called a String literal.

❖ By new keyword

Strings in Java are objects. Therefore you need to use the new operator to
create a new Java String object. Here is a Java String instantiation (creation)

String myString = new String("Hello World");

The text inside the quotes is the text the String object will contain.

Page | 20
Methods in String class

1. Java String toUpperCase() and toLowerCase() method

The java string toUpperCase() method converts this string into uppercase letter and string
toLowerCase() method into lowercase letter.

String s="Sachin";

System.out.println(s.toUpperCase()); //SACHIN

System.out.println(s.toLowerCase()); //sachin

System.out.println(s); //Sachin(no change in original)

2. trim() method

The string trim() method eliminates white spaces before and after string.

String s=" Sachin ";

System.out.println(s);// Sachin

System.out.println(s.trim());//Sachin

3. startsWith() and endsWith() method

startsWith() method checks if this string starts with given prefix. It returns true if this string starts with given
prefix else returns false.

endsWith() method checks if this string ends with given suffix. It returns true if this string ends with given
suffix else returns false.

String s="Sachin";

System.out.println(s.startsWith("Sa")); //true

System.out.println(s.endsWith("n")); //true

Page | 21
4. charAt() method

The string charAt() method returns a character at specified index.

String s="Sachin";

System.out.println(s.charAt(0));//S

System.out.println(s.charAt(3));//h

5. length() method

The string length() method returns length of the string.

String s="Sachin";

System.out.println(s.length()); //6

6. replace() method

The string replace() method replaces all occurrence of first sequence of character with second
sequence of character.

String s1="Java is a programming language. Java is a platform. Java is an Island.";

String s2=s1.replace("Java","Kava"); //replaces all occurrences of "Java" to "Kava"

System.out.println(s2);

7. equals() method

This method compares the two given strings based on the content of the string. If any
character is not matched, it returns false. If all characters are matched, it returns true

String s1="java";
String s2="java";
String s3="JAVA";
System.out.println(s1.equals(s2)); //true because content and case is same
System.out.println(s1.equals(s3)); //false because case is not same

Page | 22
8. equalsIgnoreCase() method

This method determines the equality of two Strings, ignoring their case (upper or lower case
doesn't matters with this function ).

String str = "java";

System.out.println(str.equalsIgnoreCase("JAVA"));

9. substring() method:

substring() method returns a part of the string. substring() method has two forms,

public String substring(int begin);

public String substring(int begin, int end);

The first argument represents the starting point of the subtring. If the substring() method is called
with only one argument, the subtring returned, will contain characters from specified starting point
to the end of original string.

But, if the call to substring() method has two arguments, the second argument specify the end point
of substring.

String str = "0123456789";

System.out.println(str.substring(4)); // 456789

System.out.println(str.substring(4,7)); // 456

10. concat() method

Concatenation is joining of two or more strings

String str1="Sachin";
str2=str1.concat(" Tendulkar");
System.out.println(str2); //Sachin Tendulkar

Page | 23
Methods in StringBuffer class

Java StringBuffer class is used to create mutable (modifiable) string. The StringBuffer
class in java is same as String class except it is mutable i.e. it can be changed.

What is mutable string

A string that can be modified or changed is known as mutable string.

StringBuffer and StringBuilder classes are used for creating mutable string

different methods of StringBuffer class

1) StringBuffer append() method

The append() method concatenates the given argument with this string.

StringBuffer sb=new StringBuffer("Hello ");

sb.append("Java"); //now original string is changed

System.out.println(sb); //prints Hello Java

2) StringBuffer insert() method

The insert() method inserts the given string with this string at the given position.

StringBuffer sb=new StringBuffer("Hello ");

sb.insert(1,"Java"); //now original string is changed

System.out.println(sb); //prints HJavaello

Page | 24
3) StringBuffer replace() method

The replace() method replaces the given string from the specified beginIndex and
endIndex.

StringBuffer sb=new StringBuffer("Hello");

sb.replace(1,3,"Java");

System.out.println(sb); //prints HJavalo

4) StringBuffer delete() method

The delete() method of StringBuffer class deletes the string from the specified
beginIndex to endIndex.

StringBuffer sb=new StringBuffer("Hello");

sb.delete(1,3);

System.out.println(sb); //prints Hlo

5) StringBuffer reverse() method

The reverse() method of StringBuilder class reverses the current string.

StringBuffer sb=new StringBuffer("Hello");

sb.reverse();

System.out.println(sb); //prints olleH

Page | 25
Java StringBuilder class
Java StringBuilder class is used to create mutable (modifiable) string. The Java
StringBuilder class is same as StringBuffer class except that it is non-
synchronized

different methods of StringBuilder class.

1) StringBuilder append() method

The StringBuilder append() method concatenates the given argument with this string.

StringBuilder sb=new StringBuilder("Hello ");

sb.append("Java");//now original string is changed

System.out.println(sb);//prints Hello Java

2) StringBuilder insert() method

The StringBuilder insert() method inserts the given string with this string at the given
position.

StringBuilder sb=new StringBuilder("Hello ");

sb.insert(1,"Java");//now original string is changed

System.out.println(sb);//prints HJavaello

3) StringBuilder replace() method

The StringBuilder replace() method replaces the given string from the specified
beginIndex and endIndex.

StringBuilder sb=new StringBuilder("Hello");

sb.replace(1,3,"Java");

System.out.println(sb);//prints HJavalo

Page | 26
4) StringBuilder delete() method

The delete() method of StringBuilder class deletes the string from the specified
beginIndex to endIndex.

StringBuilder sb=new StringBuilder("Hello");

sb.delete(1,3);

System.out.println(sb);//prints Hlo

5) StringBuilder reverse() method

The reverse() method of StringBuilder class reverses the current string.

StringBuilder sb=new StringBuilder("Hello");

sb.reverse();

System.out.println(sb);//prints olleH

Difference between StringBuffer and StringBuilder

StringBuffer is synchronized i.e. thread safe.

It means two threads can't call the methods of StringBuffer simultaneously.

StringBuilder is non-synchronized i.e. not thread safe.

It means two threads can call the methods of StringBuilder simultaneously.

Difference between String and StringBuffer

String class is immutable (Immutable simply means unmodifiable or unchangeable)

StringBuffer class is mutable (mutable simply means modifiable or changeable)

Page | 27
Java Array
An array is a very common type of data structure where in all elements
must be of the same data type.

Array in java is index based, first element of the array is stored at 0 index.

Advantage of Java Array

❖ It makes the code optimized, we can retrieve or sort the data easily.
❖ We can get any data located at any index position.

Disadvantage of Java Array

❖ Once defined the size of an array is fixed and cannot increase to


accommodate more elements.

Array Declaration

Syntax :

datatype[ ] identifier;

or

datatype identifier[ ];

Both are valid syntax for array declaration. But the former is more readable.

Example :

int[ ] arr;

char[ ] arr;

short[ ] arr;

long[ ] arr;

int[ ][ ] arr; // two dimensional array.

Page | 28
Initialization of Array

new operator is used to initialize an array.

Example :

int[ ] arr = new int[10];

//this creates an empty array named arr of integer type whose size is 10.

(or)

int[ ] arr = {10,20,30,40,50};

//this creates an array named arr whose elements are given.

Accessing array element

As mention ealier array index starts from 0. To access nth element of an array.
Syntax

arrayname[n-1];

Example : To access 4th element of a given array

int[ ] arr = {10,20,30,40,50};

System.out.println("Element at 4th place" + arr[3]);

The above code will print the 4th element of array arr on console.

Page | 29
Types of Array in java

There are two types of array.

❖ Single Dimensional Array


❖ Multidimensional Array

Single Dimensional Array in java

Method-1

class Testarray
{
public static void main(String args[])
{
int a[]=new int[5];
a[0]=10;
a[1]=20;
a[2]=70;
a[3]=40;
a[4]=50;
//printing array
for(int i=0;i<a.length;i++) //length is the property of array
System.out.println(a[i]);
}
}

Method-2

class Testarray1
{
public static void main(String args[])
{
int a[]={10,20,30,40,50};

//printing array
for(int i=0;i<a.length;i++) //length is the property of array
System.out.println(a[i]);

}
}

Page | 30
Multi-Dimensional Array in java

Syntax to Declare Multidimensional Array in java


dataType[][] arrayRefVar

Example to declare Multidimensional Array in java

int[][] arr=new int[3][3]; //3 row and 3 column

Example to initialize Multidimensional Array in java

arr[0][0]=1;

arr[0][1]=2;

arr[0][2]=3;

arr[1][0]=4;

arr[1][1]=5;

arr[1][2]=6;

arr[2][0]=7;

arr[2][1]=8;

arr[2][2]=9;

Page | 31
Example to print the 2 Dimensional array.

class Testarray3

public static void main(String args[])

//declaring and initializing 2D array

int arr[][]={{1,2,3},{2,4,5},{4,4,5}};

//printing 2D array

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

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

System.out.print(arr[i][j]+" ");

System.out.println();

Output:

123

245

445

Page | 32
Addition of 2 matrices in java (3x3 matrices)

class Testarray5

public static void main(String args[])

//creating two matrices

int a[][]={{1,3,4},{3,4,5},{4,5,6}};

int b[][]={{1,3,4},{3,4,5},{5,6,7}};

//creating another matrix to store the sum of two matrices

int c[][]=new int[3][3];

//adding and printing addition of 2 matrices

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

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

c[i][j]=a[i][j]+b[i][j];

System.out.print(c[i][j]+" ");

System.out.println();//new line

Page | 33
MATRIX ADDITION BY PASSING VALUES AT RUNTIME

/*There are various ways to read input from the keyboard, the
java.util.Scanner class is one of them.

The Java Scanner class breaks the input into tokens */

import java.util.Scanner;
public class Add1
{
public static void main(String args[])
{
int i, j;
int a[][] = new int[2][2];
int b[][] = new int[2][2];
int c[][] = new int[2][2];
Scanner scan = new Scanner(System.in);
System.out.println("Enter first Matrix Elements : ");
for(i=0; i<2; i++)
{
for(j=0; j<2; j++)
{
a[i][j] = scan.nextInt();
//Returns the next token as an int. If the next token is not an
integer, InputMismatchException is thrown.
}
}

Page | 34
System.out.println("Enter second Matrix Elements : ");
for(i=0; i<2; i++)
{
for(j=0; j<2; j++)
{
b[i][j] = scan.nextInt();
}
}
System.out.println("Adding both Matrix to form the Third Matrix...\n");
for(i=0; i<2; i++)
{
for(j=0; j<2; j++)
{
c[i][j] = a[i][j] + b[i][j];
}
}
System.out.println("The Two Matrix Added Successfully..!!\n");
System.out.println("The New Matrix will be :\n");
for(i=0; i<2; i++)
{
for(j=0; j<2; j++)
{
System.out.print(c[i][j]+ " ");
}
System.out.println();
}
}
}

Page | 35
MATRIX MULTIPLICATION

import java.util.Scanner;
public class Multiplication
{
public static void main(String args[])
{

int r1, c1, r2, c2, sum = 0, a, b, c;


Scanner in = new Scanner(System.in);

System.out.print("Enter Number of Rows and Columns of First Matrix : ");


r1 = in.nextInt();
c1 = in.nextInt();

int first[][] = new int[r1][c1];

System.out.print("Enter First Matrix Elements : ");

for(a=0 ; a<r1; a++)


{
for(b=0; b<c1; b++)
{
first[a][b] = in.nextInt();
}
}

Page | 36
System.out.print("Enter Number of Rows and Columns of Second Matrix : ");
r2 = in.nextInt();
c2 = in.nextInt();
if ( c1 != r1 )
{
System.out.print("Matrix of the entered order can't be Multiplied..!!");
}
else
{
int second[][] = new int[r2][c2];
int multiply[][] = new int[r1][c2];
System.out.print("Enter Second Matrix Elements :\n");
for(a=0; a<r2; a++)
{
for(b=0; b<c2; b++)
{
second[a][b] = in.nextInt();
}
}
System.out.print("Multiplying both Matrix...\n");
for(a=0; a<r1; a++)
{
for(b=0; b<c2; b++)
{
for(c=0; c<r2; c++)
{
sum = sum + first[a][c]*second[c][b];
}
multiply[a][b] = sum;
sum = 0;
}
}

Page | 37
System.out.print("Multiplication Successfully performed..!!\n");
System.out.print("Now the Matrix Multiplication Result is :\n");

for(a=0; a<r1; a++)


{
for(b=0; b<c2; b++)
{
System.out.print(multiply[a][b] + "\t");
}
System.out.print("\n");
}
}

}
}

Page | 38
TRANSPOSE OF A MATRIX
import java.util.Scanner;

public class Transpose

public static void main(String args[])

int i, j;

int a[][] = new int[3][3];

int b[][] = new int[3][3];

Scanner scan = new Scanner(System.in);

System.out.print("Enter 3*3 Array Elements : ");

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


{
for(j=0; j<3; j++)
{
a[i][j] = scan.nextInt();
}
}

System.out.print("Transposing Array...\n");

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


{
for(j=0; j<3; j++)
{
b[i][j] = a[j][i];
}
}

Page | 39
System.out.print("Transpose of the Matrix is :\n");

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


{
for(j=0; j<3; j++)
{
System.out.print(b[i][j]+ " ");
}
System.out.println();
}
}
}
Wrapper class in Java

Wrapper class in java provides the mechanism to convert primitive into


object and object into primitive.

autoboxing and unboxing feature converts primitive into object and


object into primitive automatically.

The automatic conversion of primitive into object is known as autoboxing


The automatic conversion of object into primitive is known as unboxing.

The list of wrapper classes


Primitive Type Wrapper class
boolean Boolean
char Character
byte Byte
short Short
int Integer
long Long
float Float
double Double

Page | 40
Wrapper class Example: Primitive to Wrapper

public class WrapperExample1


{
public static void main(String args[])
{
int a=20;
Integer i=Integer.valueOf(a);
//converting int into Integer
Integer j=a;
//autoboxing, now compiler will write Integer.valueOf(a) internally
System.out.println(a+" "+i+" "+j);
}
}
Output:20 20 20

Wrapper class Example: Wrapper to Primitive

public class WrapperExample2


{
public static void main(String args[])
{
Integer a=new Integer(3);
int i=a.intValue(); //converting Integer to int
int j=a;
//unboxing, now compiler will write a.intValue() internally

System.out.println(a+" "+i+" "+j);


}
}
Output:3 3 3

Page | 41
Page | 42

You might also like