All about Java
All about Java
JAVA was developed by James Gosling at Sun Microsystems Inc in the year 1995, later
acquired by Oracle Corporation. It is a simple programming language. Java makes writing,
compiling, and debugging programming easy. It helps to create reusable code and modular
programs. Java is a class-based, object-oriented programming language and is designed to
have as few implementation dependencies as possible. A general-purpose programming
language made for developers to write once run anywhere that is compiled Java code can run
on all platforms that support Java. Java applications are compiled to byte code that can run
on any Java Virtual Machine. The syntax of Java is similar to c/c++.
History:
Java’s history is very interesting. It is a programming language created in 1991. James
Gosling, Mike Sheridan, and Patrick Naughton, a team of Sun engineers known as the Green
team initiated the Java language in 1991. Sun Microsystems released its first public
implementation in 1996 as Java 1.0. It provides no-cost -run-times on popular platforms.
Java1.0 compiler was re-written in Java by Arthur Van Hoff to strictly comply with its
specifications. With the arrival of Java 2, new versions had multiple configurations built for
different types of platforms.
In 1997, Sun Microsystems approached the ISO standards body and later formalized Java,
but it soon withdrew from the process. At one time, Sun made most of its Java
implementations available without charge, despite their proprietary software status. Sun
generated revenue from Java through the selling of licenses for specialized products such as
the Java Enterprise System.
On November 13, 2006, Sun released much of its Java virtual machine as free, open-source
software. On May 8, 2007, Sun finished the process, making all of its JVM’s core code
available under open-source distribution terms.
Java programming language is named JAVA. Why?
After the name OAK, the team decided to give a new name to it and the suggested words
were Silk, Jolt, revolutionary, DNA, dynamic, etc. These all names were easy to spell and
fun to say, but they all wanted the name to reflect the essence of technology. In accordance
with James Gosling, Java the among the top names along with Silk, and since java was a
unique name so most of them preferred it.
Java is the name of an island in Indonesia where the first coffee(named java coffee) was
produced. And this name was chosen by James Gosling while having coffee near his office.
Note that Java is just a name, not an acronym.
Java Terminology
Before learning Java, one must be familiar with these common terms of Java.
1. Java Virtual Machine(JVM): This is generally referred to as JVM. There are three
execution phases of a program. They are written, compile and run the program.
Java Virtual
Java Compiler
Machine
Program
Java
ByteCode Machine code
interpreter
Now, we understood that the function of Java Virtual Machine is to execute the bytecode
produced by the compiler. Every Operating System has a different JVM but the output they
produce after the execution of bytecode is the same across all the operating systems. This is
why Java is known as a platform-independent language.
5. Garbage Collector:
In Java, programmers can’t delete the objects. To delete or recollect that memory JVM has
a program called Garbage Collector. Garbage Collectors can recollect the objects that are not
referenced. So Java makes the life of a programmer easy by handling memory management.
However, programmers should be careful about their code whether they are using objects
that have been used for a long time. Because Garbage cannot recover the memory of objects
being referenced.
6. ClassPath:
The classpath is the file path where the java runtime and Java compiler look for .class files
to load. By default, JDK provides many libraries. If you want to include external libraries
they should be added to the classpath.
1. Platform Independent:
Compiler converts source code to bytecode and then the JVM executes the bytecode
generated by the compiler. This bytecode can run on any platform be it Windows, Linux, or
macOS which means if we compile a program on Windows, then we can run it on Linux and
vice versa. Each operating system has a different JVM, but the output produced by all the
OS is the same after the execution of bytecode. That is why we call java a platform-
independent language.
2. Object-Oriented Programming Language:
Organizing the program in the terms of collection of objects is a way of object-oriented
programming, each of which represents an instance of the class.
The four main concepts of Object-Oriented programming are:
4. Robust:
Java language is robust which means reliable. It is developed in such a way that it puts a lot
of effort into checking errors as early as possible, that is why the java compiler is able to
detect even those errors that are not easy to detect by another programming language. The
main features of java that make it robust are garbage collection, Exception Handling, and
memory allocation.
5. Secure:
In java, we don’t have pointers, so we cannot access out-of-bound arrays i.e it
shows ArrayIndexOutOfBound Exception if we try to do so. That’s why several security
flaws like stack corruption or buffer overflow are impossible to exploit in Java. Also java
programs run in an environment that is independent of the os(operating system) environment
which makes java programs more secure .
6. Distributed:
We can create distributed applications using the java programming language. Remote
Method Invocation and Enterprise Java Beans are used for creating distributed applications
in java. The java programs can be easily distributed on one or more systems that are
connected to each other through an internet connection.
7. Multithreading:
Java supports multithreading. It is a Java feature that allows concurrent execution of two or
more parts of a program for maximum utilization of the CPU.
8. Portable:
As we know, java code written on one machine can be run on another machine. The platform-
independent feature of java in which its platform-independent bytecode can be taken to any
platform for execution makes java portable.
9. High Performance:
Java architecture is defined in such a way that it reduces overhead during the runtime and at
some time java uses Just In Time (JIT) compiler where the compiler compiles code on-
demand basics where it only compiles those methods that are called making applications to
execute faster.
In Java, the program contains classes and methods. Further, the methods contain the
expressions and statements required to perform a specific operation. These statements and
expressions are made up of tokens. In other words, we can say that the expression and
statement is a set of tokens. The tokens are the small building blocks of a Java program that
are meaningful to the Java
compiler. Further, these two components contain variables, constants, and operators. In this
section, we will discuss what is tokens in Java.
What is token in Java?
The Java compiler breaks the line of code into text (words) is called Java tokens. These are
the smallest element of the Java program
. The Java compiler identified these words as tokens. These tokens are separated by the
delimiters. It is useful for compilers to detect errors. Remember that the delimiters are not
part of the Java tokens.
Types of Tokens
o Keywords
o Identifiers
o Literals
o Operators
o Separators
o Comments
Keywords:
These are the pre-defined reserved words of any programming language. Each keyword has
a special meaning. It is always written in lower case. Java provides the following keywords:
01. abstract 02. boolean 03. byte 04. break 05. class
06. case 07. catch 08. char 09. continue 10. default
21. import 22. instanceof 23. int 24. interface 25. long
26. native 27. new 28. package 29. private 30. protected
31. public 32. return 33. short 34. static 35. super
36. switch 37. synchronized 38. this 39. thro 40. throws
41. transient 42. try 43. void 44. volatile 45. while
46. assert 47. const 48. enum 49. goto 50. strictfp
Identifier:
Identifiers are used to name a variable, constant, function, class, and array. It usually defined
by the user. It uses letters, underscores, or a dollar sign as the first character. The label is also
known as a special kind of identifier that is used in the goto statement. Remember that the
identifier name must be different from the reserved keywords. There are some rules to declare
identifiers are:
o The first letter of an identifier must be a letter, underscore or a dollar sign. It cannot start
with digits but may contain digits.
o The whitespace cannot be included in the identifier.
o PhoneNumber
o PRICE
o radius
o a
o a1
o _phonenumber
o $circumference
o jagged_array
o 12radius //invalid
Literals:
In programming literal is a notation that represents a fixed value (constant) in the source code.
It can be categorized as an integer literal, string literal, Boolean literal, etc. It is defined by the
programmer. Once it has been defined cannot be changed. Java provides five types of literals
are as follows:
o Integer
o Floating Point
o Character
o String
o Boolean
Literal Type
23 int
9.86 double
"javatpoint" String
In programming, operators are the special symbol that tells the compiler to perform a special
operation. Java provides different types of operators that can be classified according to the
functionality they provide. There are eight types of operators in Java
, are as follows:
o Arithmetic Operators
o Assignment Operators
o Relational Operators
o Unary Operators
o Logical Operators
o Ternary Operators
o Bitwise Operators
o Shift Operators
Operator Symbols
Arithmetic +,-,/,*,%
Unary ++ , - - , !
Assignment = , += , -= , *= , /= , %= , ^=
Logical && , ||
Bitwise &,|,^,~
Separators: The separators in Java is also known as punctuators. There are nine separators
in Java, are as follows:
o Square Brackets []: It is used to define array elements. A pair of square brackets
represents the single-dimensional array, two pairs of square brackets represent the two-
dimensional array.
o Parentheses (): It is used to call the functions and parsing the parameters.
o Curly Braces {}: The curly braces denote the starting and ending of a code block.
o Comma (,): It is used to separate two values, statements, and parameters.
o Assignment Operator (=): It is used to assign a variable and constant.
o Semicolon (;): It is the symbol that can be found at end of the statements. It separates
the two statements.
o Period (.): It separates the package name form the sub-packages and class. It also
separates a variable or method from a reference variable.
Comments: Comments
allow us to specify information about the program inside our Java code. Java compiler
recognizes these comments as tokens but excludes it form further processing. The Java
compiler treats comments as whitespaces. Java provides the following two types of
comments:
o Line Oriented: It begins with a pair of forwarding slashes (//).
o Block-Oriented: It begins with /* and continues until it founds */.
Java Constant
As the name suggests, a constant is an entity in programming that is immutable.
In other words, the value that cannot be changed. In this section, we will learn
about Java constant and how to declare a constant in Java.
What is constant?
Constant is a value that cannot be changed after assigning it. Java does not directly
support the constants. There is an alternative way to define the constants in Java
by using the non-access modifiers static and final.
In Java, to declare any variable as constant, we use static and final modifiers. It is
also known as non-access modifiers. According to the Java naming
convention the identifier name must be in capital letters.
Where static and final are the non-access modifiers. The double is the data type
and PRICE is the identifier name in which the value 432.78 is assigned.
In the above statement, the static modifier causes the variable to be available
without an instance of its defining class being loaded and the final modifier makes
the variable fixed.
Here a question arises that why we use both static and final modifiers to declare
a constant?
If we declare a variable as static, all the objects of the class (in which constant is
defined) will be able to access the variable and can be changed its value. To
overcome this problem, we use the final modifier with a static modifier.
When the variable defined as final, the multiple instances of the same constant
value will be created for every different object which is not desirable.
When we use static and final modifiers together, the variable remains static and
can be initialized once. Therefore, to declare a variable as constant, we use both
static and final modifiers. It shares a common memory location for all objects of
its containing class.
Points to Remember:
o Write the identifier name in capital letters that we want to declare as constant.
For example, MAX=12.
o If we use the private access-specifier before the constant name, the value of
the constant cannot be changed in that particular class.
o If we use the public access-specifier before the constant name, the value of
the constant can be changed in the program.
import java.util.Scanner;
public class ConstantExample1
{
//declaring constant
private static final double PRICE=234.90;
public static void main(String[] args)
{
int unit;
double total_bill;
System.out.print("Enter the number of units you have used: ");
Scanner sc=new Scanner(System.in);
unit=sc.nextInt();
total_bill=PRICE*unit;
System.out.println("The total amount you have to deposit is: "+total_bill);
}
1. }
Output:
In the following example, we have declared constant PI as public. Inside the main()
method, we have assigned 3.15 in the constant PI. After that, we have invoked the
printValue() method. When we execute the program, it shows an error cannot
assign a value to the final variable PI.
In Java, the program contains classes and methods. Further, the methods contain the
expressions and statements required to perform a specific operation. These statements and
expressions are made up of tokens. In other words, we can say that the expression and
statement is a set of tokens. The tokens are the small building blocks of a Java program that
are meaningful to the Java
compiler. Further, these two components contain variables, constants, and operators. In this
section, we will discuss what is tokens in Java.
What is token in Java?
The Java compiler breaks the line of code into text (words) is called Java tokens. These are
the smallest element of the Java program
. The Java compiler identified these words as tokens. These tokens are separated by the
delimiters. It is useful for compilers to detect errors. Remember that the delimiters are not
part of the Java tokens.
Types of Tokens
o Keywords
o Identifiers
o Literals
o Operators
o Separators
o Comments
Keywords:
These are the pre-defined reserved words of any programming language. Each keyword has
a special meaning. It is always written in lower case. Java provides the following keywords:
01. abstract 02. boolean 03. byte 04. break 05. class
06. case 07. catch 08. char 09. continue 10. default
21. import 22. instanceof 23. int 24. interface 25. long
26. native 27. new 28. package 29. private 30. protected
31. public 32. return 33. short 34. static 35. super
36. switch 37. synchronized 38. this 39. thro 40. throws
41. transient 42. try 43. void 44. volatile 45. while
46. assert 47. const 48. enum 49. goto 50. strictfp
Identifier:
Identifiers are used to name a variable, constant, function, class, and array. It usually defined
by the user. It uses letters, underscores, or a dollar sign as the first character. The label is also
known as a special kind of identifier that is used in the goto statement. Remember that the
identifier name must be different from the reserved keywords. There are some rules to declare
identifiers are:
o The first letter of an identifier must be a letter, underscore or a dollar sign. It cannot start
with digits but may contain digits.
o The whitespace cannot be included in the identifier.
o PhoneNumber
o PRICE
o radius
o a
o a1
o _phonenumber
o $circumference
o jagged_array
o 12radius //invalid
Literals:
In programming literal is a notation that represents a fixed value (constant) in the source code.
It can be categorized as an integer literal, string literal, Boolean literal, etc. It is defined by the
programmer. Once it has been defined cannot be changed. Java provides five types of literals
are as follows:
o Integer
o Floating Point
o Character
o String
o Boolean
Literal Type
23 int
9.86 double
"javatpoint" String
Data types specify the different sizes and values that can be stored in the variable. There are
two types of data types in Java:
1. Primitive data types: The primitive data types include boolean, char, byte, short, int,
long, float and double.
2. Non-primitive data types: The non-primitive data types include Classes, Interfaces,
and Arrays.
In Java language, primitive data types are the building blocks of data manipulation. These are
the most basic data types available in Java language.
Java Variables
A variable is a container which holds the value while the Java program is executed. A variable
is assigned with a data type.
Variable is a name of memory location. There are three types of variables in java: local,
instance and static.
There are two types of data types in Java: primitive and non-primitive.
A variable is the name of a reserved area allocated in memory. In other words, it is a name of
the memory location. It is a combination of "vary + able" which means its value can be
changed.
Types of Variables
o local variable
o instance variable
o static variable
1) Local Variable
A variable declared inside the body of the method is called local variable. You can use this
variable only within that method and the other methods in the class aren't even aware that the
variable exists.
2) Instance Variable
A variable declared inside the class but outside the body of the method, is called an instance
variable. It is not declared as static.
It is called an instance variable because its value is instance-specific and is not shared among
instances.
3) Static variable
A variable that is declared as static is called a static variable. It cannot be local. You can create
a single copy of the static variable and share it among all the instances of the class. Memory
allocation for static variables happens only once when the class is loaded in the memory.
Ex: 1
public classSimple
{
public static void main(String[] args)
{
int a=10;
int b=10;
int c=a+b;
System.out.println(c);
}
}
Out Put: 20
Ex: 2Java Variable Example: Widening
public classSimple
{
public static void main(String[] args)
{
int a=10;
float f=a;
System.out.println(a);
System.out.println(f);
}
}
Output: 10
10.0
Operators in Java
Operator in Java is a symbol that is used to perform operations. For example: +, -, *, / etc.
There are many types of operators in Java which are given below:
o Unary Operator,
o Arithmetic Operator,
o Shift Operator,
o Relational Operator,
o Bitwise Operator,
o Logical Operator,
o Ternary Operator and
o Assignment Operator.
additive +-
equality == !=
bitwise exclusive OR ^
bitwise inclusive OR |
logical OR ||
Ternary ternary ?:
Unary Operator
The Java unary operators require only one operand. Unary operators are used to perform
various operations i.e.
o incrementing/decrementing a value by one
o negating an expression
o inverting the value of a boolean
Output:
10
12
12
10
Java arithmetic operators are used to perform addition, subtraction, multiplication, and
division. They act as basic mathematical operations.
Java Arithmetic Operator Example
Output:
15
5
50
2
0
The Java left shift operator << is used to shift all of the bits in a value to the left side of a
specified number of times.
Output: Output:
40
80
80
240
The Java right shift operator >> is used to move the value of the left operand to right by the
number of bits specified by the right operand.
public OperatorExample
{
public static void main(String args[])
{
System.out.println(10>>2);//10/2^2=10/4=2
System.out.println(20>>2);//20/2^2=20/4=5
System.out.println(20>>3);//20/2^3=20/8=2
}
}
Output:
2
5
2
The logical && operator doesn't check the second condition if the first condition is false. It
checks the second condition only if the first one is true.
The bitwise & operator always checks both conditions whether first condition is true or false.
Output:
false
false
The logical || operator doesn't check the second condition if the first condition is true. It checks
the second condition only if the first one is false.
true
true
true
10
true
11
Java Ternary operator is used as one line replacement for if-then-else statement and used a lot
in Java programming. It is the only conditional operator which takes three operands.
Output:
Assignment Operator
Java assignment operator is one of the most common operators. It is used to assign the value
on its right to the operand on its left.
Output:
14
16
System.out.println() or
System.out.print() or
System.out.printf()
Scanf()
Cin>>
Java provides different ways to get input from the user. However, the user using the object
of Scanner class. To get the input.
In order to use the object of Scanner,
we need to import java.util.Scanner
package.
Import java.util.Scanner:
Class Input
{
Public static void main(String args[])
{
Scanner input = new Scanner(System.in)// creating new obj-----
System.out.prinln(“enter an integer”);
Int number=input.nectInt();
System.out.println(“you entered” +number);
Input.class();
}
}
Output:
enter an integer:
23
You entered
23
Type Casting
The process of converting the value of one data type (int, float, double, etc.) to another data
type is known as typecasting.
In Java, there are 13 types of type conversion. However, in this tutorial, we will only focus
on the major 2 types.
In Widening Type Casting, Java automatically converts one data type to another data type.
class main
{
Public static void main(String args[])
{
int num=10;
System.ou.println(“the integer value is:”+num );
double data=num; //convert into double type
System.out.println(“then double value is:”+data”);
}
}
Output
In the above example, we are assigning the int type variable named num to a double type
variable named data.
Here, the Java first converts the int type data into the double type. And then assign it to
the double variable.
In the case of Widening Type Casting, the lower data type (having smaller size) is
converted into the higher data type (having larger size). Hence there is no loss in data. This is
why this type of conversion happens automatically.
Narrowing Type Casting
In Narrowing Type Casting, we manually convert one data type into another using the
parenthesis.
class main
{
Public static void main(String args[])
{
double num=10.99;
System.out.println(the double value is:” +num);
int data=(int)num; //manually…….
System.out.println(the double value is:” +data);
}
}
Output
The Enum in Java is a data type which contains a fixed set of constants and enum is a
keyword
It can be used for days of the week (SUNDAY, MONDAY, TUESDAY, WEDNESDAY,
THURSDAY, FRIDAY, and SATURDAY) , directions (NORTH, SOUTH, EAST, and
WEST),
Enums are used to create our own data type like classes. The enum data type (also known as
Enumerated Data Type) is used to define an enum in Java. Unlike C/C++, enum in Java is
more powerful. Here, we can define an enum either inside the class or outside the class.
class EnumExample1
{
public enum Season { WINTER, SPRING, SUMMER, FALL } //defining enum within c
lass
}
}
Output:
WINTER
SPRING
SUMMER
FALL
Value of WINTER is: WINTER
Index of WINTER is: 0
Index of SUMMER is: 2
Example:2
enum Level{LOW,MEDIUM,HIGH}
{
Level myVar = Level.MEDIUM;
switch(myVar)
{
case LOW:
System.out.println("Low level");
break;
case MEDIUM:
System.out.println("Medium level");
break;
case HIGH:
System.out.println("High level");
break;
}
}
The output will be:
Medium level
Conditional statements:
Conditional statements are mostly used in decision-making scenarios which means these
statements take a decision on the basis of some conditions. The conditional statements are also
referred as branching statements because the program takes a decision based on the result of the
assessed condition.
o if statement
o if-else statement
o if-else-if ladder
o nested if statement
if Statement:
The Java if statement tests the condition. It executes the if block if condition is true. If the given condition is
satisfied it will execute the true block statement only
Example Program:
if-else Statement
The Java if-else statement also tests the condition. It executes the if block if condition is true otherwise else
block is executed. It will execute either true block statement or false block statements.
Example Program:1
if(condition1)
{
//code to be executed if condition1 is true
}
else if(condition2)
{
//code to be executed if condition2 is true
}
else if(condition3)
{
//code to be executed if condition3 is true
}
...
Else
{
//code to be executed if all the conditions are false
}
Example Program:
if(marks<50)
{
System.out.println("fail");
}
else if(marks>=50 && marks<60)
{
System.out.println("D grade");
}
else if(marks>=60 && marks<70)
{
System.out.println("C grade");
}
else if(marks>=70 && marks<80)
{
System.out.println("B grade");
}
else if(marks>=80 && marks<90)
{
System.out.println("A grade");
}
else if(marks>=90 && marks<100)
{
System.out.println("A+ grade");
}
else
{
System.out.println("Invalid!");
}
}
}
Output:
C Grade
Nested if statement:
The nested if statement represents the if block within another if block. Here, the inner if block condition
executes only when outer if block condition is true.
if(condition)
{
//code to be executed
if(condition)
{
//code to be executed
}
}
Example:
public class JavaNestedIfExample2
{
public static void main(String[] args)
{
//Creating two variables for age and weight
int age=25;
int weight=48;
//applying condition on age and weight
if(age>=18)
{
if(weight>50)
{
System.out.println("You are eligible to donate blood");
}
else
{
System.out.println("You are not eligible to donate blood");
}
}
else
{
System.out.println("Age must be greater than 18");
}
}
}
Output: 16
Syntax:
switch(expression)
{
case value1:
//code to be executed;
break; //optional
case value2:
//code to be executed;
break; //optional
………
default:
code to be executed if all cases are not matched;
}
Example program:
public class SwitchMonthExample
{
public static void main(String[] args)
{
//Specifying month number
int month=7;
String monthString="";
//Switch statement
switch(month)
{
//case statements within the switch block
case 1: monthString="1 - January";
break;
case 2: monthString="2 - February";
break;
case 3: monthString="3 - March";
break;
case 4: monthString="4 - April";
break;
case 5: monthString="5 - May";
break;
case 6: monthString="6 - June";
break;
case 7: monthString="7 - July";
break;
case 8: monthString="8 - August";
break;
case 9: monthString="9 - September";
break;
case 10: monthString="10 - October";
break;
case 11: monthString="11 - November";
break;
case 12: monthString="12 - December";
break;
default:System.out.println("Invalid Month!");
}
//Printing month of the given number
System.out.println(monthString);
}
}
Out put:
3 – March
Iteration Statements:
For Loop:
Iteration statements are used to execute a particular set of instructions repeatedly
until a particular condition is met or for a fixed number of iterations.
• The initialization statement is executed only once.
• Then, the test expression is evaluated. If the test expression is evaluated to
false, the for loop is terminated.
• However, if the test expression is evaluated to true, statements inside the
body of the for loop are executed,
• and the update expression is updated.
• Again the test expression is evaluated.
This process goes on until the test expression is false. When the test expression is
false, the loop terminates.
Example : Display numbers from 1 to 5
class Main
{
public static void main(String[] args)
{
int n = 5;
for (int i = 1; i <= n; ++i)
{
System.out.println(i);
}
}
}
The Java while loop is used to iterate a part of the program repeatedly until the specified
Boolean condition is true. As soon as the Boolean condition becomes false, the loop
automatically stops.
The while loop is considered as a repeating if statement. If the number of iteration is not fixed,
it is recommended to use the while loop.
Syntax:
while (condition)
{
//code to be executed
Increment / decrement statement
}
Example: Sum of Positive Numbers Only
import java.util.Scanner;
class Main
{
public static void main(String[] args)
{
int sum = 0; // create an object of Scanner class
Scanner input = new Scanner(System.in); // take integer input from the user
System.out.println("Enter a number");
int number = input.nextInt(); // while loop continues // until entered number is positive
while (number >= 0)
{ // add only positive numbers
sum += number;
System.out.println("Enter a number");
number = input.nextInt();
}
System.out.println("Sum = " + sum); input.close();
}
}
Output:
Enter a number
25
Enter a number
9
Enter a number
5
Enter a number
-3
Sum = 39
do-while Loop
The Java do-while loop is used to iterate a part of the program repeatedly, until the specified
condition is true. If the number of iteration is not fixed and you must have to execute the loop
at least once, it is recommended to use a do-while loop.
Java do-while loop is called an exit control loop. Therefore, unlike while loop and for loop,
the do-while check the condition at the end of loop body. The Java do-while loop is executed
at least once because condition is checked after loop body.
Syntax:
Do
{
//code to be executed / loop body
//update statement
}
While (condition);
In the below example, we print integer values from 1 to 10. Unlike the for loop, we
separately need to initialize and increment the variable used in the condition (here, i).
Otherwise, the loop will execute infinitely.
Output:
10
For-each loop in Java
The Java for-each loop or enhanced for loop is introduced since J2SE 5.0.
It provides an alternative approach to traverse the array or collection in
Java.
It is mainly used to traverse the array or collection elements.
The advantage of the for-each loop is that it eliminates the possibility of
bugs and makes the code more readable.
It is known as the for-each loop because it traverses each element one by
one.
The drawback of the enhanced for loop is that it cannot traverse the elements in
reverse order.
you do not have the option to skip any element because it does not work on an
index basis. Moreover, you cannot traverse the odd or even elements only.
For-each is another array traversing technique like for loop, while loop, do-while loop
introduced in Java5.
It’s commonly used to iterate over an array or a Collections class (eg, ArrayList).
Syntax:
for (type var : array)
{
statements using var;
}
is equivalent to:
The execution of a Java program is done in sequential order. Looping statements like for,
while, and do-while are used to execute a set of statements repeatedly. If such an execution
were to continue, it would go on forever. This can be prevented by adding appropriate
terminating conditions to the loop or by implementing jump statements. A jump statement
helps transfer the control of a program from one line of the code to another and skip the ones
in between.
1.Break Statement:
In java, the break statement is used to terminate the execution of the
nearest looping statement or switch statement. The break statement is widely used with the
switch statement, for loop, while loop, do-while loop.
Syntax:
break;
When a break statement is found inside a loop, the loop is terminated, and the control
reaches the statement that follows the loop. here is an example:
For( )//
For( ) {
{ For ( )
break;
} {
break;
import java.io.*; }
class Break
}
{
public static void main(String[] args)
{
int n = 10;
for (int i = 0; i < n; i++)
{
if (i == 6)
break;
System.out.println(i);
}
}
}
Output:
0
1
2
3
4
5
Example: 2
public class Break2
{
public static void main(String args[])
{
int i = 3;
switch(i)
{
case 1:
System.out.println("One");
break;
case 2:
System.out.println("Two");
break;
case 3:
System.out.println("Three");
break;
case 4:
System.out.println("Four");
break;
default:
System.out.println("Other");
}
}
}
Output :
Three
Goto:
The goto keyword is a commonly used jump statement in C/C++. However, Java uses
break statements to perform the same function as goto. Labels can be used to identify blocks
of code in Java. Any valid identifier followed by a semicolon represents a label. We can
break out of a labelled block by mentioning the label name after the break keyword.
Output:
0
1
2
Example:2
class myClass
{
public static void main( String args[] )
{
label:
for (int i=0;i<6;i++)
{
if (i==3)
{
break label; // exits the loop when it reaches 3
}
System.out.println(i);
}
}
}
0
1
2
Continue statement:
Continue is a jump statement used when a loop’s current iteration is
to be skipped. It allows the control to temporarily exit the loop and ignore the remaining
statements that follow. After this jump, the control immediately moves with the next
iteration of the same loop.
Design Patterns are introduced by architect Christopher Alexander and are used as best practices
for various other software developers’ commonly faced problems while creating software.
This helps in designing smart and flexible codes as per project requirements with suitable
objects, classes, loosely coupled codes, quick understanding strictures and many more.
Unwanted codes and problems can be easily identified and changed helpless work to
testers and maintainers of the application.
Client and end-users feel the interface more user-friendly and provide a good user
experience while working or using an application or software.
In the IT industry, coding and application design, and structure play a key role in the
success of the application or software.
This jobs of designing effective software with easy and simple patterns can be done
using design patterns in java.
Many hugs and robust designs can be maintained and executed quickly because of
design patterns.
It identifies the common mistakes in coding in the phase of design and reduces the
cost of ownership.
Scope:
Design Patterns are very popular and are used by many professional companies
worldwide to design and develop software programs and application.
It has high industrial usage and helps design, test, maintain, and reuse the coding for
multiple processes.
It’s easy to fix the issue at any phase of the application due to its easy-to-understand
stricture to identify the code of the problem with suitable solutions to fix it.
It deals with dynamics change at runtime and class scopes at the time of built.
Note :
when two classes or modules or components have low dependency on each other is called as
loosely coupled codes.
Example:1
class ptr1
{
public static void main(String args[])
{
int i,j;
for(i=1;i<=5;i++)
{
for(j=1;j<=i;j++)
{
System.out.print("* ");
}
System.out.println();
}
}
}
Output:
*
**
***
****
*****
Example: 2
class ptr2
{
public static void main(String args[])
{
int i,j;
for(i=5;i>=1;i--)
{
for(j=1;j<=i;j++)
{
System.out.print("* ");
}
System.out.println();
}
}
}
Output:
*****
****
***
**
*
Arrays:
An array is a collection of similar type of elements which has contiguous
memory location. Java array is an object which contains elements of a similar data type.
Additionally, The elements of an array are stored in a contiguous memory location. It is a
data structure where we store similar elements. We can store only a fixed set of elements in a
Java array.
type var-name[];
OR
type[] var-name;
Disadvantages:
Size Limit:
We can store only the fixed size of elements in the array. It doesn't grow its size at runtime.
One Dimensional Array in java is always used with only one subscript ([]).One
Dimensional Array in java is always used with only one subscript ( []). A one-dimensional
array behaves likes a list of variables. You can access the variables of an array by using an
index in square brackets preceded by the name of that array. Index value should be an
integer. Before using the array, we must declare it.
type var-name[];
OR
type[] var-name;
Example Program:1
class OnedimenisionaArray
{
public static void main(String[] args)
{
int[] arr; // declares an Array of integers.
arr = new int[5]; // allocating memory for 5 integers.
arr[0] = 10; // initialize the first elements of the array
arr[1] = 20; // initialize the second elements of the array
arr[2] = 30;
arr[3] = 40;
arr[4] = 50;
// accessing the elements of the specified array
for (int i = 0; i < arr.length; i++)
System.out.println("Element at index " + i + " : " + arr[i]);
}
}
Output:
Element at index 0 : 10
Element at index 1 : 20
Element at index 2 : 30
Element at index 3 : 40
Element at index 4 : 50
Multidimensional Arrays:
Multidimensional Arrays can be defined in simple words as array of arrays. Data in
multidimensional arrays are stored in tabular form (in row major order).
data_type[1st dimension][2nd dimension][]..[Nth dimension] array_name = new
data_type[size1][size2]….[sizeN];
data_type: Type of data to be stored in the array. For example: int, char, etc.
dimension: The dimension of the array created. For example: 1D, 2D, etc.
array_name: Name of the array
size1, size2, …, sizeN: Sizes of the dimensions respectively.
Example:2
public class TwoDimensional
{
public static void main(String args[])
{
// declaring and initializing 2D array
int arr[][]
= { { 2, 7, 9 }, { 3, 6, 1 }, { 7, 4, 2 } };
// printing 2D array
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
System.out.print(arr[i][j] + " ");
System.out.println();
}
}
}
Output:
279
361
742
Multidimensional array:
Three – dimensional array is a complex form of a
multidimensional array. A three – dimensional array can be seen as an array of two –
dimensional array for easier understanding. Multi-dimensional array represents with three
subscripts. Elements in three-dimensional arrays are commonly referred by x[i][j][k] where
‘i’ is the array number, ‘j’ is the row number and ‘k’ is the column number.
Example:3
class MultiDimensional
{
public static void main(String[] args)
{
int[][][] arr = { { { 1, 2 }, { 3, 4 } },
{ { 5, 6 }, { 7, 8 } } };
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < 2; j++)
{
for (int k = 0; k < 2; k++)
{
System.out.print(arr[i][j][k] + " ");
}
System.out.println();
}
System.out.println();
}
}
}
Output:
12
34
56
78
Strings in java:
String manipulation is the most common part of the java program. String
represents a character of sequence of character/ group of character. That is easiest way to
represent a sequence of character in java by using a character array. String is fixed length
character it does not changed during the execution of a program.
Or
Java, a string is an object that represents a number of character
values. Each letter in the string is a separate character value that makes up the Java string
object. Characters in Java are represented by the char class. Users can write an array of char
values that will mean the same thing as a string.
1. By string literal
2. By new keyword
1) String Literal:
Java String literal is created by using double quotes. For Example:
String s="SRIT";
Each time you create a string literal, the JVM checks the "string
constant pool" first. If the string already exists in the pool, a reference to the pooled instance
is returned. If the string doesn't exist in the pool, a new string instance is created and placed
in the pool. For example:
1. String s1="csd";
2. String s2="SRIT";//It doesn't create a new instance
In the above example, only one object will be created. Firstly, JVM will not find any string
object with the value "Welcome" in string constant pool that is why it will create a new
object. After that it will find the string with the value "Welcome" in the pool, it will not
create a new object but will return the reference to the same instance.
will create a new string object in normal (non-pool) heap memory, and the literal
"Welcome" will be placed in the string constant pool. The variable s will refer to the
object in a heap (non-pool).
Java String Example
Output:
SRIT
ANANTH
CSM and CSD
Example:2
import java.io.*;
import java.lang.*;
class SRIT
{
public static void main(String[] args)
{
// Declare String without using new operator
String s = "SRIT";
// Prints the String.
System.out.println("String s = " + s);
// Declare String using new operator
String s1 = new String("Ananthapur");
// Prints the String.
System.out.println("String s1 = " + s1);
}
}
Output:
String s = SRIT
String s1 = Ananthapur
String Class:
20 int indexOf(int ch, int fromIndex) It returns the specified char value
index starting with given index.
Java StringBuffer class is used to create mutable (modifiable) String objects. The StringBuffer
class in Java is the same as String class except it is mutable i.e. it can be changed.
Constructor Description
StringBuffer() It creates an empty String buffer with the initial capacity of
16.
public insert(int offset, String It is used to insert the specified string with this
synchronized s) string at the specified position. The insert()
StringBuffer method is overloaded like insert(int, char),
insert(int, boolean), insert(int, int), insert(int,
float), insert(int, double) etc.
public int length() It is used to return the length of the string i.e.
total number of characters.
public String substring(int It is used to return the substring from the
beginIndex) specified beginIndex.
The append() method concatenates the given argument with this String
class StringBufferExample
{
public static void main(String args[])
{
StringBuffer sb=new StringBuffer("Hello ");
sb.append("SRIT"); //now original string is changed
System.out.println(sb); //prints Hello Java
}
}
Output:
Hello SRIT
he insert() method inserts the given String with this string at the given position.
class StringBufferExample2
{
public static void main(String args[])
{
StringBuffer sb=new StringBuffer("Hello ");
sb.insert(1,"Java");//now original string is changed
System.out.println(sb);//prints HJavaello
}
}
Output:
HJavaello
the replace() method replaces the given String from the specified beginIndex and endIndex.
class StringBufferExample3
{
public static void main(String args[])
{
StringBuffer sb=new StringBuffer("Hello");
sb.replace(1,3,"Java");
System.out.println(sb);//prints HJavalo
}
}
Output:
HJavalo
The delete() method of the StringBuffer class deletes the String from the specified beginIndex
to endIndex.
class StringBufferExample4
{
public static void main(String args[])
{
StringBuffer sb=new StringBuffer("Hello");
sb.delete(1,3);
System.out.println(sb);//prints Hlo
}
}
Output:
Hlo
The reverse() method of the StringBuilder class reverses the current String.
class StringBufferExample5
{
public static void main(String args[])
{
StringBuffer sb=new StringBuffer("Hello");
sb.reverse();
System.out.println(sb);//prints olleH
}
}
Output:
olleH
the capacity() method of the StringBuffer class returns the current capacity of the buffer.
The default capacity of the buffer is 16. If the number of character increases from its current
capacity, it increases the capacity by (oldcapacity*2)+2. For example if your current
capacity is 16, it will be (16*2)+2=34.
class StringBufferExample6
{
public static void main(String args[])
{
StringBuffer sb=new StringBuffer();
System.out.println(sb.capacity());//default 16
sb.append("Hello");
System.out.println(sb.capacity());//now 16
sb.append("java is my favourite language");
System.out.println(sb.capacity());//now (16*2)+2=34 i.e (oldcapacity*2)+2
}
}
Output:
16
16
34
The ensureCapacity() method of the StringBuffer class ensures that the given capacity is the
minimum to the current capacity. If it is greater than the current capacity, it increases the
capacity by (oldcapacity*2)+2. For example if your current capacity is 16, it will be
(16*2)+2=34.
class StringBufferExample7
{
public static void main(String args[])
{
StringBuffer sb=new StringBuffer();
System.out.println(sb.capacity());//default 16
sb.append("Hello");
System.out.println(sb.capacity());//now 16
sb.append("java is my favourite language");
System.out.println(sb.capacity());//now (16*2)+2=34 i.e (oldcapacity*2)+2
sb.ensureCapacity(10);//now no change
System.out.println(sb.capacity());//now 34
sb.ensureCapacity(50);//now (34*2)+2
System.out.println(sb.capacity());//now 70
}
}
Output:
16
16
34
34
70
StringTokenizer in Java:
The java.util.StringTokenizer class allows you to break a String into tokens. It is simple
way to break a String. It is a legacy class of Java.
It doesn't provide the facility to differentiate numbers, quoted strings, identifiers etc. like
StreamTokenizer class.
In the StringTokenizer class, the delimiters can be provided at the time of creation or one by
one to the tokens.
Constructors of the StringTokenizer Class:
Constructor Description
String nextToken() It returns the next token from the StringTokenizer object.
String nextToken(String delim) It returns the next token based on the delimiter.
Object nextElement() It is the same as nextToken() but its return type is Object.
Let's see an example of the StringTokenizer class that tokenizes a string "my name is khan"
on the basis of whitespace.
import java.util.StringTokenizer;
public class Simple
{
public static void main(String args[])
{
StringTokenizer st = new StringTokenizer("MyCollege Name SRIT-
Ananthapur"," ");
while (st.hasMoreTokens())
{
System.out.println(st.nextToken());
}
}
}
Output:
My
CollegeName
SRIT-
Ananthapur
import java.util.*;
public class Test
{
public static void main(String[] args)
{
StringTokenizer st = new StringTokenizer("my,name,is,khan");
// printing next token
System.out.println("Next token is : " + st.nextToken(","));
}
}
Output:
Next token is : my
This method returns true if more tokens are available in the tokenizer String otherwise
returns false.
import java.util.StringTokenizer;
public class StringTokenizer1
{
/* Driver Code */
public static void main(String args[])
{
/* StringTokenizer object */
StringTokenizer st = new StringTokenizer("Demonstrating methods from StringTokeni
zer class"," ");
/* Checks if the String has any more tokens */
while (st.hasMoreTokens())
{
System.out.println(st.nextToken());
}
}
}
Output:
Demonstrating
methods
from
StringTokenizer
Class
This method returns the same value as hasMoreTokens() method of StringTokenizer class.
The only difference is this class can implement the Enumeration interface.
import java.util.StringTokenizer;
public class StringTokenizer2
{
public static void main(String args[])
{
StringTokenizer st = new StringTokenizer("Hello Everyone we are SRIT College
Students"," ");
while (st.hasMoreElements())
{
System.out.println(st.nextToken());
}
}
}
Output:
HelloEveryone
we
are
SRIT
College
Students
nextElement() returns the next token object in the tokenizer String. It can implement
Enumeration interface.
import java.util.StringTokenizer;
public class StringTokenizer3
{
/* Driver Code */
public static void main(String args[])
{
/* StringTokenizer object */
StringTokenizer st = new StringTokenizer("Hello Everyone Welcome to SRIT"," ");
/* Checks if the String has any more tokens */
while (st.hasMoreTokens())
{
/* Prints the elements from the String */
System.out.println(st.nextElement());
}
}
}
Output:
Hello
Everyone
Welcome
to
SRIT
This method calculates the number of tokens present in the tokenizer String.
import java.util.StringTokenizer;
public class StringTokenizer3
{
/* Driver Code */
public static void main(String args[])
{
/* StringTokenizer object */
StringTokenizer st = new StringTokenizer("Hello Everyone Welcome to SRIT
Department of CSD and CSM "," ");
/* Prints the number of tokens present in the String */
System.out.println("Total number of Tokens: "+st.countTokens());
}
}
Output:
Total number of Tokens: 10