0% found this document useful (0 votes)
23 views15 pages

JAVA COnstructos Conditons Arrays

The document discusses constructors in Java. Constructors initialize objects and are similar to methods but have no return type. Classes have default constructors if none are defined. The document also discusses no-argument and parameterized constructors, providing examples of each.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
23 views15 pages

JAVA COnstructos Conditons Arrays

The document discusses constructors in Java. Constructors initialize objects and are similar to methods but have no return type. Classes have default constructors if none are defined. The document also discusses no-argument and parameterized constructors, providing examples of each.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 15

JAVA Constructors

A constructor initializes an object when it is created. It has the same name as its class and
is syntactically similar to a method. However, constructors have no explicit return type.
Typically, you will use a constructor to give initial values to the instance variables defined
by the class, or to perform any other start-up procedures required to create a fully formed
object.
All classes have constructors, whether you define one or not, because Java automatically
provides a default constructor that initializes all member variables to zero. However, once
you define your own constructor, the default constructor is no longer used.
Syntax
Following is the syntax of a constructor −
class ClassName {
ClassName() {
}
}
Java allows two types of constructors namely −
• No argument Constructors
• Parameterized Constructors
AD
No argument Constructors
As the name specifies the no argument constructors of Java does not accept any parameters
instead, using these constructors the instance variables of a method will be initialized with
fixed values for all objects.
Example
Public class MyClass {
Int num;
MyClass() {
num = 100;
}
}
You would call constructor to initialize objects as follows
public class ConsDemo {
public static void main(String args[]) {
MyClass t1 = new MyClass();
MyClass t2 = new MyClass();
System.out.println(t1.num + " " + t2.num);
}
}
This would produce the following result
100 100

Task: create a class called `circle` that represents a circle. The class should have the
following features:

