Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 31

Array ,classes and objects

Array in java

• Array is a collection of similar type of data.

• It is fixed in size means that you can't increase the


size of array at run time.

• It is a collection of homogeneous data elements. It


store the value on the basis of the index value.
• Advantage of Array
• One variable can store multiple value: The main
advantage of the array is we can represent multiple value
under the same name.
• Code Optimization: No, need to declare a lot of variable
of same type data, We can retrieve and sort data easily.
• Random access: We can retrieve any data from array
with the help of the index value.
• Disadvantage of Array
• The main limitation of the array is Size Limit when once
we declare array there is no chance to increase and
decrease the size of an array according to our
requirement.
• Types of Array in java
• There are two types of array.
• Single Dimensional Array
• Multidimensional Array
• Single Dimensional Array in java
• Syntax to Declare an Array in java
• dataType[] arr; (or)  
• dataType []arr; (or)  
• dataType arr[];  
• Instantiation of an Array in java
• arrayRefVar = new datatype[size];  
class Testarray{  
public static void main(String args[]){  
  
int a[]=new int[5]; //declaration   
a[0]=10; //initialization  
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]);  
  
}}  
Output: 10 20 70 40 50
class Testarray1{  
public static void main(String args[]){  
  
int a[]={33,3,4,5}; //declaration and initialization  
  
//printing array  
for(int i=0;i<a.length;i++)//length is the property of array  
System.out.println(a[i]);  
  
}}  
Output: 33 3 4 5
• Multidimensional array in java
• In such case, data is stored in row and column based
index (also known as matrix form).
• Syntax to Declare Multidimensional Array in java
• dataType[][] arrayRefVar; (or)  
• dataType [][]arrayRefVar; (or)  
• dataType arrayRefVar[][]; (or)  
• dataType []arrayRefVar[];   
• Example to instantiate 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;  
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
• Difference Between Length and Length() in
Java

• length: It is a final variable and only applicable


for array. It represent size of array.

• Example
• int[] a=new int[10];
System.out.println(a.length); // 10
System.out.println(a.length()); // Compile
time error
• length(): It is the final method applicable only for
String objects. It represents the number of
characters present in the String.
• Example
• String s="Java";
• System.out.println(s.length()); // 4
System.out.println(s.length); // Compile time
error
• Defining classes and Method
• a class is a user-defined data type and provides a
template for an object.
• Ones the class type has been defined ,we can create
variables of that type using declaration that similar to
the basic type declaration.
• Syntax: class classname
• { [variable declaration;]
• [method declaration];
• }
• Classname is any valid java identifier.
• Adding Methods :
• We add method because they are necessary for manipulating
the data contained in the class.
• Methods are declared inside the body of the class.
• Syntax : rettype methodname(params)
• { method body;}
• The rettype specifies the type of value the method would
return. this could be any basic type or any class type.
• The methodname is any valid identifier.
• The params is always enclosed in parenthesis. This
comma-separeted list contains variable name and types of
all the value we want to give to the method as input.
• The body describes the operation to be performed on the
data.
Class complex
{ double x,y;
void setdata(double a, double b)
{
x=a;
y= b;
}
void putdata()
{
System.out.println(“x=“+x+”y=“+y);
}
Double getmagnitude()
{
Return math.sqrt(x*x+y*y);
}
}
• Creating object :
• An object in java is a block of memory that contains
space to store all the instance variables.
• Object in java are created using the new operator. the new
operator creates an object of the specified class and
returns a reference to that object.
• Eg. Complex c1; //declare
• c1 = new complex(); //instantiate
• The first statement declares a variable to hold the object
reference and the second one actually assigns the object
reference to the variable.

• Complex c1 = new complex();


• The method complex() is the default constructor of the
class. We can create any number of objects of complex.
• Accessing class members
• to access the instance variable and the methods outside
the class we must use the concerned object and the dot
operator .
• Syntax : objectname.variable_name;
• objectname.method_name(params);
• Here object_name is the name of object ,
variable_name is the name of instance variable inside
the object ,method_name is the method that we wish to
call and params is comma separated list .
Eg. C1.x = 10; c1.y = 20;
C2.x = 30; c2.y =40;

Eg. Complex c1 = new complex();


