Java – Inner Classes

Java – Inner classes ”; Previous Next Java Inner Class A Java inner class is a class that is defined inside another class. The concept of inner class works with nested Java classes where outer and inner classes are used. The main class in which inner classes are defined is known as the outer class and all other classes which are inside the outer class are known as Java inner classes. Nested Classes In Java, just like methods, variables of a class too can have another class as its member. Writing a class within another is allowed in Java. The class written within is called the nested class, and the class that holds the inner class is called the outer class. Syntax Following is the syntax to write a nested class. Here, the class Outer_Demo is the outer class and the class Inner_Demo is the nested class. class Outer_Demo { class Inner_Demo { } } Nested classes are divided into two types − Non-static nested classes − These are the non-static members of a class. Static nested classes − These are the static members of a class. Inner Classes (Non-static Nested Classes) Inner classes are a security mechanism in Java. We know a class cannot be associated with the access modifier private, but if we have the class as a member of other class, then the inner class can be made private. And this is also used to access the private members of a class. Types of Java Inner Classes Inner classes are of three types depending on how and where you define them. They are − Inner Class Method-local Inner Class Anonymous Inner Class Creating an Inner Class Creating an inner class is quite simple. You just need to write a class within a class. Unlike a class, an inner class can be private and once you declare an inner class private, it cannot be accessed from an object outside the class. Following is the program to create an inner class and access it. In the given example, we make the inner class private and access the class through a method. Example: Creating an inner class in Java class Outer_Demo { int num; // inner class private class Inner_Demo { public void print() { System.out.println(“This is an inner class”); } } // Accessing he inner class from the method within void display_Inner() { Inner_Demo inner = new Inner_Demo(); inner.print(); } } public class My_class { public static void main(String args[]) { // Instantiating the outer class Outer_Demo outer = new Outer_Demo(); // Accessing the display_Inner() method. outer.display_Inner(); } } Here you can observe that Outer_Demo is the outer class, Inner_Demo is the inner class, display_Inner() is the method inside which we are instantiating the inner class, and this method is invoked from the main method. If you compile and execute the above program, you will get the following result − Output This is an inner class. Accessing the Private Members As mentioned earlier, inner classes are also used to access the private members of a class. Suppose, a class is having private members to access them. Write an inner class in it, return the private members from a method within the inner class, say, getValue(), and finally from another class (from which you want to access the private members) call the getValue() method of the inner class. To instantiate the inner class, initially you have to instantiate the outer class. Thereafter, using the object of the outer class, following is the way in which you can instantiate the inner class. Outer_Demo outer = new Outer_Demo(); Outer_Demo.Inner_Demo inner = outer.new Inner_Demo(); The following program shows how to access the private members of a class using inner class. Example: Accessing the Private Members Using Inner Class class Outer_Demo { // private variable of the outer class private int num = 175; // inner class public class Inner_Demo { public int getNum() { System.out.println(“This is the getnum method of the inner class”); return num; } } } public class My_class2 { public static void main(String args[]) { // Instantiating the outer class Outer_Demo outer = new Outer_Demo(); // Instantiating the inner class Outer_Demo.Inner_Demo inner = outer.new Inner_Demo(); System.out.println(inner.getNum()); } } If you compile and execute the above program, you will get the following result − Output This is the getnum method of the inner class: 175 Method-local Inner Class In Java, we can write a class within a method and this will be a local type. Like local variables, the scope of the inner class is restricted within the method. A method-local inner class can be instantiated only within the method where the inner class is defined. The following program shows how to use a method-local inner class. Example: Method-local Inner Class public class Outerclass { // instance method of the outer class void my_Method() { int num = 23; // method-local inner class class MethodInner_Demo { public void print() { System.out.println(“This is method inner class “+num); } } // end of inner class // Accessing the inner class MethodInner_Demo inner = new MethodInner_Demo(); inner.print(); } public static void main(String args[]) { Outerclass outer = new Outerclass(); outer.my_Method(); } } If you compile and execute the above program, you will get the following result − Output This is method inner class 23 Anonymous Inner Class An inner class declared without a class name is known as an anonymous inner class. In case of anonymous inner classes, we declare and instantiate them at the same time. Generally, they are used whenever you need to override the method of a class or an interface. The syntax of an anonymous inner class is as follows − Syntax: Anonymous Inner Class AnonymousInner an_inner = new AnonymousInner() { public void my_method() { …….. …….. } }; The following program shows how to override the method of a class using anonymous inner class. Example: Anonymous Inner Class abstract class AnonymousInner { public abstract void mymethod(); } public class Outer_class { public static void main(String

Java – Enums

Java – Enum class ”; Previous Next Introduction The Java Enum class is the common base class of all Java language enumeration types. Class Declaration Following is the declaration for java.lang.Enum class − public abstract class Enum<E extends Enum<E>> extends Object implements Comparable<E>, Serializable Class constructors Sr.No. Constructor & Description 1 protected Enum(String name, int ordinal) This is the single constructor. Class methods Sr.No. Method & Description 1 int compareTo(E o) This method compares this enum with the specified object for order. 2 boolean equals(Object other) This method returns true if the specified object is equal to this enum constant. 3 Class<E> getDeclaringClass() This method returns the Class object corresponding to this enum constant”s enum type. 4 int hashCode() This method returns a hash code for this enum constant. 5 String name() This method returns the name of this enum constant, exactly as declared in its enum declaration. 6 int ordinal() This method returns the ordinal of this enumeration constant (its position in its enum declaration, where the initial constant is assigned an ordinal of zero). 7 String toString() This method returns the name of this enum constant, as contained in the declaration. 8 static <T extends Enum<T>> T valueOf(Class<T> enumType, String name) This method returns the enum constant of the specified enum type with the specified name. Methods inherited This class inherits methods from the following classes − java.lang.Object Example Following example showcases the usage of enum in if and switch statements. package com.tutorialspoint; public class EnumDemo { public static void main(String args[]) { //print an Enum System.out.println(Mobile.Motorola); Mobile mobile = Mobile.Samsung; //Usage in IF statment if(mobile == Mobile.Samsung) { System.out.println(“Matched”); } //Usage in Swith statment switch(mobile) { case Samsung: System.out.println(“Samsung”); break; case Nokia: System.out.println(“Nokia”); break; case Motorola: System.out.println(“Motorola”); } } } enum Mobile { Samsung, Nokia, Motorola } Output Let us compile and run the above program, this will produce the following result − Motorola Matched Samsung Print Page Previous Next Advertisements ”;

Java – Math Class

Java – Math Class ”; Previous Next Java Math Class The java.lang.Math class contains methods for performing basic numeric operations such as the elementary exponential, logarithm, square root, and trigonometric functions. Math Class Declaration Following is the declaration for java.lang.Math class − public final class Math extends Object Java Math Class Fields Following are the fields for java.lang.Math class − static double E − This is the double value that is closer than any other to e, the base of the natural logarithms. static double PI − This is the double value that is closer than any other to pi, the ratio of the circumference of a circle to its diameter. Java Math Class Methods Sr.No. Method & Description 1 static double abs(double a) This method returns the absolute value of a double value. 2 static float abs(float a) This method returns the absolute value of a float value. 3 static int abs(int a) This method returns the absolute value of an int value. 4 static long abs(long a) This method returns the absolute value of a long value. 5 static double acos(double a) This method returns the arc cosine of a value; the returned angle is in the range 0.0 through pi. 6 static double asin(double a) This method returns the arc sine of a value; the returned angle is in the range -pi/2 through pi/2. 7 static double atan(double a) This method returns the arc tangent of a value; the returned angle is in the range -pi/2 through pi/2. 8 static double atan2(double y, double x) This method returns the angle theta from the conversion of rectangular coordinates (x, y) to polar coordinates (r, theta). 9 static double cbrt(double a) This method returns the cube root of a double value. 10 static double ceil(double a) This method returns the smallest (closest to negative infinity) double value that is greater than or equal to the argument and is equal to a mathematical integer. 11 static double copySign(double magnitude, double sign) This method returns the first floating-point argument with the sign of the second floating-point argument. 12 static float copySign(float magnitude, float sign) This method returns the first floating-point argument with the sign of the second floating-point argument. 13 static double cos(double a) This method returns the trigonometric cosine of an angle. 14 static double cosh(double x) This method returns the hyperbolic cosine of a double value. 15 static double exp(double a) This method returns Euler”s number e raised to the power of a double value. 16 static double expm1(double x) This method returns ex -1. 17 static double floor(double a) This method returns the largest (closest to positive infinity) double value that is less than or equal to the argument and is equal to a mathematical integer. 18 static int getExponent(double d) This method returns the unbiased exponent used in the representation of a double. 19 static int getExponent(float f) This method returns the unbiased exponent used in the representation of a float. 20 static double hypot(double x, double y) This method returns sqrt(x2 +y2) without intermediate overflow or underflow. 21 static double IEEEremainder(double f1, double f2) This method computes the remainder operation on two arguments as prescribed by the IEEE 754 standard. 22 static double log(double a) This method returns the natural logarithm (base e) of a double value. 23 static double log10(double a) This method returns the base 10 logarithm of a double value. 24 static double log1p(double x) This method returns the natural logarithm of the sum of the argument and 1. 25 static double max(double a, double b) This method returns the greater of two double values. 26 static float max(float a, float b) This method returns the greater of two float values. 27 static int max(int a, int b) This method returns the greater of two int values. 28 static long max(long a, long b) This method returns the greater of two long values. 29 static double min(double a, double b) This method returns the smaller of two double values. 30 static float min(float a, float b) This method returns the smaller of two float values. 31 static int min(int a, int b) This method returns the smaller of two int values. 32 static long min(long a, long b) This method returns the smaller of two long values. 33 static double nextAfter(double start, double direction) This method returns the floating-point number adjacent to the first argument in the direction of the second argument. 34 static float nextAfter(float start, double direction) This method returns the floating-point number adjacent to the first argument in the direction of the second argument. 35 static double nextUp(double d) This method returns the floating-point value adjacent to d in the direction of positive infinity. 36 static float nextUp(float f) This method returns the floating-point value adjacent to f in the direction of positive infinity. 37 static double pow(double a, double b) This method returns the value of the first argument raised to the power of the second argument. 38 static double random() This method returns a double value with a positive sign, greater than or equal to 0.0 and less than 1.0. 39 static double rint(double a) This method returns the double value that is closest in value to the argument and is equal to a mathematical integer. 40 static long round(double a) This method returns the closest long to the argument. 41 static int round(float a) This method returns the closest int to the argument. 42 static double scalb(double d, int scaleFactor) This method returns d × 2scaleFactor rounded as if performed by a single correctly rounded floating-point multiply to a member of the double value set. 43 static float scalb(float f, int scaleFactor) This method return f × 2scaleFactor rounded as if performed by a single correctly rounded floating-point multiply to a member of the float value set. 44 static double signum(double d) This method returns the signum function of the argument; zero if the argument is zero, 1.0 if the argument is greater

Java – Static Class

Java – Static Classes ”; Previous Next In Java concept of static class is introduced under concept of inner classes, which are specially designed for some delicate functionality in a class. Java Static Classes Static classes in Java are allowed only for inner classes which are defined under some other class, as static outer class is not allowed which means that we can”t use static keyword with outer class. Static classes are defined the same as other inner classes in Java only with a static keyword in front of its name. These classes have some unique characteristics that make them differ from other non-static inner classes. Features of Java Static Classes The following are the features of static classes in Java: Static class do not need to create an instance of outer containing class in order to create its own instance. Static class can access members(variables/methods) of outer containing class only if they are static in nature.Which means that a static nested class does not have access to the instance variables and methods of the outer class. Syntax of Java Static Class The syntax of static nested class is as follows − class MyOuter { static class Nested_Demo { } } Instantiating a static nested class is a bit different from instantiating an inner class. The following programs show how to use a static nested class in multiple cases. Example of Java Static Class In this example, we”ve created a class Outer and an inner static class as NestedDemo within it. In main() method, we”re using static method of static class directly without any reference as main is part of Outer class. package com.tutorialspoint; public class Outer { static class NestedDemo { public static void print() { System.out.println(“This is my nested class”); } } public static void main(String args[]) { NestedDemo.print(); } } If you compile and execute the above program, you will get the following result − Output This is my nested class Java Static Class: More Examples Example 1 In this example, we”ve created a class Outer and an inner static class as NestedDemo within it. As main method is in different class, we”re accessing the static inner class using Outer class. package com.tutorialspoint; public class Tester { public static void main(String[] arguments) { Outer.NestedDemo.print(); } } class Outer { static class NestedDemo { public static void print() { System.out.println(“This is my nested class”); } } } If you compile and execute the above program, you will get the following result − Output This is my nested class Example 2 In this example, we”ve created a class Outer and an inner static class as NestedDemo within it. Now as static class has instance method and main method is in different class, we”re accessing the static inner class using Outer class object. package com.tutorialspoint; public class Tester { public static void main(String[] arguments) { new Outer.NestedDemo().print(); } } class Outer { static class NestedDemo { public void print() { System.out.println(“This is my nested class”); } } } If you compile and execute the above program, you will get the following result − Output This is my nested class Print Page Previous Next Advertisements ”;

Java – Dynamic Binding

Java – Dynamic Binding ”; Previous Next Binding is a mechanism creating link between method call and method actual implementation. As per the polymorphism concept in Java, object can have many different forms. Object forms can be resolved at compile time and run time. Java Dynamic Binding Dynamic binding refers to the process in which linking between method call and method implementation is resolved at run time (or, a process of calling an overridden method at run time). Dynamic binding is also known as run-time polymorphism or late binding. Dynamic binding uses objects to resolve binding. Characteristics of Java Dynamic Binding Linking − Linking between method call and method implementation is resolved at run time. Resolve mechanism − Dynamic binding uses object type to resolve binding. Example − Method overriding is the example of Dynamic binding. Type of Methods − Virtual methods use dynamic binding. Example of Java Dynamic Binding In this example, we”ve created two classes Animal and Dog where Dog class extends Animal class. In main() method, we”re using Animal class reference and assign it an object of Dog class to check Dynamic binding effect. package com.tutorialspoint; class Animal { public void move() { System.out.println(“Animals can move”); } } class Dog extends Animal { public void move() { System.out.println(“Dogs can walk and run”); } } public class Tester { public static void main(String args[]) { Animal a = new Animal(); // Animal reference and object // Dynamic Binding Animal b = new Dog(); // Animal reference but Dog object a.move(); // runs the method in Animal class b.move(); // runs the method in Dog class } } Output Animals can move Dogs can walk and run In the above example, you can see that even though b is a type of Animal it runs the move method in the Dog class. The reason for this is: In compile time, the check is made on the reference type. However, in the runtime, JVM figures out the object type and would run the method that belongs to that particular object. Therefore, in the above example, the program will compile properly since Animal class has the method move. Then, at the runtime, it runs the method specific for that object. Java Dynamic Binding: Using the super Keyword When invoking a superclass version of an overridden method the super keyword is used so that we can utilize parent class method while using dynamic binding. Example: Using the super Keyword In this example, we”ve created two classes Animal and Dog where Dog class extends Animal class. Dog class overrides the move method of its super class Animal. But it calls parent move() method using super keyword so that both move methods are called when child method is called due to dynamic binding. In main() method, we”re using Animal class reference and assign it an object of Dog class to check Dynamic binding effect. class Animal { public void move() { System.out.println(“Animals can move”); } } class Dog extends Animal { public void move() { super.move(); // invokes the super class method System.out.println(“Dogs can walk and run”); } } public class TestDog { public static void main(String args[]) { Animal b = new Dog(); // Animal reference but Dog object b.move(); // runs the method in Dog class } } Output Animals can move Dogs can walk and run Print Page Previous Next Advertisements ”;

Java – Overriding

Java – Overriding ”; Previous Next In the previous chapter, we talked about superclasses and subclasses. If a class inherits a method from its superclass, then there is a chance to override the method provided that it is not marked final. Benefit of Overriding in Java The benefit of overriding is: ability to define a behavior that”s specific to the subclass type, which means a subclass can implement a parent class method based on its requirement. In object-oriented terms, overriding means to override the functionality of an existing method. Java Method Overriding Method overriding allows us to achieve run-time polymorphism and is used for writing specific definitions of a subclass method that is already defined in the superclass. The method is superclass and overridden method in the subclass should have the same declaration signature such as parameters list, type, and return type. Usage of Java Method Overriding Following are the two important usages of method overriding in Java: Method overriding is used for achieving run-time polymorphism. Method overriding is used for writing specific definition of a subclass method (this method is known as the overridden method). Example of Method Overriding in Java Let us look at an example. class Animal { public void move() { System.out.println(“Animals can move”); } } class Dog extends Animal { public void move() { System.out.println(“Dogs can walk and run”); } } public class TestDog { public static void main(String args[]) { Animal a = new Animal(); // Animal reference and object Animal b = new Dog(); // Animal reference but Dog object a.move(); // runs the method in Animal class b.move(); // runs the method in Dog class } } Output Animals can move Dogs can walk and run In the above example, you can see that even though b is a type of Animal it runs the move method in the Dog class. The reason for this is: In compile time, the check is made on the reference type. However, in the runtime, JVM figures out the object type and would run the method that belongs to that particular object. Therefore, in the above example, the program will compile properly since Animal class has the method move. Then, at the runtime, it runs the method specific for that object. Consider the following example − Example class Animal { public void move() { System.out.println(“Animals can move”); } } class Dog extends Animal { public void move() { System.out.println(“Dogs can walk and run”); } public void bark() { System.out.println(“Dogs can bark”); } } public class TestDog { public static void main(String args[]) { Animal a = new Animal(); // Animal reference and object Animal b = new Dog(); // Animal reference but Dog object a.move(); // runs the method in Animal class b.move(); // runs the method in Dog class b.bark(); } } Output TestDog.java:26: error: cannot find symbol b.bark(); ^ symbol: method bark() location: variable b of type Animal 1 error This program will throw a compile time error since b”s reference type Animal doesn”t have a method by the name of bark. Rules for Method Overriding The argument list should be exactly the same as that of the overridden method. The return type should be the same or a subtype of the return type declared in the original overridden method in the superclass. The access level cannot be more restrictive than the overridden method”s access level. For example: If the superclass method is declared public then the overridding method in the sub class cannot be either private or protected. Instance methods can be overridden only if they are inherited by the subclass. A method declared final cannot be overridden. A method declared static cannot be overridden but can be re-declared. If a method cannot be inherited, then it cannot be overridden. A subclass within the same package as the instance”s superclass can override any superclass method that is not declared private or final. A subclass in a different package can only override the non-final methods declared public or protected. An overriding method can throw any uncheck exceptions, regardless of whether the overridden method throws exceptions or not. However, the overriding method should not throw checked exceptions that are new or broader than the ones declared by the overridden method. The overriding method can throw narrower or fewer exceptions than the overridden method. Constructors cannot be overridden. Java Method and Constructor Overriding In Java, each class has a different name and the constructor”s name is the same as the class name. Thus, we cannot override a constructor as they cannot have the same name. Java Method Overriding: Using the super Keyword When invoking a superclass version of an overridden method the super keyword is used. Example: Using the super Keyword class Animal { public void move() { System.out.println(“Animals can move”); } } class Dog extends Animal { public void move() { super.move(); // invokes the super class method System.out.println(“Dogs can walk and run”); } } public class TestDog { public static void main(String args[]) { Animal b = new Dog(); // Animal reference but Dog object b.move(); // runs the method in Dog class } } Output Animals can move Dogs can walk and run Print Page Previous Next Advertisements ”;

Java – Abstraction

Java – Abstraction ”; Previous Next As per dictionary, abstraction is the quality of dealing with ideas rather than events. For example, when you consider the case of e-mail, complex details such as what happens as soon as you send an e-mail, the protocol your e-mail server uses are hidden from the user. Therefore, to send an e-mail you just need to type the content, mention the address of the receiver, and click send. Java Abstraction Abstraction is a process of hiding the implementation details from the user, only the functionality will be provided to the user. In other words, the user will have the information on what the object does instead of how it does it. In Java programming, abstraction is achieved using Abstract classes and interfaces. Java Abstract Classes A Java class which contains the abstract keyword in its declaration is known as abstract class. Java abstract classes may or may not contain abstract methods, i.e., methods without body ( public void get(); ) But, if a class has at least one abstract method, then the class must be declared abstract. If a class is declared abstract, it cannot be instantiated. To use an abstract class, you have to inherit it from another class, provide implementations to the abstract methods in it. If you inherit an abstract class, you have to provide implementations to all the abstract methods in it. Example: Java Abstract Class This section provides you an example of the Java Abstract Class. To create an abstract class in Java, just use the abstract keyword before the class keyword, in the class declaration. /* File name : Employee.java */ public abstract class Employee { private String name; private String address; private int number; public Employee(String name, String address, int number) { System.out.println(“Constructing an Employee”); this.name = name; this.address = address; this.number = number; } public double computePay() { System.out.println(“Inside Employee computePay”); return 0.0; } public void mailCheck() { System.out.println(“Mailing a check to ” + this.name + ” ” + this.address); } public String toString() { return name + ” ” + address + ” ” + number; } public String getName() { return name; } public String getAddress() { return address; } public void setAddress(String newAddress) { address = newAddress; } public int getNumber() { return number; } } You can observe that except abstract methods the Employee class is same as normal class in Java. The class is now abstract, but it still has three fields, seven methods, and one constructor. Now you can try to instantiate the Employee class in the following way − /* File name : AbstractDemo.java */ public class AbstractDemo { public static void main(String [] args) { /* Following is not allowed and would raise error */ Employee e = new Employee(“George W.”, “Houston, TX”, 43); System.out.println(“n Call mailCheck using Employee reference–“); e.mailCheck(); } } abstract class Employee { private String name; private String address; private int number; public Employee(String name, String address, int number) { System.out.println(“Constructing an Employee”); this.name = name; this.address = address; this.number = number; } public double computePay() { System.out.println(“Inside Employee computePay”); return 0.0; } public void mailCheck() { System.out.println(“Mailing a check to ” + this.name + ” ” + this.address); } public String toString() { return name + ” ” + address + ” ” + number; } public String getName() { return name; } public String getAddress() { return address; } public void setAddress(String newAddress) { address = newAddress; } public int getNumber() { return number; } } When you compile the above class, it gives you the following error − Employee.java:46: Employee is abstract; cannot be instantiated Employee e = new Employee(“George W.”, “Houston, TX”, 43); ^ 1 error Inheriting the Java Abstract Class We can inherit the properties of Employee class just like concrete class in the following way − Example: Inheriting the Abstract Class in Java /* File name : Salary.java */ public class Salary extends Employee { private double salary; // Annual salary public Salary(String name, String address, int number, double salary) { super(name, address, number); setSalary(salary); } public void mailCheck() { System.out.println(“Within mailCheck of Salary class “); System.out.println(“Mailing check to ” + getName() + ” with salary ” + salary); } public double getSalary() { return salary; } public void setSalary(double newSalary) { if(newSalary >= 0.0) { salary = newSalary; } } public double computePay() { System.out.println(“Computing salary pay for ” + getName()); return salary/52; } } Here, you cannot instantiate the Employee class, but you can instantiate the Salary Class, and using this instance you can access all the three fields and seven methods of Employee class as shown below. /* File name : AbstractDemo.java */ public class AbstractDemo { public static void main(String [] args) { Salary s = new Salary(“Mohd Mohtashim”, “Ambehta, UP”, 3, 3600.00); Employee e = new Salary(“John Adams”, “Boston, MA”, 2, 2400.00); System.out.println(“Call mailCheck using Salary reference –“); s.mailCheck(); System.out.println(“n Call mailCheck using Employee reference–“); e.mailCheck(); } } abstract class Employee { private String name; private String address; private int number; public Employee(String name, String address, int number) { System.out.println(“Constructing an Employee”); this.name = name; this.address = address; this.number = number; } public double computePay() { System.out.println(“Inside Employee computePay”); return 0.0; } public void mailCheck() { System.out.println(“Mailing a check to ” + this.name + ” ” + this.address); } public String toString() { return name + ” ” + address + ” ” + number; } public String getName() { return name; } public String getAddress() { return address; } public void setAddress(String newAddress) { address = newAddress; } public int getNumber() { return number; } } class Salary extends Employee { private double salary; // Annual salary public Salary(String name, String address, int number, double salary) { super(name, address, number); setSalary(salary); } public void mailCheck() { System.out.println(“Within mailCheck of Salary class “); System.out.println(“Mailing check to ” + getName() + ” with salary ” + salary); } public double getSalary() { return salary; } public void setSalary(double newSalary) {

Java – do-while Loops

Java – do…while Loop ”; Previous Next Java do while Loop A do while loop is similar to a while loop, except that a do while loop is guaranteed to execute at least one time. The do-while loop is an exit control loop, where the condition is checked after executing the loop”s body. Syntax of do while Loop Following is the syntax of a do…while loop − do { // Statements }while(Boolean_expression); Execution Process of a do while Loop Notice that the Boolean expression appears at the end of the loop, so the statements in the loop execute once before the Boolean is tested. If the Boolean expression is true, the control jumps back up to do statement, and the statements in the loop execute again. This process repeats until the Boolean expression is false. Flow Diagram The following diagram shows the flow diagram (execution process) of a do while loop in Java – do while Loop Examples Example 1: Printing Numbers in a Range Using do while In this example, we”re showing the use of a while loop to print numbers starting from 10 to 19. Here we”ve initialized an int variable x with a value of 10. Then in do while loop, we”re checking x as less than 20 after do while loop body.In do while loop body we”re printing the value of x and incrementing the value of x by 1. While loop will run until x becomes 20. Once x is 20, loop will stop execution and program exits. public class Test { public static void main(String args[]) { int x = 10; do { System.out.print(“value of x : ” + x ); x++; System.out.print(“n”); }while( x < 20 ); } } Output value of x : 10 value of x : 11 value of x : 12 value of x : 13 value of x : 14 value of x : 15 value of x : 16 value of x : 17 value of x : 18 value of x : 19 Example 2: Printing Elements of an Array Using do while In this example, we”re showing the use of a do while loop to print contents of an array. Here we”re creating an array of integers as numbers and initialized it some values. We”ve created a variable named index to represent index of the array while iterating it. In do while loop we”re checking the index to be less than size of the array after loop body and printed the element of the array using index notation. Within loop body index variable is incremented by 1 and loop continues till index becomes the sie of the array and loop exits. public class Test { public static void main(String args[]) { int [] numbers = {10, 20, 30, 40, 50}; int index = 0; do { System.out.print(“value of item : ” + numbers[index] ); index++; System.out.print(“n”); } while( index < 5 ); } } Output value of item : 10 value of item : 20 value of item : 30 value of item : 40 value of item : 50 do while Infinite Loop in Java An infinite loop can also be implemented by writing “true” as the conditional statement using do do-while loop statement in Java. Example: Implementing an infinite do while Loop In this example, we”re showing the infinite loop using while loop. It will keep printing the numbers until you press ctrl+c to terminate the program. public class Test { public static void main(String args[]) { int x = 10; do { System.out.print(“value of x : ” + x ); x++; System.out.print(“n”); } while( true ); } } Output value of item : 10 value of item : 20 value of item : 30 value of item : 40 value of item : 50 … ctrl+c java_loop_control.htm Print Page Previous Next Advertisements ”;

Java – Break

Java – break Statement ”; Previous Next Java break Statement The break statement in Java programming language has following two usages − When the break statement is encountered inside a loop, the loop is immediately terminated and the program control resumes at the next statement following the loop. It can be used to terminate a case in the switch statement (covered in the next chapter). Syntax The syntax of a break is a single statement inside any loop or switch case − break; Flow Diagram Examples Example 1: Using break with while loop In this example, we”re showing the use of a break statement to break a while loop to print numbers starting from 10 to 14 which will otherwise print element till 19. Here we”ve initialized an int variable x with a value of 10. Then in while loop, we”re checking x as less than 20 and within while loop, we”re printing the value of x and incrementing the value of x by 1. While loop will run until x becomes 15. Once x is 15, break statement will break the while loop and program exits. public class Test { public static void main(String args[]) { int x = 10; while( x < 20 ) { if(x == 15){ break; } System.out.print(“value of x : ” + x ); x++; System.out.print(“n”); } } } Output value of x : 10 value of x : 11 value of x : 12 value of x : 13 value of x : 14 Example 2: Using break with for loop In this example, we”re showing the use of a break statement within a for loop to print few elements of an array instead of all elements. Here we”re creating an array of integers as numbers and initialized it some values. We”ve created a variable named index to represent index of the array within for loop, check it against size of the array and incremented it by 1. Within for loop body, we”re printing element of the array using index notation. Once 30 is encountered as value, break statement breaks the flow of for loop and program quits. public class Test { public static void main(String args[]) { int [] numbers = {10, 20, 30, 40, 50}; for(int index = 0; index < numbers.length; index++) { if(numbers[index] == 30){ break; } System.out.print(“value of item : ” + numbers[index] ); System.out.print(“n”); } } } Output value of item : 10 value of item : 20 Example 3: Using break with an infinite loop In this example, we”re showing the use of break statement to break an infinite loop using while loop. It will keep printing the numbers until the value of x becomes 15. public class Test { public static void main(String args[]) { int x = 10; while( true ) { System.out.print(“value of x : ” + x ); x++; if(x == 15) { break; } System.out.print(“n”); } } } Output value of item : 10 value of item : 11 value of item : 12 value of item : 13 value of item : 14 java_loop_control.htm Print Page Previous Next Advertisements ”;

Java – Aggregation

Java – Aggregation ”; Previous Next Java Aggregation An aggregation is a relationship between two classes where one class contains an instance of another class. For example, when an object A contains a reference to another object B or we can say Object A has a HAS-A relationship with Object B, then it is termed as Aggregation in Java Programming. Use of Java Aggregation Aggregation in Java helps in reusing the code. Object B can have utility methods and which can be utilized by multiple objects. Whichever class has object B then it can utilize its methods. Java Aggregation Examples Example 1 In this example, we”re creating few classes like Vehicle, Speed. A Van class is defined which extends Vehicle class and has a Speed class object. Van class inherits properties from Vehicle class and Speed being its property, we”re passing it from caller object. In output, we”re printing the details of Van object. package com.tutorialspoint; class Vehicle{ private String vin; public String getVin() { return vin; } public void setVin(String vin) { this.vin = vin; } } class Speed{ private double max; public double getMax() { return max; } public void setMax(double max) { this.max = max; } } class Van extends Vehicle { private Speed speed; public Speed getSpeed() { return speed; } public void setSpeed(Speed speed) { this.speed = speed; } public void print() { System.out.println(“Vin: ” +this.getVin() + “, Max Speed: ” + speed.getMax() ); } } public class Tester { public static void main(String[] args) { Speed speed = new Speed(); speed.setMax(120); Van van = new Van(); van.setVin(“abcd1233″); van.setSpeed(speed); van.print(); } } Output Vin: abcd1233, Max Speed: 120.0 Example 2 In this example, we”re creating few classes like Student, Address. A student can has a address. So we”ve defined an address as an instance variable in Student class. In output, we”re printing the student details. package com.tutorialspoint; class Address { int strNum; String city; String state; String country; Address(int street, String c, String st, String country) { this.strNum = street; this.city = c; this.state = st; this.country = country; } } class Student { int rno; String stName; Address stAddr; Student(int roll, String name, Address address){ this.rno = roll; this.stName = name; this.stAddr = address; } } public class Tester { public static void main(String[] args) { Address ad= new Address(10, “Bareilly”, “UP”, “India”); Student st= new Student(1, “Aashi”, ad); System.out.println(“Roll no: “+ st.rno); System.out.println(“Name: “+ st.stName); System.out.println(“Street: “+ st.stAddr.strNum); System.out.println(“City: “+ st.stAddr.city); System.out.println(“State: “+ st.stAddr.state); System.out.println(“Country: “+ st.stAddr.country); } } Output Roll no: 1 Name: Aashi Street: 10 City: Bareilly State: UP Country: India In a unique sense, this is a type of association. Aggregation is a one way directed relationship that precisely expresses HAS-A relationship between classes. Additionally, when two classes are aggregated, terminating one of them has no effect on the other. When compared to composition, it is frequently designated as a weak relationship. In comparison, the parent owns the child entity, which means the child entity cannot be accessed directly and cannot exist without the parent object. Contrarily, in an association, the parent and child entities may both exist in their own right. HAS-A Relationship These relationships are mainly based on the usage. This determines whether a certain class HAS-A certain thing. This relationship helps to reduce duplication of code as well as bugs. Example public class Vehicle{} public class Speed{} public class Van extends Vehicle { private Speed sp; } This shows that class Van HAS-A Speed. By having a separate class for Speed, we do not have to put the entire code that belongs to speed inside the Van class, which makes it possible to reuse the Speed class in multiple applications. In Object-Oriented feature, the users do not need to bother about which object is doing the real work. To achieve this, the Van class hides the implementation details from the users of the Van class. So, basically what happens is the users would ask the Van class to do a certain action and the Van class will either do the work by itself or ask another class to perform the action. Print Page Previous Next Advertisements ”;