Java – Method Overloading ”; Previous Next Java Method Overloading When a class has two or more methods by the same name but different parameters, at the time of calling based on the parameters passed respective method is called (or respective method body will be bonded with the calling line dynamically). This mechanism is known as method overloading. Advantage of Method Overloading Method overloading improves the code readability and reduces code redundancy. Method overloading also helps to achieve compile-time polymorphism. Example of Method Overloading If you observe the following example, Here we have created a class named Tester this class has two methods with same name (add) and return type, the only difference is the parameters they accept (one method accepts two integer variables and other accepts three integer variables). class Calculator{ public static int add(int a, int b){ return a + b; } public static int add(int a, int b, int c){ return a + b + c; } } When you invoke the add() method based on the parameters you pass respective method body gets executed. int result = Calculator.add(1,2); // returns 3; result = Calculator.add(1,2,3); // returns 6; Different Ways of Java Method Overloading Method overloading can be achieved using following ways while having same name methods in a class. Use different number of arguments Use different type of arguments Invalid Ways of Java Method Overloading Method overloading cannot be achieved using following ways while having same name methods in a class. Compiler will complain of duplicate method presence. Using different return type Using static and non-static methods Method Overloading: Different Number of Arguments You can implement method overloading based on the different number of arguments. Example: Different Number of Arguments (Static Methods) In this example, we”ve created a Calculator class having two static methods with same name but different arguments to add two and three int values respectively. In main() method, we”re calling these methods and printing the result. Based on the type of arguments passed, compiler decides the method to be called and result is printed accordingly. package com.tutorialspoint; class Calculator{ public static int add(int a, int b){ return a + b; } public static int add(int a, int b, int c){ return a + b + c; } } public class Tester { public static void main(String args[]){ System.out.println(Calculator.add(20, 40)); System.out.println(Calculator.add(40, 50, 60)); } } Output 60 150 Example: Different Number of Arguments (Non Static Methods) In this example, we”ve created a Calculator class having two non-static methods with same name but different arguments to add two and three int values respectively. In main() method, we”re calling these methods using object of Calculator class and printing the result. Based on the number of arguments passed, compiler decides the method to be called and result is printed accordingly. package com.tutorialspoint; class Calculator{ public int add(int a, int b){ return a + b; } public int add(int a, int b, int c){ return a + b + c; } } public class Tester { public static void main(String args[]){ Calculator calculator = new Calculator(); System.out.println(calculator.add(20, 40)); System.out.println(calculator.add(40, 50, 60)); } } Output 60 150 Method Overloading: Different Type of Arguments You can implement method overloading based on the different type of arguments. Example: Different Type of Arguments In this example, we”ve created a Calculator class having two non-static methods with same name but different types of arguments to add two int values and two double values respectively. In main() method, we”re calling these methods using object of Calculator class and printing the result. Based on the type of arguments passed, compiler decides the method to be called and result is printed accordingly. package com.tutorialspoint; class Calculator{ public int add(int a, int b){ return a + b; } public double add(double a, double b){ return a + b; } } public class Tester { public static void main(String args[]){ Calculator calculator = new Calculator(); System.out.println(calculator.add(20, 40)); System.out.println(calculator.add(20.0, 40.0)); } } Output 60 60.0 Print Page Previous Next Advertisements ”;
Category: Java
Java – Thread Scheduler
Java – Scheduling Threads with Examples ”; Previous Next Java is a multi-threaded programming language which means we can develop multi-threaded program using Java. A multi-threaded program contains two or more parts that can run concurrently and each part can handle a different task at the same time making optimal use of the available resources specially when your computer has multiple CPUs. By definition, multitasking is when multiple processes share common processing resources such as a CPU. Multi-threading extends the idea of multitasking into applications where you can subdivide specific operations within a single application into individual threads. Each of the threads can run in parallel. The OS divides processing time not only among different applications, but also among each thread within an application. Multi-threading enables you to write in a way where multiple activities can proceed concurrently in the same program. Java provides a java.util.concurrent.ScheduledExecutorService interface which is a subinterface of ExecutorService interface, and supports future and/or periodic execution of tasks/threads. Following are few important and useful methods this interface. ScheduledExecutorService Methods Sr.No. Method & Description 1 <V> ScheduledFuture<V> schedule(Callable<V> callable, long delay, TimeUnit unit) Creates and executes a ScheduledFuture that becomes enabled after the given delay. 2 ScheduledFuture<?> schedule(Runnable command, long delay, TimeUnit unit) Creates and executes a one-shot action that becomes enabled after the given delay. 3 ScheduledFuture<?> scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit) Creates and executes a periodic action that becomes enabled first after the given initial delay, and subsequently with the given period; that is executions will commence after initialDelay then initialDelay+period, then initialDelay + 2 * period, and so on. 4 ScheduledFuture<?> scheduleWithFixedDelay(Runnable command, long initialDelay, long delay, TimeUnit unit) Creates and executes a periodic action that becomes enabled first after the given initial delay, and subsequently with the given delay between the termination of one execution and the commencement of the next. Example 1 The following TestThread program shows usage of ScheduledExecutorService interface in thread based environment to schedule a task to run after 2 seconds at interval of 2 seconds in time period of 10 seconds showcasing usage of scheduleAtFixedRate() and schedule() methods. package com.tutorialspoint; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; public class TestThread { public static void main(final String[] arguments) throws InterruptedException { final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1); final ScheduledFuture<?> beepHandler = scheduler.scheduleAtFixedRate(new BeepTask(), 2, 2, TimeUnit.SECONDS); scheduler.schedule(new Runnable() { @Override public void run() { beepHandler.cancel(true); scheduler.shutdown(); } }, 10, TimeUnit.SECONDS); } static class BeepTask implements Runnable { public void run() { System.out.println(“beep”); } } } Output beep beep beep beep beep Example 2 The following TestThread program shows usage of ScheduledExecutorService interface in thread based environment to schedule a task to run after 2 seconds at interval of 2 seconds in time period of 10 seconds showcasing usage of scheduleAtFixedDelay() and schedule() methods. package com.tutorialspoint; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; public class TestThread { public static void main(final String[] arguments) throws InterruptedException { final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1); final ScheduledFuture<?> beepHandler = scheduler.scheduleAtFixedDelay(new BeepTask(), 2, 2, TimeUnit.SECONDS); scheduler.schedule(new Runnable() { @Override public void run() { beepHandler.cancel(true); scheduler.shutdown(); } }, 10, TimeUnit.SECONDS); } static class BeepTask implements Runnable { public void run() { System.out.println(“beep”); } } } Output beep beep beep beep Example 3 The following TestThread program shows usage of ScheduledExecutorService interface in thread based environment to schedule a task to run once after 2 seconds in time period of 10 seconds showcasing usage of schedule() method. package com.tutorialspoint; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; public class TestThread { public static void main(final String[] arguments) throws InterruptedException { final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1); final ScheduledFuture<?> beepHandler = scheduler.schedule(new BeepTask(), 2, TimeUnit.SECONDS); scheduler.schedule(new Runnable() { @Override public void run() { beepHandler.cancel(true); scheduler.shutdown(); } }, 10, TimeUnit.SECONDS); } static class BeepTask implements Runnable { public void run() { System.out.println(“beep”); } } } Output beep Print Page Previous Next Advertisements ”;
Java – Finally Block
Java – Finally Block ”; Previous Next The finally Block in Java The finally block follows a try block or a catch block. A finally block of code always executes, irrespective of occurrence of an Exception. Using a finally block allows you to run any cleanup-type statements that you want to execute, no matter what happens in the protected code. Syntax: Finally Block A finally block appears at the end of the catch blocks and has the following syntax − try { // Protected code } catch (ExceptionType1 e1) { // Catch block } catch (ExceptionType2 e2) { // Catch block } catch (ExceptionType3 e3) { // Catch block }finally { // The finally block always executes. } Points To Remember While Using Finally Block A catch clause cannot exist without a try statement. It is not compulsory to have finally clauses whenever a try/catch block is present. The try block cannot be present without either catch clause or finally clause. Any code cannot be present in between the try, catch, finally blocks. finally block is not executed in case exit() method is called before finally block or a fatal error occurs in program execution. finally block is executed even method returns a value before finally block. Why Java Finally Block Used? Java finally block can be used for clean-up (closing) the connections, files opened, streams, etc. those must be closed before exiting the program. It can also be used to print some final information. Java Finally Block Example Here is code segment showing how to use finally after try/catch statements after handling exception. In this example, we”re creating an error accessing an element of an array using invalid index. The catch block is handling the exception and printing the same. Now in finally block, we”re printing a statement signifying that finally block is getting executed. package com.tutorialspoint; public class ExcepTest { public static void main(String args[]) { int a[] = new int[2]; try { System.out.println(“Access element three :” + a[3]); } catch (ArrayIndexOutOfBoundsException e) { System.out.println(“Exception thrown :” + e); }finally { a[0] = 6; System.out.println(“First element value: ” + a[0]); System.out.println(“The finally statement is executed”); } } } Output Exception thrown :java.lang.ArrayIndexOutOfBoundsException: 3 First element value: 6 The finally statement is executed More Examples Example 1 Here is code segment showing how to use finally after try/catch statements even exception is not handled. In this example, we”re creating an error accessing an element of an array using invalid index. As the catch block is not handling the exception, we can check in output that finally block is printing a statement signifying that finally block is getting executed. package com.tutorialspoint; public class ExcepTest { public static void main(String args[]) { int a[] = new int[2]; try { System.out.println(“Access element three :” + a[3]); } catch (ArithmeticException e) { System.out.println(“Exception thrown :” + e); }finally { a[0] = 6; System.out.println(“First element value: ” + a[0]); System.out.println(“The finally statement is executed”); } } } Output First element value: 6 The finally statement is executed Exception in thread “main” java.lang.ArrayIndexOutOfBoundsException: 3 at com.tutorialspoint.ExcepTest.main(ExcepTest.java:8) Example 2 Here is code segment showing how to use finally block where a method can return a value within try block. In this example, we”re returning a value within try block. We can check in output that finally block is printing a statement signifying that finally block is getting executed even after method returned a value to caller function. package com.tutorialspoint; public class ExcepTest { public static void main(String args[]) { System.out.println(testFinallyBlock()); } private static int testFinallyBlock() { int a[] = new int[2]; try { return 1; } catch (ArrayIndexOutOfBoundsException e) { System.out.println(“Exception thrown :” + e); }finally { a[0] = 6; System.out.println(“First element value: ” + a[0]); System.out.println(“The finally statement is executed”); } return 0; } } Output First element value: 6 The finally statement is executed 1 Print Page Previous Next Advertisements ”;
Java – Daemon Threads
Java – Daemon Thread ”; Previous Next Daemon Thread in Java A Daemon thread is created to support the user threads. It generallty works in background and terminated once all the other threads are closed. Garbage collector is one of the example of Daemon thread. Characteristics of a Daemon Thread in Java A Daemon thread is a low priority thread. A Daemon thread is a service provider thread and should not be used as user thread. JVM automatically closes the daemon thread(s) if no active thread is present and revives it if user threads are active again. A daemon thread cannot prevent JVM to exit if all user threads are done. Thread Class Methods for Java Daemon Thread The following are the methods provided by the Thread class for Daemon Thread in Java – Thread.setDaemon() Method: Marks this thread as either a daemon thread or a user thread. Thread.isDaemon() Method: Checks if this thread is a daemon thread. Example of Java Daemon Thread In this example, we”ve created a ThreadDemo class which extends Thread class. In main method, we”ve created three threads. As we”re not setting any thread as daemon thread, no thread is marked as daemon thread. package com.tutorialspoint; class ThreadDemo extends Thread { ThreadDemo( ) { } public void run() { System.out.println(“Thread ” + Thread.currentThread().getName() + “, is Daemon: ” + Thread.currentThread().isDaemon()); } public void start () { super.start(); } } public class TestThread { public static void main(String args[]) { ThreadDemo thread1 = new ThreadDemo(); ThreadDemo thread2 = new ThreadDemo(); ThreadDemo thread3 = new ThreadDemo(); thread1.start(); thread2.start(); thread3.start(); } } Output Thread Thread-1, is Daemon: false Thread Thread-0, is Daemon: false Thread Thread-2, is Daemon: false More Example of Java Daemon Thread Example 1 In this example, we”ve created a ThreadDemo class which extends Thread class. In main method, we”ve created three threads. As we”re setting one thread as daemon thread, one thread will be printed as daemon thread. package com.tutorialspoint; class ThreadDemo extends Thread { ThreadDemo( ) { } public void run() { System.out.println(“Thread ” + Thread.currentThread().getName() + “, is Daemon: ” + Thread.currentThread().isDaemon()); } public void start () { super.start(); } } public class TestThread { public static void main(String args[]) { ThreadDemo thread1 = new ThreadDemo(); ThreadDemo thread2 = new ThreadDemo(); ThreadDemo thread3 = new ThreadDemo(); thread3.setDaemon(true); thread1.start(); thread2.start(); thread3.start(); } } Output Thread Thread-1, is Daemon: false Thread Thread-2, is Daemon: true Thread Thread-0, is Daemon: false Example 2 In this example, we”ve created a ThreadDemo class which extends Thread class. In main method, we”ve created three threads. Once a thread starts, it cannot be set as daemon thread. As we”re setting one thread as daemon thread after it started, a runtime exception will be raised. package com.tutorialspoint; class ThreadDemo extends Thread { ThreadDemo( ) { } public void run() { System.out.println(“Thread ” + Thread.currentThread().getName() + “, is Daemon: ” + Thread.currentThread().isDaemon()); } public void start () { super.start(); } } public class TestThread { public static void main(String args[]) { ThreadDemo thread1 = new ThreadDemo(); ThreadDemo thread2 = new ThreadDemo(); ThreadDemo thread3 = new ThreadDemo(); thread1.start(); thread2.start(); thread3.start(); thread3.setDaemon(true); } } Output Exception in thread “main” Thread Thread-1, is Daemon: false Thread Thread-2, is Daemon: false Thread Thread-0, is Daemon: false java.lang.IllegalThreadStateException at java.lang.Thread.setDaemon(Unknown Source) at com.tutorialspoint.TestThread.main(TestThread.java:27) Print Page Previous Next Advertisements ”;
Java – Packages
Java – Packages ”; Previous Next Java Packages Packages are used in Java in order to prevent naming conflicts, control access, make searching/locating and usage of classes, interfaces, enumerations, and annotations easier, etc. A Java package can be defined as a grouping of related types (classes, interfaces, enumerations, and annotations ) providing access protection and namespace management. Types of Java Packages Java packages are of two types: Built-in Java Packages User-defined Java Packages Some of the existing packages in Java are − java.lang − bundles the fundamental classes java.io − classes for input , output functions are bundled in this package User-defined Java Packages You can define your own packages to bundle groups of classes/interfaces, etc. It is a good practice to group related classes implemented by you so that a programmer can easily determine that the classes, interfaces, enumerations, and annotations are related. Since the package creates a new namespace there won”t be any name conflicts with names in other packages. Using packages, it is easier to provide access control and it is also easier to locate the related classes. Creating a Java Package While creating a package, you should choose a name for the package and include a package statement along with that name at the top of every source file that contains the classes, interfaces, enumerations, and annotation types that you want to include in the package. The package statement should be the first line in the source file. There can be only one package statement in each source file, and it applies to all types in the file. If a package statement is not used then the class, interfaces, enumerations, and annotation types will be placed in the current default package. Compiling with Java Package To compile the Java programs with package statements, you have to use -d option as shown below. javac -d Destination_folder file_name.java Then a folder with the given package name is created in the specified destination, and the compiled class files will be placed in that folder. Java Package Example Let us look at an example that creates a package called animals. It is a good practice to use names of packages with lower case letters to avoid any conflicts with the names of classes and interfaces. Following package example contains interface named animals − /* File name : Animal.java */ package animals; interface Animal { public void eat(); public void travel(); } Now, let us implement the above interface in the same package animals − package animals; /* File name : MammalInt.java */ public class MammalInt implements Animal { public void eat() { System.out.println(“Mammal eats”); } public void travel() { System.out.println(“Mammal travels”); } public int noOfLegs() { return 0; } public static void main(String args[]) { MammalInt m = new MammalInt(); m.eat(); m.travel(); } } interface Animal { public void eat(); public void travel(); } Output Now compile the java files as shown below − $ javac -d . Animal.java $ javac -d . MammalInt.java Now a package/folder with the name animals will be created in the current directory and these class files will be placed in it as shown below. You can execute the class file within the package and get the result as shown below. Mammal eats Mammal travels Importing Java Package If a class wants to use another class in the same package, the package name need not be used. Classes in the same package find each other without any special syntax. Example Here, a class named Boss is added to the payroll package that already contains Employee. The Boss can then refer to the Employee class without using the payroll prefix, as demonstrated by the following Boss class. package payroll; public class Boss { public void payEmployee(Employee e) { e.mailCheck(); } } What happens if the Employee class is not in the payroll package? The Boss class must then use one of the following techniques for referring to a class in a different package. The fully qualified name of the class can be used. For example − payroll.Employee The package can be imported using the import keyword and the wild card (*). For example − import payroll.*; The class itself can be imported using the import keyword. For example − import payroll.Employee; Example package payroll; public class Employee { public void mailCheck() { System.out.println(“Pay received.”); } } Example package payroll; import payroll.Employee; public class Boss { public void payEmployee(Employee e) { e.mailCheck(); } public static void main(String[] args) { Boss boss = new Boss(); Employee e = new Employee(); boss.payEmployee(e); } } Output Pay received. Note − A class file can contain any number of import statements. The import statements must appear after the package statement and before the class declaration. Directory Structure of a Java Package Two major results occur when a class is placed in a package − The name of the package becomes a part of the name of the class, as we just discussed in the previous section. The name of the package must match the directory structure where the corresponding bytecode resides. Here is simple way of managing your files in Java − Put the source code for a class, interface, enumeration, or annotation type in a text file whose name is the simple name of the type and whose extension is .java. For example − // File Name : Car.java package vehicle; public class Car { // Class implementation. } Now, put the source file in a directory whose name reflects the name of the package to which the class belongs − ….vehicleCar.java Now, the qualified class name and pathname would be as follows − Class name → vehicle.Car Path name → vehicleCar.java (in windows) In general, a company uses its reversed Internet domain name for its package names. Example − A company”s Internet domain name is apple.com, then all its package names would start with com.apple. Each component of the package name corresponds to a subdirectory. Example − The company had a com.apple.computers package that contained
Java – Instance Initializer Block ”; Previous Next Java Instance Initializer Block An instance initializer block is a block of code that is declared inside a class to initialize the instance data members. Instance Initializer block is executed once for each object and can be used to set initial values for instance variables. The instance initializer block is similar to the Java constructor but its execution and uses are different. Java Instance Initializer Block Example This example demonstrates instance initializer block in Java: public class Tester { public int a; { a = 10; } } Characteristics of Instance Initializer Block Instance initializer block is called once an object is created. Instance initializer block is called before any constructor of an object is invoked. In case of child class, Instance initializer block will be called after super class constructor call. Instance initializer block can be used to execute multiple statements. Instance initializer block is generally used to instantiate multiple values fields like arrays. Use of Instance Initializer Block The following are the uses of instance initializer block in Java: To initialize the instance variable. To initialize the resources used in the code. To perform the dynamic initialization of the instance variables. To use the common initialization logic for multiple constructors. Java Instance Initializer Block: More Examples Example 1: Demonstrating What Invokes First, Instance Initializer Block or Constructor In this example, we”ve shown that instance initializer block is getting executed before the object constructor. Both instance initializer block and constructor are invoked when object is created using new operator. package com.tutorialspoint; public class Tester { { System.out.println(“Inside instance initializer block”); } Tester(){ System.out.println(“Inside constructor”); } public static void main(String[] arguments) { Tester test = new Tester(); } } Output 60 150 Example 2: Demonstrating Whether Constructor Overrides Instance Initializer Block In this example, we”ve shown that a value initialized in instance initializer block is getting overriden by the object constructor. Both instance initializer block and constructor are invoked when object is created using new operator. package com.tutorialspoint; public class Tester { int a; { System.out.println(“Inside instance initializer block”); a = 10; } Tester(){ System.out.println(“Inside constructor”); a = 20; } public static void main(String[] arguments) { Tester test = new Tester(); System.out.println(“Value of a: ” + a); } } Output Inside instance initializer block Inside constructor Value of a: 20 Example 3: Instance Initializer Block and Super Constructor In this example, we”ve shown that a super constructor is invoked before child instance initializer block. We”ve created a SuperTester class and Tester class extends this class. In main() method, we”re printing the value of instance variable. In output, you can verify the order of blocks invoked. First super constructor is invoked. Then child instance initializer is invoked which initializes an instance variable and then constructor of child class is invoked. package com.tutorialspoint; class SuperTester{ SuperTester(){ System.out.println(“Inside super constructor”); } } public class Tester extends SuperTester { int a; { System.out.println(“Inside instance initializer block”); a = 10; } Tester(){ System.out.println(“Inside constructor”); } public static void main(String[] arguments) { Tester test = new Tester(); System.out.println(“Value of a: ” + test.a); } } Output Inside super constructor Inside instance initializer block Inside constructor Value of a: 10 Print Page Previous Next Advertisements ”;
Java – Static Binding
Java – Static 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 Static Binding Static binding refers to the process in which linking between method call and method implementation is resolved at compile time. Static binding is also known as compile-time binding or early binding. Characteristics of Java Static Binding Linking − Linking between method call and method implementation is resolved at compile time. Resolve mechanism − Static binding uses type of the class and fields to resolve binding. Example − Method overloading is the example of Static binding. Type of Methods − private, final and static methods and variables uses static binding. Example of Java Static Binding In this example, we”ve created a Calculator class having two static methods with same name but different arguments to add two and three int values respectively. In main() method, we”re calling these methods and printing the result. Based on the number of arguments passed, compiler decides the method using static binding which method is to be called and result is printed accordingly. package com.tutorialspoint; class Calculator{ public static int add(int a, int b){ return a + b; } public static int add(int a, int b, int c){ return a + b + c; } } public class Tester { public static void main(String args[]){ System.out.println(Calculator.add(20, 40)); System.out.println(Calculator.add(40, 50, 60)); } } Output 60 150 Java Static Binding: More Examples Example 1 In this example, we”ve created a Calculator class having two non-static methods with same name but different arguments to add two and three int values respectively. In main() method, we”re calling these methods using object of Calculator class and printing the result. Based on the number of arguments passed, compiler decides the method using static binding which method is to be called and result is printed accordingly. package com.tutorialspoint; class Calculator{ public int add(int a, int b){ return a + b; } public int add(int a, int b, int c){ return a + b + c; } } public class Tester { public static void main(String args[]){ Calculator calculator = new Calculator(); System.out.println(calculator.add(20, 40)); System.out.println(calculator.add(40, 50, 60)); } } Output 60 150 Example 2 In this example, we”ve created a Calculator class having two non-static methods with same name but different types of arguments to add two int values and two double values respectively. In main() method, we”re calling these methods using object of Calculator class and printing the result. Based on the type of arguments passed, compiler decides the method using static binding which method is to be called and result is printed accordingly. package com.tutorialspoint; class Calculator{ public int add(int a, int b){ return a + b; } public double add(double a, double b){ return a + b; } } public class Tester { public static void main(String args[]){ Calculator calculator = new Calculator(); System.out.println(calculator.add(20, 40)); System.out.println(calculator.add(20.0, 40.0)); } } Output 60 60.0 Print Page Previous Next Advertisements ”;
Java – Loop Control
Java – Loop Control ”; Previous Next When Loops are Required? 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. Loop Statement 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 Loops Java programming language provides the following types of loops to handle the 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. 4 Enhanced for loop As of Java 5, the enhanced for loop was introduced. This is mainly used to traverse collection of elements including arrays. 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. In Java, the following are the loops control statements: 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. Print Page Previous Next Advertisements ”;
Java – For Loops
Java – for Loop ”; Previous Next Java for Loop A for loop is a repetition control structure that allows you to efficiently write a loop that needs to be executed a specific number of times. A for loop is useful when you know how many times a task is to be repeated. Just like the while loop, the for loop is also an entry control loop where the given condition executes first. Syntax of for Loop The syntax of a for loop is − for(initialization; Boolean_expression; update) { // Statements } Parts of Java For Loop In Java, the for loop is constructed (implemented) using three parts. The following are the parts of a for loop in Java – Initialization – Contains the initialization statement (s) of the loop counter. Boolean expression – Contains the condition to be tested. Body – Contains the statements to be iterated till the given Boolean expression is true, also to update the loop counter. Execution Process of a for Loop Here is the flow of control in a for loop − The initialization step is executed first, and only once. This step allows you to declare and initialize any loop control variables and this step ends with a semi colon (;). Next, the Boolean expression is evaluated. If it is true, the body of the loop is executed. If it is false, the body of the loop will not be executed and control jumps to the next statement past the for loop. After the body of the for loop gets executed, the control jumps back up to the update statement. This statement allows you to update any loop control variables. This statement can be left blank with a semicolon at the end. The Boolean expression is now evaluated again. If it is true, the loop executes and the process repeats (body of loop, then update step, then Boolean expression). After the Boolean expression is false, the for loop terminates. Flow Diagram The following diagram shows the flow diagram (execution process) of a for loop in Java – Java for Loop Examples Example 1: Printing Numbers in a Range Using for Loop In this example, we”re showing the use of a for loop to print numbers starting from 10 to 19. Here we”ve initialized an int variable x with a value of 10 within initialization blook of for loop. Then in expression block, we”re checking x as less than 20, and in the end under update block, we”re incrementing x by 1. Within body of for loop, we”re printing the value of x. For 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[]) { for(int x = 10; x < 20; x = x + 1) { System.out.print(“value of 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 value of x : 15 value of x : 16 value of x : 17 value of x : 18 value of x : 19 Example 2: Printing Array Elements Using for Loop In this example, we”re showing the use of a for 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 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 index becomes same as array size, for loop exits 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++) { System.out.print(“value of item : ” + numbers[index] ); System.out.print(“n”); } } } Output value of item : 10 value of item : 20 value of item : 30 value of item : 40 value of item : 50 Java Infinite for Loop An infinite loop never ends unless you stop manually by pressing CTRL + C. To implement an infinite for loop either use such a condition that is always true or directly use true as the condition. Example: Implementing Infinite for Loop In this example, we”re showing the infinite loop using for 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; for( ;; ) { System.out.print(“value of x : ” + x ); x++; 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 … ctrl+c Nested for Loop in Java A nested for loop is a for loop containing another for loop inside it. Example: Print Tables from 1 to 10 Using Nested for Loop In this example, we are printing tables of the numbers from 1 to 10. public class Main { public static void main(String[] args) { // Implementing nested for loop // Initializing loop counters int num = 1; int i = 1; // outer for loop for (num = 1; num <= 10; num++) { //inner for loop System.out.print(“Table of ” + num + ” is : “); for (i = 1; i <= 10; i++) { // printing table System.out.print(num * i + ” “); } // printing a new line System.out.println(); } } } Output Table of 1 is : 1 2 3 4 5 6 7 8 9 10 Table of 2 is : 2 4 6 8 10 12 14 16 18 20 Table of 3 is : 3 6 9 12 15 18 21 24 27 30 Table of 4
Java – Environment Setup
Java – Environment Setup ”; Previous Next Set Up Your Java Development Environment If you want to set up your own environment for Java programming language, then this tutorial guides you through the whole process. Please follow the steps given below to set up your Java environment. Java SE is available for download for free. To download click here, please download a version compatible with your operating system. Follow the instructions to download Java, and run the .exe to install Java on your machine. Once you have installed Java on your machine, you would need to set environment variables to point to correct installation directories. Setting Up the Environment Path for Windows 2000/XP Assuming you have installed Java in c:Program Filesjavajdk directory. Below are the steps to set up the Java environment path for Windows 2000/XP: Right-click on ”My Computer” and select ”Properties”. Click on the ”Environment variables” button under the ”Advanced” tab. Now, edit the ”Path” variable and add the path to the Java executable directory at the end of it. For example, if the path is currently set to C:WindowsSystem32, then edit it the following way C:WindowsSystem32;c:Program Filesjavajdkbin. Setting Up the Environment Path for Windows 95/98/ME Assuming you have installed Java in c:Program Filesjavajdk directory. Below are the steps to set up the Java environment path for Windows 95/98/ME: Edit the ”C:autoexec.bat” file and add the following line at the end −SET PATH=%PATH%;C:Program Filesjavajdkbin Setting Up the Environment Path for Linux, UNIX, Solaris, FreeBSD Environment variable PATH should be set to point to where the Java binaries have been installed. Refer to your shell documentation if you have trouble doing this. For example, if you use bash as your shell, then you would add the following line at the end of your .bashrc − export PATH=/path/to/java:$PATH” Online Java Compiler We have set up the Java Programming environment online, so that you can compile and execute all the available examples online. It gives you confidence in what you are reading and enables you to verify the programs with different options. Feel free to modify any example and execute it online. Try the following example using Run & Edit button available at the top right corner of the above sample code box − public class MyFirstJavaProgram { public static void main(String []args) { System.out.println(“Hello World”); } } For most of the examples given in this tutorial, you will find a Run & Edit option in our website code sections at the top right corner that will take you to the Online Java Compiler. So just make use of it and enjoy your learning. Popular Java Editors To write Java programs, you need a text editor. There are even more sophisticated IDEs available in the market. The most popular ones are briefly described below − Notepad − On Windows machine, you can use any simple text editor like Notepad (recommended for this tutorial) or WordPad. Notepad++ is also a free text editor which enhanced facilities. Netbeans − It is a Java IDE that is open-source and free which can be downloaded from www.netbeans.org/index.html. Eclipse − It is also a Java IDE developed by the Eclipse open-source community and can be downloaded from www.eclipse.org. IDE or Integrated Development Environment, provides all common tools and facilities to aid in programming, such as source code editor, build tools and debuggers etc. What is Next? Next chapter will teach you how to write and run your first Java program and some of the important basic syntaxes in Java needed for developing applications. Print Page Previous Next Advertisements ”;