1. Private instance variables: `radius` (double) and `pi` (final double, with a value of
3.14159).
2. A no-argument constructor that sets the default value of `radius` to 1.0.
3. A method called `getarea()` that calculates and returns the area of the circle (pi *
radius * radius).
4. A method called `getcircumference()` that calculates and returns the
circumference of the circle (2 * pi * radius).
Public class circle {
private double radius;
private final double pi = 3.14159;

public circle() {
// no-argument constructor
radius = 1.0;
}

public double getarea() {


return pi * radius * radius;
}

public double getcircumference() {


return 2 * pi * radius;
}

public static void main(string[] args) {


circle circle = new circle(); // creating an instance of circle using the no-argument
constructor
system.out.println("radius: " + circle.radius);
system.out.println("area: " + circle.getarea());
system.out.println("circumference: " + circle.getcircumference());
}
}
```

In this example, the `circle` class has a no-argument constructor that sets the default
value of the `radius` field to 1.0. The `getarea()` method calculates the area of the circle
using the formula `pi * radius * radius`, and the `getcircumference()` method calculates
the circumference using the formula `2 * pi * radius`.

In the `main()` method, we create an instance of the `circle` class using the no-argument
constructor and then print the radius, area, and circumference of the circle. Since we
haven't provided any arguments to the constructor, it will use the default value of 1.0 for
the radius.

The output will be:

Radius: 1.0
Area: 3.14159
Circumference: 6.28318
Parameterized Constructors
Most often, you will need a constructor that accepts one or more parameters. Parameters
are added to a constructor in the same way that they are added to a method, just declare
them inside the parentheses after the constructor's name.
Example
Here is a simple example that uses a constructor −
// A simple constructor.
class MyClass {
int x;

// Following is the constructor


MyClass(int i ) {
x = i;
}
}
You would call constructor to initialize objects as follows −
public class ConsDemo {
public static void main(String args[]) {
MyClass t1 = new MyClass( 10 );
MyClass t2 = new MyClass( 20 );
System.out.println(t1.x + " " + t2.x);
}
}
This would produce the following result −
10 20

Task: Create a class called `Rectangle` that represents a rectangle. The class should have the
following features:

1. Private instance variables: `length` (double) and `width` (double).


2. A parameterized constructor that accepts the length and width of the rectangle as arguments and
sets the corresponding instance variables.
3. A method called `getArea()` that calculates and returns the area of the rectangle (length * width).
4. A method called `getPerimeter()` that calculates and returns the perimeter of the rectangle (2 *
(length + width)).
public class Rectangle {
private double length;
private double width;

public Rectangle(double length, double width) {


// Parameterized constructor
this.length = length;
this.width = width;
}

public double getArea() {


return length * width;
}

public double getPerimeter() {


return 2 * (length + width);
}

public static void main(String[] args) {


Rectangle rectangle = new Rectangle(4.5, 3.2); // Creating an instance of
Rectangle using the parameterized constructor
System.out.println("Length: " + rectangle.length);
System.out.println("Width: " + rectangle.width);
System.out.println("Area: " + rectangle.getArea());
System.out.println("Perimeter: " + rectangle.getPerimeter());
}
}

In this example, the `Rectangle` class has a parameterized constructor that accepts
the length and width of the rectangle as arguments. The constructor sets the
corresponding instance variables using the `this` keyword.

The `getArea()` method calculates the area of the rectangle by multiplying the length
and width, and the `getPerimeter()` method calculates the perimeter by adding twice
the length and twice the width.

In the `main()` method, we create an instance of the `Rectangle` class using the
parameterized constructor by passing the length as 4.5 and the width as 3.2. Then,
we print the length, width, area, and perimeter of the rectangle.

The output will be:


Length: 4.5
Width: 3.2
Area: 14.4
Perimeter: 15.4
Loops
There may be a situation when you need to execute a block of code several number of
times. In general, statements are executed sequentially: The first statement in a function is
executed first, followed by the second, and so on.
Programming languages provide various control structures that allow for more complicated
execution paths.
A loop statement allows us to execute a statement or group of statements multiple times
and following is the general form of a loop statement in most of the programming
languages −

Java programming language provides the following types of loop to handle looping
requirements.
Sr.No. Loop & Description

1 while loop
Repeats a statement or group of statements while a given condition is true. It tests
the condition before executing the loop body.

2 for loop
Execute a sequence of statements multiple times and abbreviates the code that
manages the loop variable.

3 do...while loop
Like a while statement, except that it tests the condition at the end of the loop
body.

Loop Control Statements


Loop control statements change execution from its normal sequence. When execution
leaves a scope, all automatic objects that were created in that scope are destroyed.
Java supports the following control statements. Click the following links to check their
detail.

Sr.No. Control Statement & Description

1 break statement
Terminates the loop or switch statement and transfers execution to the statement
immediately following the loop or switch.

2 continue statement
Causes the loop to skip the remainder of its body and immediately retest its
condition prior to reiterating.

AD
Enhanced for loop in Java
As of Java 5, the enhanced for loop was introduced. This is mainly used to traverse
collection of elements including arrays.
Syntax
Following is the syntax of enhanced for loop −
for(declaration : expression) {
// Statements
}
• Declaration − The newly declared block variable, is of a type compatible with the
elements of the array you are accessing. The variable will be available within the for
block and its value would be the same as the current array element.
• Expression − This evaluates to the array you need to loop through. The expression
can be an array variable or method call that returns an array.
Example
public class Test {

public static void main(String args[]) {


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

for(int x : numbers ) {
System.out.print( x );
System.out.print(",");
}
System.out.print("\n");
String [] names = {"James", "Larry", "Tom", "Lacy"};

for( String name : names ) {


System.out.print( name );
System.out.print(",");
}
}
}
This will produce the following result −
Output
10, 20, 30, 40, 50,
James, Larry, Tom, Lacy,
Java Arrays
Java provides a data structure, the array, which stores a fixed-size sequential collection of
elements of the same type. An array is used to store a collection of data, but it is often more
useful to think of an array as a collection of variables of the same type.
Instead of declaring individual variables, such as number0, number1, ..., and number99,
you declare one array variable such as numbers and use numbers[0], numbers[1], and ...,
numbers[99] to represent individual variables.
This tutorial introduces how to declare array variables, create arrays, and process arrays
using indexed variables.
Declaring Array Variables
To use an array in a program, you must declare a variable to reference the array, and you
must specify the type of array the variable can reference. Here is the syntax for declaring
an array variable −
Syntax
dataType[] arrayRefVar; // preferred way.
or
dataType arrayRefVar[]; // works but not preferred way.
Note − The style dataType[] arrayRefVar is preferred. The style dataType
arrayRefVar[] comes from the C/C++ language and was adopted in Java to accommodate
C/C++ programmers.
Example
The following code snippets are examples of this syntax −
double[] myList; // preferred way.
or
double myList[]; // works but not preferred way.
AD
Creating Arrays
You can create an array by using the new operator with the following syntax −
Syntax
arrayRefVar = new dataType[arraySize];
The above statement does two things −
• It creates an array using new dataType[arraySize].
• It assigns the reference of the newly created array to the variable arrayRefVar.
Declaring an array variable, creating an array, and assigning the reference of the array to
the variable can be combined in one statement, as shown below −
dataType[] arrayRefVar = new dataType[arraySize];
Alternatively you can create arrays as follows −
dataType[] arrayRefVar = {value0, value1, ..., valuek};
The array elements are accessed through the index. Array indices are 0-based; that is, they
start from 0 to arrayRefVar.length-1.
Example
Following statement declares an array variable, myList, creates an array of 10 elements of
double type and assigns its reference to myList −
double[] myList = new double[10];
Following picture represents array myList. Here, myList holds ten double values and the
indices are from 0 to 9.

Processing Arrays
When processing array elements, we often use either for loop or foreach loop because all
of the elements in an array are of the same type and the size of the array is known.
Example
Here is a complete example showing how to create, initialize, and process arrays −
public class TestArray {

public static void main(String[] args) {


double[] myList = {1.9, 2.9, 3.4, 3.5};

// Print all the array elements


for (int i = 0; i < myList.length; i++) {
System.out.println(myList[i] + " ");
}

// Summing all elements


double total = 0;
for (int i = 0; i < myList.length; i++) {
total += myList[i];
}
System.out.println("Total is " + total);

// Finding the largest element


double max = myList[0];
for (int i = 1; i < myList.length; i++) {
if (myList[i] > max) max = myList[i];
}
System.out.println("Max is " + max);
}
}
This will produce the following result −
Output
1.9
2.9
3.4
3.5
Total is 11.7
Max is 3.5
A

D
The foreach Loops
JDK 1.5 introduced a new for loop known as foreach loop or enhanced for loop, which
enables you to traverse the complete array sequentially without using an index variable.
Example
The following code displays all the elements in the array myList −
Live Demo

public class TestArray {

public static void main(String[] args) {


double[] myList = {1.9, 2.9, 3.4, 3.5};

// Print all the array elements


for (double element: myList) {
System.out.println(element);
}
}
}
This will produce the following result −
Output
1.9
2.9
3.4
3.5
Passing Arrays to Methods
Just as you can pass primitive type values to methods, you can also pass arrays to methods.
For example, the following method displays the elements in an int array −
Example
public static void printArray(int[] array) {
for (int i = 0; i < array.length; i++) {
System.out.print(array[i] + " ");
}
}
You can invoke it by passing an array. For example, the following statement invokes the
printArray method to display 3, 1, 2, 6, 4, and 2 –
Example
printArray(new int[]{3, 1, 2, 6, 4, 2});
Returning an Array from a Method
A method may also return an array. For example, the following method returns an array
that is the reversal of another array −
Example
public static int[] reverse(int[] list) {
int[] result = new int[list.length];

for (int i = 0, j = result.length - 1; i < list.length; i++, j--) {


result[j] = list[i];
}
return result;
}
The Arrays Class
The java.util.Arrays class contains various static methods for sorting and searching arrays,
comparing arrays, and filling array elements. These methods are overloaded for all
primitive types.

Sr.No. Method & Description

1 public static int binarySearch(Object[] a, Object key)


Searches the specified array of Object ( Byte, Int , double, etc.) for the specified
value using the binary search algorithm. The array must be sorted prior to making
this call. This returns index of the search key, if it is contained in the list;
otherwise, it returns ( – (insertion point + 1)).

2 public static boolean equals(long[] a, long[] a2)


Returns true if the two specified arrays of longs are equal to one another. Two
arrays are considered equal if both arrays contain the same number of elements,
and all corresponding pairs of elements in the two arrays are equal. This returns
true if the two arrays are equal. Same method could be used by all other primitive
data types (Byte, short, Int, etc.)

3 public static void fill(int[] a, int val)


Assigns the specified int value to each element of the specified array of ints. The
same method could be used by all other primitive data types (Byte, short, Int, etc.)

4 public static void sort(Object[] a)


Sorts the specified array of objects into an ascending order, according to the
natural ordering of its elements. The same method could be used by all other
primitive data types ( Byte, short, Int, etc.)

You might also like