Array, Classes and Objects
Array, Classes and Objects
Array in java
Output: 123
245
445
• Difference Between Length and Length() in
Java
• 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.