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 ”;

Java – Type Casting

Java – Type Casting ”; Previous Next Java Type Casting (Type Conversion) Type casting is a technique that is used either by the compiler or a programmer to convert one data type to another. For example, converting int to double, double to int, short to int, etc. Type typing is also known as Type conversion. There are two types of cast typing allowed in Java programming: Widening type casting Narrowing type casting Widening Type Casting Widening Type Casting is also known as implicit type casting in which a smaller type is converted into a larger type, it is done by the compiler automatically. Here is the hierarchy of widening type casting in Java: byte > short > char > int > long > float > double The compiler plays a role in the type conversion but not the programmers. It changes the type of the variables at the compile time. Also, type conversion occurs from the small data type to large data type only. Example 1: Widening Type Casting In the example below, we demonstrated that we can get an error when the compiler tries to convert a large data type to a small data type. Here, we created the num1 integer and num2 double variable. The sum of num1 and num2 will be double, and when we try to store it to the sum of the int type, the compiler gives an error. package com.tutorialspoint; public class Tester { // Main driver method public static void main(String[] args) { // Define int variables int num1 = 5004; double num2 = 2.5; int sum = num1 + num2; // show output System.out.println(“The sum of ” + num1 + ” and ” + num2 + ” is ” + sum); } } Compile and run Tester. This will produce the following result − Output Exception in thread “main” java.lang.Error: Unresolved compilation problem: Type mismatch: cannot convert from double to int at com.tutorialspoint.Tester.main(Tester.java:9) Example 2: Widening Type Casting In the example below, we created the num1 and num2 variables as same in the first example. We store the sum of both numbers in the sum variable of double type. In the output, we can observe the sum of double type. package com.tutorialspoint; public class Tester { // Main driver method public static void main(String[] args) { // Define int variables int num1 = 5004; double num2 = 2.5; double sum = num1 + num2; // show output System.out.println(“The sum of ” + num1 + ” and ” + num2 + ” is ” + sum); } } Compile and run Tester. This will produce the following result − Output The sum of 5004 and 2.5 is 5006.5 Narrowing Type Casting Narrowing type casting is also known as explicit type casting or explicit type conversion which is done by the programmer manually. In the narrowing type casting a larger type can be converted into a smaller type. When a programmer changes the variable type while writing the code. We can use the cast operator to change the type of the variable. For example, double to int or int to double. Syntax Below is the syntax for narrowing type casting i.e., to manually type conversion: double doubleNum = (double) num; The above code statement will convert the variable to double type. Example: Narrowing Type Casting In the example below, we define the num variable of integer type and initialize it with the value. Also, we define the doubleNum variable of double type and store the num variable”s value after converting it to the double. Next, We created the ”convertedInt” integer type variable and stored the double value after type casting to int. In the output, we can observe the value of the double and int variables. package com.tutorialspoint; public class Tester { // Main driver method public static void main(String[] args) { // Define int variable int num = 5004; // Type casting int to double double doubleNum = (double) num; // show output System.out.println(“The value of ” + num + ” after converting to the double is ” + doubleNum); // Type casting double to int int convertedInt = (int) doubleNum; // show output System.out.println(“The value of ” + doubleNum + ” after converting to the int again is ” + convertedInt); } } Compile and run Tester. This will produce the following result − Output The value of 5004 after converting to the double is 5004.0 The value of 5004.0 after converting to the int again is 5004 Print Page Previous Next Advertisements ”;

Java – Home

Java Tutorial Table of content What is Java? Java First Example Online Java Compiler Java Features Java Applications Java Jobs & Opportunities Why to Learn Java? Who Should Learn Java Prerequisites to Learn Java Java Online Quizzes Java Examples Getting Started Java Practices Java References Java Certification Java FAQs Job Search PDF Version Quick Guide Resources Discussion Java Tutorial This Java tutorial has been written for beginners to advanced programmers who are striving to learn Java Programming. We have provided numerious practical examples to explain the concepts in simple and easy steps. This tutorial has been prepared and reviewed by experienced Java Programmers at Tutorials Point and best effort has been put to make it useful for the students and Java developers. After completing this tutorial, you will find yourself at a moderate level of expertise in Java Programming, from where you can elevate yourself to the next levels. What is Java? Java is a popular high-level, object-oriented programming language, which was originally developed by Sun Microsystems and released in 1995. Currently, Java is owned by Oracle and more than 3 billion devices run Java. Java runs on a variety of platforms, such as Windows, Mac OS, and the various versions of UNIX. Today Java is being used to develop numerous types of software applications including Desktop Apps, Mobile apps, Web apps, Games, and much more. Java is a general-purpose programming language intended to let programmers Write Once, Run Anywhere (WORA). This means that compiled Java code can run on all platforms that support Java without the need to recompile. In this tutorial, you will learn everything about Java starting from basics to advanced concepts such as overview, history, installations, basic input/output, conditional & control statements, arrays, classes, inheritances, method overloading & overriding, exceptional handling, exception handling, and many more. Java First Example The first example in Java is to print “Hello, World!” on the screen. Let”s have a quick look at the first examples in Java programming example.: public class MyFirstJavaProgram { /* This is my first java program. * This will print ”Hello, World!” as the output */ public static void main(String []args) { System.out.println(“Hello, World!”); // prints Hello, World! } } Online Java Compiler Our Java programming tutorial provides various examples to explain the concepts. To compile and execute the given Java programming examples in your browser itself, we have provided Online Java Compiler. You can Edit and Execute almost all the examples directly from your browser without the need to set up your development environment. Try to click the icon to run the following Java code to print conventional “Hello, World!” using Java Programming. Below code box allows you to change the value of the code. So, please try to change the value inside println() and run it again to verify the result. public class MyFirstJavaProgram { /* This is my first java program. * This will print ”Hello, World!” as the output */ public static void main(String []args) { System.out.println(“Hello, World!”); // prints Hello, World! } } Java Features Java is a feature-rich language. Java is evolving continuously with every update and updates are coming after every six months. Following are some of the main features of Java language – Object Oriented: Java is a pure object-oriented language and everything in Java is an object. Java supports OOPS principles like Inheritance, Encapsulation, Polymorphism, Classes , and so on. Java itself can be extended as well being based on an object model. Platform Independent: Java code is platform independent. A Java code is not compiled into machine-specific code, it is compiled into a platform-neutral byte code. This byte code is executed by JVM which runs the code on the underlying platform. This capability makes Java a Write Once Run Anywhere language. Easy To Learn: Java inherits features from C, and C++ and developers can easily learn Java if they know any of the C or C++ language. Even for someone new to computer languages, java is very easy to learn from scratch. Secure: Java is secure by architecture. A developer is not required to directly interact with underlying memory or Operating System. Java provides automatic garbage collection so developers are not required to worry about memory leaks, management, etc. Architectural-Neutral: Java byte code can be executed on any kind of processor. JRE automatically handles the code execution on different types of processors. Portable – A Java code written on a windows machine can be executed without any code change on MacOS and vice versa. There is no need to make any operating system-specific code changes. Robust – Java is a very robust language with very strong compile-time error checks, strict type checking, and runtime exception handling. Multithreading – Java provides inbuilt support for multiprocessing and multithreading. Java provides thread handling, monitors, deadlock handling, racing conditions, etc. High Performance – Java although being interpreted, still is very performant. JIT (Just In Time) compiler helps in improving performance. Distributed – Java is designed for distributed systems and is the most popular language for developing internet-based applications as the internet is a distributed environment. Java Applications Since Java supports object-oriented features and is platform-independent, it is extensively used in various fields. Listed below are a few areas where Java is used – Enterprise solutions Game development Secured web development Embedded systems Mobile application development Big Data Applications, and many more. Java Jobs & Opportunities Java is very high in demand and all the major companies are recruiting Java Programmers to develop their Desktop, Web and Mobile applications. Today a Java Programmer with 3-5 years of experience is asking for around $120,000 annual package and this is the most demanding programming language in America. Though it can vary depending on the location of the Job. Following are the great companies who are using Java and they need good Java Programmers: Google Microsoft Facebook IBM Amazon Netflix Pinterest Uber JetBrains Many more… So, you could be the next potential employee for any of these major companies. We

Java – Basic Operators

Java – Basic Operators ”; Previous Next Java operators are the symbols that are used to perform various operations on variables and values. By using these operators, we can perform operations like addition, subtraction, checking less than or greater than, etc. There are different types of operators in Java, we have listed them below − Arithmetic Operators Relational Operators Bitwise Operators Logical Operators Assignment Operators Misc Operators Java Arithmetic Operators Arithmetic operators are used in mathematical expressions in the same way that they are used in algebra. The following table lists the arithmetic operators − Assume integer variable A holds 10 and variable B holds 20, then − Show Examples Operator Description Example &plus; (Addition) Adds values on either side of the operator. A &plus; B will give 30 – (Subtraction) Subtracts right-hand operand from left-hand operand. A – B will give -10 &ast; (Multiplication) Multiplies values on either side of the operator. A &ast; B will give 200 / (Division) Divides left-hand operand by right-hand operand. B / A will give 2 % (Modulus) Divides left-hand operand by right-hand operand and returns remainder. B % A will give 0 &plus;&plus; (Increment) Increases the value of operand by 1. B&plus;&plus; gives 21 — (Decrement) Decreases the value of operand by 1. B– gives 19 Java Relational Operators There are following relational operators supported by Java language. Assume variable A holds 10 and variable B holds 20, then − Show Examples Operator Description Example == (equal to) Checks if the values of two operands are equal or not, if yes then condition becomes true. (A == B) is not true. != (not equal to) Checks if the values of two operands are equal or not, if values are not equal then condition becomes true. (A != B) is true. > (greater than) Checks if the value of left operand is greater than the value of right operand, if yes then condition becomes true. (A > B) is not true. < (less than) Checks if the value of left operand is less than the value of right operand, if yes then condition becomes true. (A < B) is true. >= (greater than or equal to) Checks if the value of left operand is greater than or equal to the value of right operand, if yes then condition becomes true. (A >= B) is not true. <= (less than or equal to) Checks if the value of left operand is less than or equal to the value of right operand, if yes then condition becomes true. (A <= B) is true. Java Bitwise Operators Java defines several bitwise operators, which can be applied to the integer types, long, int, short, char, and byte. Bitwise operator works on bits and performs bit-by-bit operation. Assume if a = 60 and b = 13; now in binary format they will be as follows − a = 0011 1100 b = 0000 1101 a&b = 0000 1100 a|b = 0011 1101 a^b = 0011 0001 ~a  = 1100 0011 The following table lists the bitwise operators − Assume integer variable A holds 60 and variable B holds 13 then − Show Examples Operator Description Example & (bitwise and) Binary AND Operator copies a bit to the result if it exists in both operands. (A & B) will give 12 which is 0000 1100 | (bitwise or) Binary OR Operator copies a bit if it exists in either operand. (A | B) will give 61 which is 0011 1101 ^ (bitwise XOR) Binary XOR Operator copies the bit if it is set in one operand but not both. (A ^ B) will give 49 which is 0011 0001 ⁓ (bitwise compliment) Binary Ones Complement Operator is unary and has the effect of ”flipping” bits. (⁓A ) will give -61 which is 1100 0011 in 2”s complement form due to a signed binary number. << (left shift) Binary Left Shift Operator. The left operands value is moved left by the number of bits specified by the right operand. A << 2 will give 240 which is 1111 0000 >> (right shift) Binary Right Shift Operator. The left operands value is moved right by the number of bits specified by the right operand. A >> 2 will give 15 which is 1111 >>> (zero fill right shift) Shift right zero fill operator. The left operands value is moved right by the number of bits specified by the right operand and shifted values are filled up with zeros. A >>>2 will give 15 which is 0000 1111 Java Logical Operators The following table lists the logical operators − Assume Boolean variables A holds true and variable B holds false, then − Show Examples Operator Description Example && (logical and) Called Logical AND operator. If both the operands are non-zero, then the condition becomes true. (A && B) is false || (logical or) Called Logical OR Operator. If any of the two operands are non-zero, then the condition becomes true. (A || B) is true ! (logical not) Called Logical NOT Operator. Use to reverses the logical state of its operand. If a condition is true then Logical NOT operator will make false. !(A && B) is true The Assignment Operators Following are the assignment operators supported by Java language − Show Examples Operator Description Example = Simple assignment operator. Assigns values from right side operands to left side operand. C = A &plus; B will assign value of A &plus; B into C &plus;= Add AND assignment operator. It adds right operand to the left operand and assign the result to left operand. C &plus;= A is equivalent to C = C &plus; A -= Subtract AND assignment operator. It subtracts right operand from the left operand and assign the result to left operand. C -= A is equivalent to C = C − A &ast;= Multiply AND assignment operator. It multiplies right operand with the left operand and assign the result to left operand. C &ast;=