Unit - 1
Introduction
Java is a robust, cross platform high level language. Java is based on object oriented programming which means it is designed using the concepts of object and classes.
Whenever a programmer writes a code in Java, that code can be available to run on any platform like LINUX, Windows or Mac OS. Also, this language is free to access for all users.
Most of the syntax in Java is derived from C and C++ programming language but eliminates the concept of pointers.
Why Java?
Java was intended to be not difficult to utilize and is hence simple to compose, compile, troubleshoot, and learn in comparison to other programming language.
Since Java is object-oriented, this permits you to make flexible program and reusable code Probably the main motivation why Java is so well known is one of its feature platforms independent.
Programs written in Java can run on numerous computer; as long as the computer has a Java Runtime Environment (JRE) installed, which allows a Java program to run on it.
Almost all kinds of computers are flexible with a JRE including computers running on Windows, Macintosh computers, Unix or Linux computers, and huge mainframe server computers, including mobile phones.
Since Java is from such a long time, probably the greatest organizations in the world are constructed utilizing the language such as Numerous banks, retailers, insurance agencies, etc.
History behind Java
Nowadays Java is one such language which is used worldwide including internet, mobiles, games, e-commerce etc.
Let’s have a look at the history of Java and see how it comes so far:
- In June 1991, the first project written in Java is initiated by a team of three members having James Gosling, Mike Sheridan and Patrick Naughton. This team of sun engineers become famous as Green Team.
- The initial purpose of using Java was for small, embedded systems such as TV set-top boxes.
- At first it was referred as Green talk by James Gosling and the file extension for it was decided is .gt.
- Then James Gosling referred it as Oak which was developed as a part of Green project.
- Since Oak was already a trademark used by Oak Technologies, so in 1995 it was renamed as Java.
- Before selecting the name Java the team had huge discussion among names suggested like dynamic, revolutionary, silk, jolt, DNA etc. Team wants to select such a name which reflects the nature of technology. So finally the team members preferred Java over other names.
- The first public implementation of Java was made in 1995 as Java 1.0 by Sun. It is based on the concept of Write once and Run Anywhere on any platforms.
- In 2006, Sun finally released Java’s some code as free and open source software Under GNU General Public License (GPL).
- And finally, in 2007 Sun declared Java’s all core code free and open source so that anyone can use it without any restrictions.
Different versions of Java
● JDK Alpha and Beta: The first version which was released in 1995 as Java Alpha and Beta was highly unstable because of its APIs and ABIs.
● JDK 1.0: The first stable version came on 23 January 1996 JDK 1.0.2 also known as Java 1.
● JDK 1.1: This version was released on 19 February 1997 which includes new features like AWT event model, addition of inner classes, JavaBeans, JDBC, RMI, reflection and JIT.
● J2SE 1.2: This version release on 8 December 1998 with the codename playground. This version a signification release by Java as its size was three times of the Java platform. This version consists of 1520 classes in 59 packages. Some new features added like strictfp keyword, Swing graphical API, Java plug-in, Java IDl and collections.
● J2SE 1.3: This version was one of the famous version came on 8 May 2000 with codename Kestrel. The main changes done in this version were inclusion of HotSpot JVM, modified RMI compatible with COBRA, Java Naming and Directory Interface (JNDI) libraries, Java Platform Debugger Architecture (JPDA) and Java Sound.
● J2SE 1.4: This version was the first version to release under Java Community Process as JSR on 6 February 2002. The major changes in this version include: addition of assert keyword and library improvement (such as exception chaining, IPv6 support, Non-blocking I/O etc).
● J2SE 5.0: This version was initially named as 1.5 but further changed to 5.0 to show the maturity, stability, scalability and security. This version was released on 30 September 2004 with code name tiger. New language features that were added like generics, metadata, autoboxing, enumerations, Varags, improved semantics and static imports.
● Java SE 6: Released on 11 December 2006 with codename mustang. Sun released this version as Java SE instead of J2SE. Some of the major changes include in this version were scripting language support, JDBC 4.0 support Java compiler API, support for Pluggable annotations etc.
● Java SE 7: This update with codename dolphin was released on 7 July 2011. Major additions in Java 7 were JVM support for dynamic languages, compressed 64-bit pointers, concurrency utilities under JSR, upstream updates to XML, java deployment rule sets.
● Java SE 8: This version was released on 18 March 2014 with codename spider. Some of the major changes that were done in Java SE 8 are support for lambda expression, JavaScript embed into applications, repeating annotations, launching of JavaFX applications and permanent generation removal.
● Java SE 9: The release of this version was delayed many time and finally released on 21 September 2017. This version provides improved support to native code integration, multi-gigabyte heaps, garbage collector and self tuning JVM.
● Java SE 10: Java SE 10 was released on 20 March 2018. This version was released with aim to remove primitive data types and support to 64 bit addressable arrays with some additional new features. These features were local variable type inference, application class data sharing, parallel full GC for GI, root certificates and many more.
● Java SE 11: This version also known as JDK 11 was released on 25 September 2018. Still its bug fixes are going on.
● Java SE 12: This was version was released 19 March 2019 with some fewer changes.
Features of Java
● Object Oriented: Java is a complete object oriented language. This means that everything in Java revolves around the use of Objects.
● Secure: Java is a very secure language; one of the main reasons is the lack of pointers. Virus free software’s can be developed using Java programming constructs.
● Robust: Java is a very robust language because of features like automatic garbage collection, memory management, exception handling, etc.
● Portable: One of the very important features of Java is that can be used on any platform without any problems. This means that it allows you to run the Java Bytecode on any platform.
● Simple: Java is a simple language because of its ease of use and less complicated features.
● Platform Independent: Java is a ‘write’ once, ‘run’ anywhere language, which means that once written, it has the capability to be executed on any machine that has Java Runtime Environment (JRE).
Key takeaway
Java is a robust, cross platform high level language. Java is based on object oriented programming which means it is designed using the concepts of object and classes.
The Java Virtual Machine's instruction set is known as Java bytecode. It functions similarly to an assembler, which is an alias for C++ code. Java bytecode is generated as soon as a java programme is compiled. Java bytecode, to put it another way, is machine code in the form of a.class file. We can achieve platform independence in Java by using java bytecode.
How does it work?
When we develop a Java programme, the compiler first compiles it and generates bytecode for it. We can run this.class file on any other platform if we want to. The Java Virtual Machine, not the processor in question, now runs the bytecode generated after the first compilation. This effectively means that on whatever platform where we wish to run our code, we only need a minimal java installation. The Java Virtual Machine makes the resources needed to run the bytecode available by instructing the processor to allocate them. Because JVMs are stack-based, they must stack implementations in order to read the codes.
Fig 1: Working of byte code
Advantages
One of the main reasons James Gosling founded Java was to achieve platform independence, and it is this implementation of bytecode that allows us to do so. As a result, bytecode is an essential part of each Java application. The JVM's set of instructions may vary from system to system, but all can decode bytecode. Keep in mind that bytecodes are non-runnable programmes that require on the presence of an interpreter to execute, which is where the JVM comes in.
Bytecode is a machine-level programming language that runs on the Java Virtual Machine. When a class is loaded, it receives a stream of bytecode for each of its methods. The bytecode for that method is invoked whenever that method is called during the execution of a programme. Javac not only compiles a programme, but it also generates bytecode for it.
As a result, we've realised that Java's bytecode implementation makes it platform-independent. This contributes to Java's portability, which is lacking in languages like C and C++. Java's portability assures that it may be used on a wide range of platforms, including computers, mobile devices, servers, and more. Supporting this, Sun Microsystems captioned JAVA as "write once, read anywhere" or "WORA" in resonance to the bytecode interpretation.
Key takeaway
Java bytecode is generated as soon as a java programme is compiled. Java bytecode, to put it another way, is machine code in the form of a.class file. We can achieve platform independence in Java by using java bytecode.
JVM (Java Virtual Machine) is a program that gives us the flexibility to execute Java programs. It provides a runtime environment to execute the Java code or applications.
This is the reason why Java is said to platform independent language as it requires JVM on the system it runs its Java code.
JVM is also used to execute programs of other languages that are compiled to Bytecode.
JVM can also be describe as:
- A specification where JVM working is pre defined.
- An implementation like JRE (Java Runtime Environment) is required.
- Runtime Instance means wherever a program is run on command prompt using java command, an instance of JVM is created.
Significance of JVM
JVM is used for two primary functions
- It allows Java programs to use the concept of “Write Once and Run Anywhere”.
- It is utilized to manage and optimize memory usage for programs.
Architecture of JVM
Java applications require a run-time engine which is provided by JVM. The main method of Java program is called by JVM. JVM is a subsystem of JRE (Java Runtime Environment).
Let’s see the internal architecture of JVM as shown in the figure below:
Fig 2: Architecture of JVM
- Class Loader: This part is used to load class files. There are three major functions of class loader as Loading, Linking and Initialization.
- Method Area: Structure of class like metadata, the constant runtime pool, and the code for methods are stored method area.
- Heap: Heap is the memory where all the objects, instance variables and arrays are stored. This is a shared memory which is accessed by multiple threads.
- JVM Language Stacks: These hold the local data variables and their results. Each thread has their own JVM stack used to store data.
- PC Registers: The currently running IVM instructions are stored in PC Registers. In Java, every thread has its their own PC register.
- Native Method Stacks: It hold the instruction of native code depending on their native library.
- Execution Engine: This engine is used to test the software, hardware or complete system. It doesn’t contain any information about the tested product.
- Native Method Interface: It is a programming interface. It allows Java code to call by libraries and native applications.
- Native Method Libraries: It consists of native libraries which are required by execution engine.
Key takeaway
JVM (Java Virtual Machine) is a program that gives us the flexibility to execute Java programs. It provides a runtime environment to execute the Java code or applications.
The term JDK stands for Java Development Kit. The Java Development Kit (JDK) is a software development environment for creating Java programmes and applets. It is a real thing. It includes JRE as well as developer tools.
The Java Development Kit (JDK) is a cross-platform software development environment that includes a set of tools and libraries for creating Java-based applications and applets. Along with the JVM (Java Virtual Machine) and the JRE (Java Runtime Environment), it is a key package used in Java (Java Runtime Environment).
Beginners frequently confuse JRE and JDK; nevertheless, if all you want to do is launch Java programmes on your machine, you may do so with ease using Java Runtime Environment. However, if you want to create a Java-based software programme, you'll probably need some extra tools, such as JDK, in addition to JRE.
JDK is an implementation of any of Oracle Corporation's Java Platforms, as listed below:
● Standard Edition Java Platform
● Enterprise Edition Java Platform
● Micro Edition Java Platform
To finish the creation of a Java application, the JDK contains a private Java Virtual Machine (JVM) and a few other resources such as an interpreter/loader (java), a compiler (javac), an archiver (jar), a documentation generator (Javadoc), and so on.
Fig 3: JDK
Components of JDK in Java
The following is a list of the JDK's core components in Java.
● java - In older SUN Java, it serves as a deployment launcher. It interprets the source code compiled by the javac compiler after loading the class files.
● javac - The java compiler is used to transform the source code to bytecode, as specified by javac.
● javadoc - The javadoc tool creates documentation for comments contributed to source code.
● jar - The jar aids in the management of jar files in the package library by the archives.
● jps - Java Virtual Machine Process Status Tool is abbreviated as jps. It keeps track of the active JVMs for the current programme.
● appletviewer - The appletviewer is a programme that allows you to run and debug Java applets without using the internet.
● idlj - An IDL-to-Java compiler converts a Java IDL file into Java bindings.
● javap - The javap performs the function of a file disassembler.
● JConsole - JConsole is a Java management and monitoring application.
● javah - The javah is a stub-generator, and native methods are written with C-Header.
● javaws - For JNLP apps, javaws serves as a Web Start launcher.
● jhat - The jhat is a tool for heap analysis.
● jmc - The abbreviation jmc stands for Java Mission Control.
Why JDK used?
The Java Development Kit includes a number of tools as well as knowledge on Java development. Downloading JDK software and blending it with the classpath is all it takes to deploy Java software. After downloading and installing JDK, the only method to run the software is to select the correct version of Java. Although Java 8 is the most widely used version, Java 10 is the most recent version that is also available online.
JDK is a collection of directories that are used to implement the Java platform standard, including class libraries and the compiler. It's also referred to as the JRE's superset.
Key takeaway
The term JDK stands for Java Development Kit. The Java Development Kit (JDK) is a software development environment for creating Java programmes and applets. It is a real thing. It includes JRE as well as developer tools.
Various data types are used in Java. These data types are used to represent the memory allocation. Every data type has a different amount of memory allocation associated with it.
They are also called as primitive data types in Java.
- Byte: The byte data type is an 8-bit signed two's complement integer. Range is -128 to 127.
- Short: The short data type is a 16-bit signed two's complement integer. Range is -32,768 to 32,767 (inclusive).
- Int: The int data type is a 32-bit signed two's complement integer. Range is -231 to 231-1.
- Long: The long data type is a 64-bit two's complement integer. Range is -263 to 263-1.
- Float: The float data type is a 32-bit IEEE 754 floating point.
- Double: The double data type is a 64-bit IEEE 754 floating point.
- Boolean: true and false are two possible values of the boolean data type.
- Char: The char data type is a single 16-bit Unicode character. Range is '\u0000' (or 0) to '\uffff'.
Key takeaway
Various data types are used in Java. These data types are used to represent the memory allocation. Every data type has a different amount of memory allocation associated with it.
Operators are special symbols that are used to perform some specific operations on variables and values. For example +, *, -, /, <, > etc.
Since there are so many operators available, system has decided some precedence among them. The precedence of operators helps the compiler to decide which operator will perform first in case of availability of multiple operators.
The below table shows the precedence of operator.
Operators | Precedence |
Postfix | Expr++, expr-- |
Unary | ++expr, --expr, +expr, -expr, ~! |
Multiplicative | * / % |
Additive | + - |
Shift | << >> >>> |
Relational | < > <= >= instanceof |
Equality | == != |
Bitwise AND | & |
Bitwise exclusive OR | ^ |
Bitwise inclusive OR | | |
Logical AND | && |
Logical OR | || |
Ternary | ? : |
Assignment | = += -= *= /= %= &= ^= |= <<= >>= >>>= |
The precedence of the operator in the table is given as top operator has precedence and last operator has low precedence.
Operator having higher precedence will be evaluated by the compiler first. While operators on the same line have same precedence.
Different types of Operators
Following are various types of operators in Java:
- Arithmetic Operators
- Unary Operators
- Relational Operators
- Logical Operators
- Boolean Operators
- Bitwise Operators
- Ternary Operators
- New Operators
- Cast Operators
1. Arithmetic Operators: They are the type of operators that perform an operation on two operands.
+, -, *, /, % are various Arithmetic operators
+ is the Addition operator
- is the Subtraction operator
* is the Multiplication operator
/ is the division operator
% is the remainder operator also called as modulus operator
Lets see a program on this concept
Code:
Class ArithmeticOperators{
Public static void main(String[] args) {
Double n1 = 12.5, n2 = 3.5, add, subtract, multiply, divide, mod;
// This is how you use the addition operator
Add = n1 + n2;
System.out.println("n1 + n2 = " +add);
// This is how you use the subtraction operator
Subtract = n1 - n2;
System.out.println("n1 - n2 = " +subtract);
// This is how you use the multiplication operator
Multiply = n1 * n2;
System.out.println("n1 * n2 = " +multiply);
// This is how you use the division operator
Divide = n1 / n2;
System.out.println("n1 / n2 = " +divide);
// This is how you use the mod or remainder operator
Mod = n1 % n2;
System.out.println("n1 % n2 = " +mod);
}
}
Output:
2. Unary Operators: They are the types of operators that perform an operation on one operand.
+ is the Unary Plus Operator
- is the Unary Minus Operator. It inverts sign of an expression
++ is the Increment Operator. Increments value by 1
-- is the decrement Operator. Decreases value by 1
! is the Logical complement Operator. It inverts the value of a boolean, i.e. true to false and false to true
Program:
Class UnaryOperator {
Public static void main(String[] args) {
Double number = 5.2, unaryPlus, unaryMinus, increment, decrement, unaryLogical;
Boolean flag = false;
System.out.println("+ unaryPlus = " + +number);
System.out.println("- unaryMinus= " + -number);
System.out.println("++ increment = " + ++number);
System.out.println("-- decrement= " + --number);
System.out.println("! unaryLogical: !flag = " + !flag);
}
}
Output:
3. Relational Operators: Also called as equality and relational operators, these operators determine the relationship between the two operands.
== is the Equal to operator
!= is the Not equal to operator
> is the Greater than operator
>= is the Greater than or equal to operator
< is the Less than operator
<= is the Less than or equal to operator
Program:
Class RelationalOperators {
Public static void main(String args[]) {
Int x = 50;
Int y = 70;
System.out.println("x == y = " + (x == y) );
System.out.println("x != y = " + (x != y) );
System.out.println("x < y = " + (x < y) );
System.out.println("x > y = " + (x > y) );
System.out.println("y <= x = " + (y <= x) );
System.out.println("y >= x = " + (y >= x) );
}
}
Output:
4. Logical Operators: Also called as conditional operators, Logical operators operate on boolean expressions. Various Logical operators are:
&& Conditional-AND, its true only if all boolean expressions are true
|| Conditional-OR, its true if either of the boolean expression is true
Program:
Class LogicalOperators{
Public static void main(String args[]) {
Boolean n = false;
Boolean m = true;
System.out.println("m && n = " + (m&&n));
System.out.println("!(m && n) = " + !(m && n));
System.out.println("m || n = " + (m||n) );
}
}
Output:
5. Boolean Operators: These operators operate only on Boolean Operands
& denotes the AND operator
| denotes the OR operator
^ denotes the XOR operator
! denotes the NOT operator
!= denotes the NOT EQUAL TO operator
== denotes the EQUAL TO operator
Program:
Class BooleanOperators{
Public static void main(String args[]){
Boolean X = true;
Boolean Y = false;
System.out.println("X&Y = "+(X&Y));
System.out.println("X|Y = "+(X|Y));
System.out.println("X^Y = "+(X^Y));
System.out.println("!X = "+(!X));
System.out.println("X!=Y = "+(X!=Y));
System.out.println("X==Y = "+(X==Y));
System.out.println("(X|Y)&X = "+((X|Y)&X));
}
}
Output:
6. Bitwise Operators: They are used to perform bit shift operators in Java.
~ Unary bitwise complement
<< Signed left shift
>> Signed right shift
>>> Unsigned right shift
& Bitwise AND
^ Bitwise exclusive OR
| Bitwise inclusive OR
Program:
Class BitwiseOperators {
Public static void main(String[] args)
{
Int x = 5;
Int y = 7;
// bitwise AND 0101 & 0111=0101 = 5
System.out.println("x&y = " + (x & y));
// bitwise OR 0101 | 0111=0111 = 7
System.out.println("x|y = " + (x | y));
// bitwise XOR 0101 ^ 0111=0010 = 2
System.out.println("x^y = " + (x ^ y));
// bitwise AND ~0101=1010, will give 2's complement of 1010 = -6
System.out.println("~x = " + ~x);
// can be combined with assignment operator for shorthand assignment x=x&y
x &= y;
System.out.println("x= " + x);
}
}
Output:
7. Ternary Operators: It is the only operator that takes three operands. It can be used to replace if-else statements as well as switch statements.
Program:
Class TernaryOperator {
Public static void main(String[] args) {
Double num = -5.5;
String verdict;
Verdict = (num>0.0) ? "Positive" : "Not Positive";
System.out.println("The Number " +num+ " is " +verdict);
}
}
Output:
8. New Operator: The new operator instantiates a class by dynamically allocating (i.e., allocation at run time) memory for a new object and returning a reference to that memory.
Program:
Class Square
{
double squareSide;
}
public class NewOperator
{
Public static void main(String[] args)
{
Square s1 = new Square();
// assigning s2 to s1
Square s2 = s1;
s2.squareSide = 20;
System.out.println(s1.squareSide);
System.out.println(s2.squareSide);
}
}
Output:
M
Up casting: Java Virtual Machine (JVM) performs automatic conversion.
Byte => short => int => long => float => double
e.g. int j = 5;
Long i = j;
Down Casting: Also called as explicit casting, this can be best explained through an example.
e.g. int j = 5;
Long i = j;
Byte b1=j; //compile time error
Byte b2=(byte)j; //allowed. Explicit casting is done
Key takeaway
Operators are special symbols that are used to perform some specific operations on variables and values. For example +, *, -, /, <, > etc.
Java Control Structures
Java program or code is nothing but some set of instructions which are executed by compiler.
In certain applications or program a user needs to write some choices which are to be selected by the compiler based on the conditions.
However, Java provides us some statements for such situations known as control structures.
Control structures are used to change the execution path and also control the execution of instructions.
Java provides three types of control structures: Conditional, Loop/Iterators and Branching statements.
Different Types of Control statements
Java provides us three types of control structures:
● Conditional statements: These are used when we want to choose among two or more paths. Conditional statements are of three types in java: if/else/else if, ternary operator and switch.
● Loop/Iterators: Loops are used when we want to repeatedly run some part of the code. Java provides three types of loop: for, while and do while.
● Branching statements: These statements are used to alter the flow of control in loops. Branching statements are of two types: break and continue.
Conditional Statements
Conditional statements are used to choose the path for execution. These are of three types: if/else/else if, ternary and switch.
1. If statement
The simplest form of control structure is if statement. This statement checked a Boolean expression, if the expression value is true then the program enters a block of code; otherwise if Boolean expression value is false it skip if statement block.
Syntax of if statement is:
If(Boolean condition)
{
Line 1; //it will execute only when if statement holds true
}
Example
Public class Program {
Public static void main(String[] args)
{
Int a = 5;
Int b = 15;
If(a+b>=20)
{
System.out.println(“Output is true”);
}
}
}
Output:
Output is true
2. If-else statement
An extended version of if statement, which use a second block of code which is known as else block in the situation when if condition fails.
Syntax of if else statement:
If(Boolean condition)
{
Line 1; // it will execute only when if statement holds true
}
Else
{
Line 2; // it will execute only when if statement holds false
}
Example
Public class Program {
Public static void main(String[] args)
{
Int a = 5;
Int b = 15;
If(a+b>=20)
{
System.out.println(“if condition is true”);
}
Else
{
System.out.println(“if condition is false”);
}
}
}
Output:
If condition is true
3. If-else-if ladder or Nested if-else condition
In nested if-else condition first if condition is followed by many else-if conditions. In other way we can define it as a decision tree of if-else-if statement where we have to make multiple choices based on combination of conditions.
Syntax of nested if-else condition:
If(Boolean condition 1) {
Statement 1; //it will executes when condition 1 is true
}
Else if(Boolean condition 2) {
Statement 2; // it will executes when condition 2 is true
}
Else {
Statement 2; //it will executes when all the conditions are false
}
Example:
Public class Example {
Public static void main(String[] args) {
Int a = 15;
If(a < 10) {
System.out.println("a is less than 10");
}else if (a = 12) {
System.out.println("a is equal to 12");
}else if(a > 10) {
System.out.println("a is greater than 10");
}else {
System.out.println(a);
}
}
}
Output:
a is greater than 10
4. Ternary Condition
Ternary condition is an enhancement or shorthand to the if-else condition. The working of ternary and if-else condition is same.
Consider an example of if-else:
If (a > 2) {
System.out.println("a is higher than 2");
} else {
System.out.println("a is lower or equal to 2");
}
Now see the same code in ternary condition
System.out.println(a > 2 ? "a is higher than 2" : "a is lower or equal to 2");
5. Switch condition
Switch conditions in Java are almost same as nested if-else statement.
Switch conditions are designed using multiple blocks of codes known as cases. Among so many cases a single case is executed based on the condition mentioned in the switch.
They are simple to use in comparison to nested if-else. While writing switch statements few things need to be kept in mind:
● We cannot create duplicate case. Each case will be different.
● The variables we can use in case are int, short, byte, char or enumeration. Strings are also supported.
● If all cases fail, then only default statement will be executed.
● While using switch statement, we use break statement also. Break statement will terminate the execution after switch case is satisfied, otherwise next case will be executed.
● The case expression variable must be same as at the time of declaration.
Syntax of switch statement:
Switch (condition){
Case data1:
Statement 1;
Break;
.
.
.
Case dataN:
Statement N;
Break;
Default:
Default statement;
}
Example:
Class Student
Public static void main(String[] args) {
Int a = 2;
Switch (a){
Case 0:
System.out.println("value is 0");
Break;
Case 1:
System.out.println("value is 1");
Break;
Default:
System.out.println(a);
}
}
}
Loops/ Iterators
In programming, there are certain situations when we want our code to execute some instructions repeatedly until the desired condition is met.
The above given situation can be implemented using the concept of loop. Loops are used to repeat the same instruction many times in succession.
Java provides us three types of looping statements as:
- For loop,
- While loop and
- Do-while loop.
1. For loop
Just like C and C++, for loop in Java is also same. A for loop is used to execute a set of code several times.
For loop consists of three parts. First part is used to initialize the loop variable, second part contains the condition and the third part increment/decrement the variable. For loop is defined in a single line.
Syntax of for loop:
For(initialization, condition, increment or decrement)
{
//block of statements to be executed
}
Example
Class Example
{
Public static void main(String[] args)
{
Int s = 1;
For(int i = 1; i<=5; i++) {
s = s + i;
}
System.out.println("The sum = " + s);
}
}
Output:
The sum = 6
2. While loop
The while loop statement is also used to repeat the execution of code multiple times.
While loops are preferable to use when we don’t know the exact number of iterations to be done in advance.
Here the initialization of variable and increment/decrement is done outside the loop statement.
In while loop the condition is checked first, if the condition is true then only execution will be done inside the loop; otherwise outside loop statements will be executed.
While loops are also know as entry controlled loop.
Syntax of while loop
While(condition){
//looping statements
}
Example
Class Example {
Public static void main(String[] args) {
Int a = 1;
System.out.println("The list of first 5 numbers \n");
While(a<=5) {
System.out.println(a);
a = a+ 1;
}
}
}
Output:
The list of first 5 even numbers
1
2
3
4
5
3. Do-while loop
In do-while loop statements are executed first then the condition is evaluated at the end of the loop.
It can we use on those places where we want to execute the statements at least once.
The do-while loops are also known as the exit controlled loop.
Syntax of do-while loop:
Do
{
Statements
} while (condition);
Example
Class Example {
Public static void main(String[] args) {
Int a = 1;
System.out.println("The list of first 5 numbers \n");
Do {
System.out.println(a);
a = a+ 1;
} while(a<=5)
}
}
For-each
Since J2SE 5.0, the Java for-each loop, sometimes known as the extended for loop, has been available. It offers a different way to traverse an array or collection in Java. It is mostly used to traverse the items of an array or collection. The for-each loop has the advantage of removing the potential of problems and making the code more readable. The for-each loop gets its name from the fact that it goes over each element one by one.
The improved for loop has the disadvantage of not being able to explore the components in reverse order. Because it does not work on an index basis, you do not have the option to skip any element. Furthermore, you can't just go through the odd or even elements.
However, for traversing the items of an array or collection, the Java for-each loop is preferable since it makes the code more understandable.
Advantages
● It improves the readability of the code.
● It eliminates the risk of programming mistakes.
Syntax
The data type with the variable is followed by a colon (:), then array or collection in the Java for-each loop syntax.
For(data_type variable : array | collection){
//body of for-each loop
}
Limitations of for-each loop
Decision-making
- When you wish to change the array, for-each loops aren't the best choice:
For (int num : marks)
{
// only changes num, not the array element
Num = num*2;
}
2. Index is not kept in for-each loops. As a result, we can't get the array index using the For-Each loop.
For (int num : numbers)
{
If (num == target)
{
Return ???; // do not know the index of num
}
}
3. For-each iterates across the array in single steps alone.
// cannot be converted to a for-each loop
For (int i=numbers.length-1; i>0; i--)
{
System.out.println(numbers[i]);
}
4. Two decision-making statements cannot be processed by for-each at the same time.
// cannot be easily converted to a for-each loop
For (int i=0; i<numbers.length; i++)
{
If (numbers[i] == arr[i])
{ ...
}
}
5. In addition, for-each has a performance penalty when compared to ordinary iteration:
/*package whatever //do not write package name here */
Import java.io.*;
Import java.util.*;
Class GFG {
Public static void main (String[] args) {
List<Integer> list = new ArrayList<>();
Long startTime;
Long endTime;
For (int i = 0; i < 1000000; i++) {
List.add(i);
}
// Type 1
StartTime = Calendar.getInstance().getTimeInMillis();
For (int i : list) {
Int a = i;
}
EndTime = Calendar.getInstance().getTimeInMillis();
System.out.println("For each loop :: " + (endTime - startTime) + " ms");
// Type 2
StartTime = Calendar.getInstance().getTimeInMillis();
For (int j = 0; j < list.size(); j++) {
Int a = list.get(j);
}
EndTime = Calendar.getInstance().getTimeInMillis();
System.out.println("Using collection.size() :: " + (endTime - startTime) + " ms");
// Type 3
StartTime = Calendar.getInstance().getTimeInMillis();
Int size = list.size();
For (int j = 0; j < size; j++) {
Int a = list.get(j);
}
EndTime = Calendar.getInstance().getTimeInMillis();
System.out.println("By calculating collection.size() first :: " + (endTime - startTime) + " ms");
// Type 4
StartTime = Calendar.getInstance().getTimeInMillis();
For(int j = list.size()-1; j >= 0; j--) {
Int a = list.get(j);
}
EndTime = Calendar.getInstance().getTimeInMillis();
System.out.println("Using [int j = list.size(); j > size ; j--] :: " + (endTime - startTime) + " ms");
}
}
Jumping Statements
Jump statements are used to change the execution flow of the program to some other specific statements.
In Java there are two types of jump statements: break and continue.
1. Break statement
It is used to immediately terminate the execution of a loop and the control will be passing on to the next statement after the loop.
Break statement are always used inside a loop or switch statement, they cannot be used independently.
Example
Class Example {
Public static void main(String[] args) {
For(int a = 1; a<= 5; a++) {
System.out.println(a);
If(a==3) {
Break;
}
}
}
}
Output
1
2
3
2. Continue statement
Continue statements are used when we want to skip only specific part of the loop and jumps to the next instruction in the loop immediately, while break statement terminates the loop.
It can be used with for or while loop.
Example
Class Example
{
Public static void main(String arg[])
{
For(int x = 0; x <=3; x++)
{
If(x == 1)
Continue;
System.out.println("Number= " + x);
}
}
}
Output
Number = 0
Number = 2
Number = 3
Methods
In general, a method is a manner of accomplishing a goal. In Java, a method is a collection of instructions that accomplishes a specified goal. It ensures that code can be reused. Methods can also be used to easily alter code. We'll study what a method is in Java, the different sorts of methods, how to declare a method, and how to invoke a method in Java in this part.
What is a method in Java?
A method is a collection of statements or a series of statements organised together to conduct a specific task or action. It's a technique for making code more reusable. We create a method once and then use it repeatedly. We don't have to write code over and over again.
It also allows for easy code modification and readability by simply adding or removing code chunks. Only when we call or invoke the method is it executed.
Method Declaration
Method properties such as visibility, return-type, name, and parameters are all stated in the method declaration. As seen in the following diagram, it consists of six components known as method headers.
Fig 4: Method declaration
Method Signature: A method signature is a description of a method. It's included in the method declaration. It contains the method name as well as a list of parameters.
Access Specifier: The method's access specifier or modifier is the method's access type. It specifies the method's visibility. There are four different types of access specifiers in Java:
● public - When we utilise the public specifier in our application, all classes can access the method.
● private - The method is only accessible in the classes in which it is declared when we use a private access specifier.
● protected - The method is accessible within the same package or subclasses in a different package when we use the protected access specifier.
● default - When no access specifier is specified in the method declaration, Java uses the default access specifier. It is visible only from the same package only.
Return Type: The data type that the method returns is known as the return type. It could be a primitive data type, an object, a collection, or void, for example. The void keyword is used when a method does not return anything.
Method Name: It's a one-of-a-kind moniker that's used to specify a method's name. It must be appropriate for the method's functionality. If we're making a method for subtracting two numbers, the name of the method must be subtraction (). The name of a method is used to call it.
Parameter List: It consists of a list of parameters separated by a comma and contained in parentheses. It specifies the data type as well as the name of the variable. Leave the parenthesis blank if the method has no parameters.
Method Body: It's included in the method declaration. It contains all of the actions that must be completed. It is protected by a pair of curly braces.
Types of Method
There are two types of methods in Java:
● Predefined Method
● User-defined Method
Predefined Method
Predefined methods in Java are methods that are previously defined in the Java class libraries. It's also known as the built-in method or the standard library approach. We can use these methods directly by calling them at any time in the application. Length(), equals(), compareTo(), sqrt(), and other pre-defined methods are examples. When we call any of the predefined methods in our software, a set of codes relevant to that method run in the background, which are already saved in the library.
Every predefined method is contained within a class. The java.io.PrintStream class, for example, defines the print() function. It outputs the statement we typed into the method. For example, print("Java"), it prints Java on the console.
Example
Demo.java
Public class Demo
{
Public static void main(String[] args)
{
// using the max() method of Math class
System.out.print("The maximum number is: " + Math.max(9,7));
}
}
Output
The maximum number is: 9
We utilised three predefined methods in the preceding example: main(), print(), and max() (). Because these methods are predefined, we have utilised them without declaring them. The PrintStream class has a print() function that prints the result to the console. The greater of two numbers is returned by the max() function of the Math class.
User-defined Method
A user-defined method is a method that is written by the user or programmer. These strategies are tweaked to meet the needs of the situation.
How to Create a User-defined Method
Let's build a user-defined mechanism for determining whether an integer is even or odd. We'll start by defining the method.
//user defined method
Public static void findEvenOdd(int num)
{
//method body
If(num%2==0)
System.out.println(num+" is even");
Else
System.out.println(num+" is odd");
}
The following method, entitled find even odd, has been defined (). It has an int-type parameter called num. We used void because the method does not return any value. The procedures to determine whether a number is even or odd are contained in the method body. If the number is even, it will be printed as such; otherwise, it will be printed as odd.
Key takeaway
In general, a method is a manner of accomplishing a goal. In Java, a method is a collection of instructions that accomplishes a specified goal. It ensures that code can be reused. Methods can also be used to easily alter code.
References:
- Programming in Java. Second Edition. Oxford Higher Education. (Sachin Malhotra/Saura V Choudhary)
- CORE JAVA For Beginners. (Rashmi Kanta Das), Vikas Publication
- JAVA Complete Reference (9th Edition) Herbert Schelidt.
- T. Budd, “Understanding Object- Oriented Programming with Java”, Pearson Education, Updated Edition (New Java 2 Coverage), 1999.