c1.setdata(10,20);
• Java static variable
• If you declare any variable as static, it is known static
variable.
• The static variable can be used to refer the common
property of all objects (that is not unique for each
object) e.g. company name of employees,college
name of students etc.
• The static variable gets memory only once in class
area at the time of class loading.
• Advantage of static variable
• It makes your program memory efficient (i.e it saves
memory).
• Understanding problem without static variable
class Student{  
•      int rollno;  
•      String name;  
•      String college="ITS";  
• }  
• Suppose there are 500 students in my college, now all
instance data members will get memory each time when
object is created.
• All student have its unique rollno and name so instance
data member is good.
• Here, college refers to the common property of all
objects.If we make it static,this field will get memory only
once.
• //Program of static variable  
•   class Student
• {  
•    int rollno;  
•    String name;  
•    static String college ="ITS";  
•      
•    Student(int r,String n)
• {  
•    rollno = r;  
•    name = n;  
•    }  
•  void display ()
• {System.out.println(rollno+" "+name+" "+college);}  
•   
•  public static void main(String args[]){  
•  Student s1 = new Student(111,"Karan");  
•  Student  s2 = new Student(222,"Aryan");  
•    
•  s1.display();  
•  s2.display();  
•  }  
• }  
• Output:
• 111 Karan ITS
• 222 Aryan ITS
• Program of counter without static variable
• class Counter{  
• int count=0; //will get memory when instance is created  
•   Counter(){  
• count++;  
• System.out.println(count);  
• }  
 public static void main(String args[]){  
•   Counter c1=new Counter();  
• Counter c2=new Counter();  
• Counter c3=new Counter();  
•   }  
• }  Output:
• 1
• 1
• 1
• class Counter2{  
• static int count=0;//will get memory only once and retain its value  
•   
• Counter2(){  
• count++;  
• System.out.println(count);  
• }  
•   
• public static void main(String args[]){  
•   
• Counter2 c1=new Counter2();  s
• Counter2 c2=new Counter2();  
• Counter2 c3=new Counter2();  
•   
•  }  
• }  
Output:
123
• static method:-
• It is a method which belongs to the class and not to
the object(instance).
• A static method can access only static data. It can
not access non-static data (instance variables).
• A static method can call only other static
methods and can not call a non-static method from it.
• A static method can be accessed directly by the class
name and doesn’t need any object.
• Syntax : <class-name>.<method-name>
• A static method cannot refer to “this” or “super”
keywords in anyway.
• class Student{  
•      int rollno;  
•      String name;  
•      static String college = "ITS";  
•        
•      static void change(){  
•      college = "BBDIT";  
•      }  
•     Student(int r, String n){  
•      rollno = r;  
•      name = n;  
•      }  
•   
•      void display ()
• {
• System.out.println(rollno+" "+name+" "+college);
• }  
•   
•    
•  public static void main(String args[]){  
•     Student.change();  
•     Student s1 = new Student9 (111,"Karan");  
•     Student s2 = new Student9 (222,"Aryan");  
•     Student s3 = new Student9 (333,"Sonoo");  
•     s1.display();  
•     s2.display();  
•     s3.display();  
•     }  
• }  
Output:111 Karan BBDIT
222 Aryan BBDIT
333 Sonoo BBDIT
• //Program to get cube of a given number by static method  
•   
• class Calculate{  
•   static int cube(int x){  
•   return x*x*x;  
•   }  
•   
•   public static void main(String args[]){  
•   int result=Calculate.cube(5);  
•   System.out.println(result);  
•   }  
• }  
• Output:125
• The static method can not use non static data
member or call non-static method directly.
• class A{  
•  int a=40;//non static  
•    
•  public static void main(String args[]){  
•   System.out.println(a);  
•  }  
• }        
Output:Compile Time Error
• These method always preceded by static keyword
Example:
• static void fun2()
• { ...... ...... }
• Memory is allocated only once at the time of class
loading.
• These are common to every object so that it is also
known as member method or class method.
• These property always access with class reference
Syntax:
• className.methodname();
• If any method wants to be execute only once in the
program that can be declare as static 
• class A
• { void fun1()
• {
• System.out.println("Hello I am Non-Static");
• }
• static void fun2()
• { System.out.println("Hello I am Static");
• }
• }
• class Person
• {
• public static void main(String args[])
• { A oa=new A();
• oa.fun1(); // non static method
• A.fun2(); // static method
• }}
• Output
• Hello I am Non-Static
• Hello I am Static

You might also like