0% found this document useful (0 votes)
11 views52 pages

Java_07_22_22

Uploaded by

rishabhs604
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views52 pages

Java_07_22_22

Uploaded by

rishabhs604
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 52

Java language fundamentals

Identifiers:

In programming languages, identifiers are used for identification


purposes. In Java, an identifier can be a class name, method name,
variable name, or label. For example :

public class Test


{
public static void main(String[] args)
{
int a = 20;

}
}

In the above java code, we have 5 identifiers namely :

 Test : class name.


 main : method name.
 String : predefined class name.
 args : variable name.
 a : variable name.

Rules for defining Java Identifiers


There are certain rules for defining a valid java identifier. These rules
must be followed, otherwise we get compile-time error. These rules are
also valid for other languages like C,C++.

 The only allowed characters for identifiers are all alphanumeric


characters([A-Z],[a-z],[0-9]), ‘$‘(dollar sign) and ‘_‘
(underscore).For example “geek@” is not a valid java identifier as it
contain ‘@’ special character.
 Identifiers should not start with digits([0-9]). For example
“123geeks” is a not a valid java identifier.
 Java identifiers are case-sensitive.
 There is no limit on the length of the identifier but it is advisable to
use an optimum length of 4 – 15 letters only.
 Reserved Words can’t be used as an identifier. For example “int
while = 20;” is an invalid statement as while is a reserved word.
There are 53 reserved words in Java.

Examples of valid identifiers :

MyVariable
MYVARIABLE
myvariable
x
i
x1
i1
_myvariable
$myvariable
sum_of_array
geeks123
Examples of invalid identifiers :

My Variable // contains a space


123geeks // Begins with a digit
a+c // plus sign is not an alphanumeric character
variable-2 // hyphen is not an alphanumeric character
sum_&_difference // ampersand is not an alphanumeric character
Reserved Words
Any programming language reserves some words to represent
functionalities defined by that language. These words are called
reserved words.They can be briefly categorized into two
parts : keywords(50) and literals(3). Keywords define functionalities
and literals define a value. Identifiers are used by symbol tables in
various analyzing phases(like lexical, syntax, semantic) of a compiler
architecture.
Note: The keywords const and goto are reserved, even though they
are not currently used. In place of const, the final keyword is used.
Some keywords like strictfp are included in later versions of Java.

Java Keywords
Java keywords are also known as reserved words. Keywords are particular
words that act as a key to a code. These are predefined words by Java so
they cannot be used as a variable or object name or class name.

List of Java Keywords


A list of Java keywords or reserved words are given below:

1. abstract

: Java abstract keyword is used to declare an abstract class. An abstract class


can provide the implementation of the interface. It can have abstract and
non-abstract methods.

2. boolean:

Java boolean keyword is used to declare a variable as a boolean type. It can


hold True and False values only.

3. break

: Java break keyword is used to break the loop or switch statement. It breaks
the current flow of the program at specified conditions.

4. byte

: Java byte keyword is used to declare a variable that can hold 8-bit data
values.

5. case
: Java case keyword is used with the switch statements to mark blocks of
text.

6. catch

: Java catch keyword is used to catch the exceptions generated by try


statements. It must be used after the try block only.

7. char

: Java char keyword is used to declare a variable that can hold unsigned 16-
bit Unicode characters

8. class

: Java class keyword is used to declare a class.

9. continue

: Java continue keyword is used to continue the loop. It continues the current
flow of the program and skips the remaining code at the specified condition.

10. default

: Java default keyword is used to specify the default block of code in a switch
statement.

11. do

: Java do keyword is used in the control statement to declare a loop. It can


iterate a part of the program several times.

12. double

: Java double keyword is used to declare a variable that can hold 64-bit
floating-point number.

13. else
: Java else keyword is used to indicate the alternative branches in an if
statement.

14. enum

: Java enum keyword is used to define a fixed set of constants. Enum


constructors are always private or default.

15. extends

: Java extends keyword is used to indicate that a class is derived from


another class or interface.

16. final

: Java final keyword is used to indicate that a variable holds a constant value.
It is used with a variable. It is used to restrict the user from updating the
value of the variable.

17. finally

: Java finally keyword indicates a block of code in a try-catch structure. This


block is always executed whether an exception is handled or not.

18. float

: Java float keyword is used to declare a variable that can hold a 32-bit
floating-point number.

19. for

: Java for keyword is used to start a for loop. It is used to execute a set of
instructions/functions repeatedly when some condition becomes true. If the
number of iteration is fixed, it is recommended to use for loop.

20. if
: Java if keyword tests the condition. It executes the if block if the condition is
true.

21. implements

: Java implements keyword is used to implement an interface.

22. import

: Java import keyword makes classes and interfaces available and accessible
to the current source code.

23. instanceof

: Java instanceof keyword is used to test whether the object is an instance of


the specified class or implements an interface.

24. int

: Java int keyword is used to declare a variable that can hold a 32-bit signed
integer.

25. interface

: Java interface keyword is used to declare an interface. It can have only


abstract methods.

26. long

: Java long keyword is used to declare a variable that can hold a 64-bit
integer.

27.native: Java native keyword is used to specify that a method is implemented


in native code using JNI (Java Native Interface).
28. new

: Java new keyword is used to create new objects.


29. null

: Java null keyword is used to indicate that a reference does not refer to
anything. It removes the garbage value.

30. package

: Java package keyword is used to declare a Java package that includes the
classes.

31. private

: Java private keyword is an access modifier. It is used to indicate that a


method or variable may be accessed only in the class in which it is declared.

32. protected

: Java protected keyword is an access modifier. It can be accessible within the


package and outside the package but through inheritance only. It can't be
applied with the class.

33. public

: Java public keyword is an access modifier. It is used to indicate that an item


is accessible anywhere. It has the widest scope among all other modifiers.

34. return

: Java return keyword is used to return from a method when its execution is
complete.

35. short

: Java short keyword is used to declare a variable that can hold a 16-bit
integer.

36. static
: Java static keyword is used to indicate that a variable or method is a class
method. The static keyword in Java is mainly used for memory management.

37. strictfp

: Java strictfp is used to restrict the floating-point calculations to ensure


portability.

38. super

: Java super keyword is a reference variable that is used to refer to parent


class objects. It can be used to invoke the immediate parent class method.

39. switch

: The Java switch keyword contains a switch statement that executes code
based on test value. The switch statement tests the equality of a variable
against multiple values.

40. synchronized

: Java synchronized keyword is used to specify the critical sections or


methods in multithreaded code.

41. this

: Java this keyword can be used to refer the current object in a method or
constructor.

42. throw

: The Java throw keyword is used to explicitly throw an exception. The throw
keyword is mainly used to throw custom exceptions. It is followed by an
instance.

43. throws
: The Java throws keyword is used to declare an exception. Checked
exceptions can be propagated with throws.

44. transient

: Java transient keyword is used in serialization. If you define any data


member as transient, it will not be serialized.

45. try

: Java try keyword is used to start a block of code that will be tested for
exceptions. The try block must be followed by either catch or finally block.

46.void: Java void keyword is used to specify that a method does not have a
return value.
47. volatile

: Java volatile keyword is used to indicate that a variable may change


asynchronously.

48. while

: Java while keyword is used to start a while loop. This loop iterates a part of
the program several times. If the number of iteration is not fixed, it is
recommended to use the while loop.

Java Variables
Variables are containers for storing data values.

In Java, there are different types of variables, for example:

 String - stores text, such as "Hello". String values are surrounded by


double quotes
 int - stores integers (whole numbers), without decimals, such as 123 or -
123
 float - stores floating point numbers, with decimals, such as 19.99 or -
19.99
 char - stores single characters, such as 'a' or 'B'. Char values are
surrounded by single quotes
 boolean - stores values with two states: true or false

Declaring (Creating) Variables


To create a variable, you must specify the type and assign it a value:

Syntax
type variableName = value;

Where type is one of Java's types (such as int or String), and variableName is
the name of the variable (such as x or name). The equal sign is used to assign
values to the variable.

To create a variable that should store text, look at the following example:

Example
Create a variable called name of type String and assign it the value "John":

String name = "John";

System.out.println(name);

To create a variable that should store a number, look at the following example:

Example
Create a variable called myNum of type int and assign it the value 15:

int myNum = 15;

System.out.println(myNum);

You can also declare a variable without assigning the value, and assign the
value later:
Example
int myNum;

myNum = 15;

System.out.println(myNum);

Note that if you assign a new value to an existing variable, it will overwrite the
previous value:

Example
Change the value of myNum from 15 to 20:

int myNum = 15;

myNum = 20; // myNum is now 20

System.out.println(myNum);

Final Variables
If you don't want others (or yourself) to overwrite existing values, use
the final keyword (this will declare the variable as "final" or "constant", which
means unchangeable and read-only):

Example
final int myNum = 15;

myNum = 20; // will generate an error: cannot assign a value to a


final variable

Other Types
A demonstration of how to declare variables of other types:
Example
int myNum = 5;

float myFloatNum = 5.99f;

char myLetter = 'D';

boolean myBool = true;

String myText = "Hello";

Literal in Java

is a synthetic representation of boolean, numeric, character,


or string data. It is a means of expressing particular values in
the program, such as an integer variable named ‘’/count is
assigned an integer value in the following statement.
int count = 0;

A literal ‘0’ represents the value zero.


Thus, a constant value assigned to the variable can be
referred to as literal.
Literals in Java can be classified into six types, as below:
1. Integral Literals
2. Floating-point Literals
3. Char Literals
4. String Literals
5. Boolean Literals
6. Null Literals
Our learners also read: Free java course!
These literals are again specified in different sub-types, let us
see one by one in the article.

1. Integral Literals
Integral literals are specified in four different ways, as
follows:
Decimal: It has base ten, and digits from 0 to 9.
For example,
Int x = 108;
Octal: It has base eight and allows digits from 0 to 7. While
assigning an octal literal in the Java code, a number must
have a prefix 0.
For example,
int x = 0745;
Hexadecimal:
It has base 16. Hexadecimal allows digits from 0 to 9, and
characters from A to F. Even though Java is case sensitive,
and it also provides an exception for using either uppercase
or lowercase characters in the code for hexadecimal literals.
For example,
int x = 0X123Fadd;
Binary:
It can be specified in binary literals, that is 0 and 1 with a
prefix 0b or 0B.
For example,
int x = 0b1011;

2. Floating-Point Literals
FLoating-point literals can be expressed using only decimal
fractions or as exponential notation.
For example,
decimalNumber = 89d;
decimalNumber = 3.14159e0;
decimalNumber = 1.0e-6D;
Floating-point literals can indicate a positive or negative
value, leading + or – sign respectively. If not specified, the
value is always considered positive. It can be represented in
the following formats:
-Integer digits (representing digits 0 through 9) followed by
either a suffix or an exponent to distinguish it from an
integral literal.
-Integer digit.
-integer digit. integer digit
– integer digit
An optional exponent of the form might be as below:
-an optional exponent sign + or –
-the exponent indicator e or E
–integer digit representing the integer exponent value
An optional floating-point suffix might be as below:
Single precision (4 bytes) floating-point number indicating
either for F
Double precision (8 bytes) floating-point number
indicating d or D

3. Char Literals
Character (Char) literals have the type char and are an
unsigned integer primitive type. They are constant value
character expressions in the Java program. These are
sixteen-bit Unicode characters that range from 0 to 65535.
Char literals are expressed as a single quote, a single closing
quote, and the character in Java.
Char literals are specified in four different ways, as given
below:
Single quote: Java literal is specified to a char data type as a
single character enclosed in a single quote.
For example,
char ch = ‘a’;
Char Literal: Java literal is specified as an integer literal
representing the Unicode value of a char. This integer can be
specified in octal, decimal, and hexadecimal, ranging from 0
to 65535.
For example,
char ch = 062;
Escape Sequence: Every escape char can be specified as char
literal.
For example,
char ch = ‘\n’;
Unicode Representation: Java literal is specified in Unicode
representation ‘\uzzz’, where zzzz are four hexadecimal
numbers.
For example,
char ch = ‘\u0061’;

4. String Literals
A sequence of (zero or more including Unicode characters)
characters within double quotes is referred to as string
literals.
For example,
String s = “Hello”;
String literals may not have unescaped line feed or newline
characters, but the Java compiler always evaluates compile-
time expressions. Unicode escape sequences or special
characters can be used within the string and character literal
as backlash characters to escape special characters, as
shown in the table below:
Name Character ASCII Hex

Single quote \’ 39 0x27

Double quote \” 34 0x22

Carriage control \r 13 0xd

Backlash \\ 92 0x5c

Newline \n 10 0x0a

NUL character \0 0 0x00

Backspace \b 8 0x08

TAB \t 9 0x09
5. Boolean Literals
Boolean literals allow only two values and thus are divided
into two literals:
True: it represents a real boolean value
False: it represents a false boolean value
For example,
boolean b = true;
boolean d = false;
6. Null Literals
Null literal is a particular literal in Java representing a null
value. This value refers to no object. Java
throws NullPointerException. Null often describe the
uninitialized state in the program. It is an error to attempt to
dereference the null value.

Literals in Java help build basics in programming. Every Java


programmer must be aware of this fundamental and essential
concept that assigns values to the program’s variables. As
null literal is not much used, commonly only the first five
literal types are applied. It is necessary to follow the rules
and maintain the correct syntax while using any literal in
Java.

Data Types in Java


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

Java Primitive Data Types


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 is a statically-typed programming language. It means, all variables

must be declared before its use. That is why we need to declare variable's type and name.

There are 8 types of primitive data types:

3.3K

Lumia 735 Hands-On

Next

o boolean data type


o byte data type
o char data type
o short data type
o int data type
o long data type
o float data type
o double data type
Data Type Default Value

boolean false

char '\u0000'

byte 0

short 0

int 0

long 0L

float 0.0f

double 0.0d
Boolean Data Type
The Boolean data type is used to store only two possible values: true and
false. This data type is used for simple flags that track true/false conditions.

The Boolean data type specifies one bit of information, but its "size" can't be
defined precisely.

Example:

1. Boolean one = false

Byte Data Type


The byte data type is an example of primitive data type. It isan 8-bit signed
two's complement integer. Its value-range lies between -128 to 127
(inclusive). Its minimum value is -128 and maximum value is 127. Its default
value is 0.

The byte data type is used to save memory in large arrays where the
memory savings is most required. It saves space because a byte is 4 times
smaller than an integer. It can also be used in place of "int" data type.

Example:

1. byte a = 10, byte b = -20

Short Data Type


The short data type is a 16-bit signed two's complement integer. Its value-
range lies between -32,768 to 32,767 (inclusive). Its minimum value is -
32,768 and maximum value is 32,767. Its default value is 0.
The short data type can also be used to save memory just like byte data
type. A short data type is 2 times smaller than an integer.

Example:

1. short s = 10000, short r = -5000

Int Data Type


The int data type is a 32-bit signed two's complement integer. Its value-
range lies between - 2,147,483,648 (-2^31) to 2,147,483,647 (2^31 -1)
(inclusive). Its minimum value is - 2,147,483,648and maximum value is
2,147,483,647. Its default value is 0.

The int data type is generally used as a default data type for integral values
unless if there is no problem about memory.

Example:

1. int a = 100000, int b = -200000

Long Data Type


The long data type is a 64-bit two's complement integer. Its value-range lies
between -9,223,372,036,854,775,808(-2^63) to
9,223,372,036,854,775,807(2^63 -1)(inclusive). Its minimum value is -
9,223,372,036,854,775,808and maximum value is
9,223,372,036,854,775,807. Its default value is 0. The long data type is used
when you need a range of values more than those provided by int.

Example:
1. long a = 100000L, long b = -200000L

Float Data Type


The float data type is a single-precision 32-bit IEEE 754 floating point.Its
value range is unlimited. It is recommended to use a float (instead of double)
if you need to save memory in large arrays of floating point numbers. The
float data type should never be used for precise values, such as currency. Its
default value is 0.0F.

Example:

1. float f1 = 234.5f

Double Data Type


The double data type is a double-precision 64-bit IEEE 754 floating point. Its
value range is unlimited. The double data type is generally used for decimal
values just like float. The double data type also should never be used for
precise values, such as currency. Its default value is 0.0d.

Example:

1. double d1 = 12.3
Char Data Type
The char data type is a single 16-bit Unicode character. Its value-range lies
between '\u0000' (or 0) to '\uffff' (or 65,535 inclusive).The char data type is
used to store characters.

Example:

1. char letterA = 'A'

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.

Java Operator Precedence


Operator Type Category Precedence

Unary postfix expr++ expr--


prefix ++expr --expr +expr -expr ~

Arithmetic multiplicative * / %

additive + -

Shift shift << >> >>>

Relational comparison < > <= >= instanceof

equality == !=

Bitwise bitwise AND &

bitwise exclusive OR ^

bitwise inclusive OR |

Logical logical AND &&

logical OR ||

Ternary ternary ? :

Assignment assignment = += -= *= /= %= &= ^= |= <<

Java Unary Operator


The Java unary operators require only one operand. Unary operators are
used to perform various operations i.e.:

Skip Ad

o incrementing/decrementing a value by one


o negating an expression
o inverting the value of a boolean
Java Unary Operator Example: ++ and --
1. public class OperatorExample{
2. public static void main(String args[]){
3. int x=10;
4. System.out.println(x++);//10 (11)
5. System.out.println(++x);//12
6. System.out.println(x--);//12 (11)
7. System.out.println(--x);//10
8. }}

Output:

10
12
12
10

Java Unary Operator Example 2: ++ and --


1. public class OperatorExample{
2. public static void main(String args[]){
3. int a=10;
4. int b=10;
5. System.out.println(a++ + ++a);//10+12=22
6. System.out.println(b++ + b++);//10+11=21
7.
8. }}

Output:

22
21

Java Unary Operator Example: ~ and !


1. public class OperatorExample{
2. public static void main(String args[]){
3. int a=10;
4. int b=-10;
5. boolean c=true;
6. boolean d=false;
7. System.out.println(~a);//-11 (minus of total positive value which starts from 0)
8. System.out.println(~b);//9 (positive of total minus, positive starts from 0)
9. System.out.println(!c);//false (opposite of boolean value)
10.System.out.println(!d);//true
11.}}

Output:

-11
9
false
true

Java Arithmetic Operators


Java arithmetic operators are used to perform addition, subtraction,
multiplication, and division. They act as basic mathematical operations.

Java Arithmetic Operator Example


1. public class OperatorExample{
2. public static void main(String args[]){
3. int a=10;
4. int b=5;
5. System.out.println(a+b);//15
6. System.out.println(a-b);//5
7. System.out.println(a*b);//50
8. System.out.println(a/b);//2
9. System.out.println(a%b);//0
10.}}

Output:

15
5
50
2
0

Java Arithmetic Operator Example: Expression


1. public class OperatorExample{
2. public static void main(String args[]){
3. System.out.println(10*10/5+3-1*4/2);
4. }}
Output:

21

Java Left Shift Operator


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.

Java Left Shift Operator Example


1. public class OperatorExample{
2. public static void main(String args[]){
3. System.out.println(10<<2);//10*2^2=10*4=40
4. System.out.println(10<<3);//10*2^3=10*8=80
5. System.out.println(20<<2);//20*2^2=20*4=80
6. System.out.println(15<<4);//15*2^4=15*16=240
7. }}

Output:

40
80
80
240

Java Right Shift Operator


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.

Java Right Shift Operator Example


1. public OperatorExample{
2. public static void main(String args[]){
3. System.out.println(10>>2);//10/2^2=10/4=2
4. System.out.println(20>>2);//20/2^2=20/4=5
5. System.out.println(20>>3);//20/2^3=20/8=2
6. }}

Output:

2
5
2
Java Shift Operator Example: >> vs >>>
1. public class OperatorExample{
2. public static void main(String args[]){
3. //For positive number, >> and >>> works same
4. System.out.println(20>>2);
5. System.out.println(20>>>2);
6. //For negative number, >>> changes parity bit (MSB) to 0
7. System.out.println(-20>>2);
8. System.out.println(-20>>>2);
9. }}

Output:

5
5
-5
1073741819

Java AND Operator Example: Logical && and Bitwise &


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.

1. public class OperatorExample{


2. public static void main(String args[]){
3. int a=10;
4. int b=5;
5. int c=20;
6. System.out.println(a<b&&a<c);//false && true = false
7. System.out.println(a<b&a<c);//false & true = false
8. }}

Output:

false
false

Java AND Operator Example: Logical && vs Bitwise &


1. public class OperatorExample{
2. public static void main(String args[]){
3. int a=10;
4. int b=5;
5. int c=20;
6. System.out.println(a<b&&a++<c);//false && true = false
7. System.out.println(a);//10 because second condition is not checked
8. System.out.println(a<b&a++<c);//false && true = false
9. System.out.println(a);//11 because second condition is checked
10.}}

Output:

false
10
false
11

Java OR Operator Example: Logical || and Bitwise |


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.

The bitwise | operator always checks both conditions whether first condition
is true or false.

1. public class OperatorExample{


2. public static void main(String args[]){
3. int a=10;
4. int b=5;
5. int c=20;
6. System.out.println(a>b||a<c);//true || true = true
7. System.out.println(a>b|a<c);//true | true = true
8. //|| vs |
9. System.out.println(a>b||a++<c);//true || true = true
10.System.out.println(a);//10 because second condition is not checked
11.System.out.println(a>b|a++<c);//true | true = true
12.System.out.println(a);//11 because second condition is checked
13.}}

Output:
true
true
true
10
true
11

Java Ternary Operator


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.

Java Ternary Operator Example


1. public class OperatorExample{
2. public static void main(String args[]){
3. int a=2;
4. int b=5;
5. int min=(a<b)?a:b;
6. System.out.println(min);
7. }}

Output:

Another Example:

1. public class OperatorExample{


2. public static void main(String args[]){
3. int a=10;
4. int b=5;
5. int min=(a<b)?a:b;
6. System.out.println(min);
7. }}

Output:

5
Java 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.

Java Assignment Operator Example


1. public class OperatorExample{
2. public static void main(String args[]){
3. int a=10;
4. int b=20;
5. a+=4;//a=a+4 (a=10+4)
6. b-=4;//b=b-4 (b=20-4)
7. System.out.println(a);
8. System.out.println(b);
9. }}

Output:

14
16

Java Assignment Operator Example


1. public class OperatorExample{
2. public static void main(String[] args){
3. int a=10;
4. a+=3;//10+3
5. System.out.println(a);
6. a-=4;//13-4
7. System.out.println(a);
8. a*=2;//9*2
9. System.out.println(a);
10.a/=2;//18/2
11.System.out.println(a);
12.}}

Output:

13
9
18
9

Java Assignment Operator Example: Adding short


1. public class OperatorExample{
2. public static void main(String args[]){
3. short a=10;
4. short b=10;
5. //a+=b;//a=a+b internally so fine
6. a=a+b;//Compile time error because 10+10=20 now int
7. System.out.println(a);
8. }}

Output:

Compile time error

After type cast:

1. public class OperatorExample{


2. public static void main(String args[]){
3. short a=10;
4. short b=10;
5. a=(short)(a+b);//20 which is int now converted to short
6. System.out.println(a);
7. }}

Output:

20

Java Comments
Comments can be used to explain Java code, and to make it more readable. It
can also be used to prevent execution when testing alternative code.
Single-line Comments
Single-line comments start with two forward slashes ( //).

Any text between // and the end of the line is ignored by Java (will not be
executed).

This example uses a single-line comment before a line of code:

Example
// This is a comment

System.out.println("Hello World");

This example uses a single-line comment at the end of a line of code:

Example
System.out.println("Hello World"); // This is a comment

Java Multi-line Comments


Multi-line comments start with /* and ends with */.

Any text between /* and */ will be ignored by Java.

This example uses a multi-line comment (a comment block) to explain the code:

Example
/* The code below will print the words Hello World

to the screen, and it is amazing */

System.out.println("Hello World");

Loops in Java
Looping in programming languages is a feature which facilitates the
execution of a set of instructions/functions repeatedly while some
condition evaluates to true. Java provides three ways for executing the
loops. While all the ways provide similar basic functionality, they differ
in their syntax and condition checking time.
 while loop: A while loop is a control flow statement that allows
code to be executed repeatedly based on a given Boolean condition.
The while loop can be thought of as a repeating if statement.
Syntax :

while (boolean condition)


{
loop statements...
}
 Flowchart:

 While loop starts with the checking of condition. If it


evaluated to true, then the loop body statements are
executed otherwise first statement following the loop is
executed. For this reason it is also called Entry control
loop
 Once the condition is evaluated to true, the statements in
the loop body are executed. Normally the statements
contain an update value for the variable being processed for
the next iteration.
 When the condition becomes false, the loop terminates
which marks the end of its life cycle.
 for loop: for loop provides a concise way of writing the loop
structure. Unlike a while loop, a for statement consumes the
initialization, condition and increment/decrement in one line thereby
providing a shorter, easy to debug structure of looping.

Syntax:

for (initialization condition; testing condition;


increment/decrement)
{
statement(s)
}
 Flowchart:

 Initialization condition: Here, we initialize the variable in


use. It marks the start of a for loop. An already declared
variable can be used or a variable can be declared, local to
loop only.
 Testing Condition: It is used for testing the exit condition
for a loop. It must return a boolean value. It is also an Entry
Control Loop as the condition is checked prior to the
execution of the loop statements.
 Statement execution: Once the condition is evaluated to
true, the statements in the loop body are executed.
 Increment/ Decrement: It is used for updating the
variable for next iteration.
 Loop termination:When the condition becomes false, the
loop terminates marking the end of its life cycle.
 do while: do while loop is similar to while loop with only difference
that it checks for condition after executing the statements, and
therefore is an example of Exit Control Loop.

Syntax:

do
{
statements..
}
while (condition);
 Flowchart:

 do while loop starts with the execution of the statement(s).


There is no checking of any condition for the first time.
 After the execution of the statements, and update of the
variable value, the condition is checked for true or false
value. If it is evaluated to true, next iteration of loop starts.
 When the condition becomes false, the loop terminates
which marks the end of its life cycle.
 It is important to note that the do-while loop will execute its
statements atleast once before any condition is checked,
and therefore is an example of exit control loop.
Pitfalls of Loops
 Infinite loop: One of the most common mistakes while
implementing any sort of looping is that it may not ever exit, that is
the loop runs for infinite time. This happens when the condition fails
for some reason. Examples:
 Java

//Java program to illustrate various pitfalls.

public class LooppitfallsDemo

{
public static void main(String[] args)

// infinite loop because condition is not apt

// condition should have been i>0.

for (int i = 5; i != 0; i -= 2)

System.out.println(i);

int x = 5;

// infinite loop because update statement

// is not provided.

while (x == 5)

System.out.println("In the loop");

}
Another pitfall is that you might be adding something into you
collection object through loop and you can run out of memory. If you
try and execute the below program, after some time, out of memory
exception will be thrown.

 Java

//Java program for out of memory exception.

import java.util.ArrayList;

public class Integer1

public static void main(String[] args)

ArrayList<Integer> ar = new ArrayList<>();

for (int i = 0; i < Integer.MAX_VALUE; i++)

ar.add(i);

Output:
Exception in thread "main" java.lang.OutOfMemoryError: Java heap
space
at java.util.Arrays.copyOf(Unknown Source)
at java.util.Arrays.copyOf(Unknown Source)
at java.util.ArrayList.grow(Unknown Source)
at java.util.ArrayList.ensureCapacityInternal(Unknown Source)
at java.util.ArrayList.add(Unknown Source)
at article.Integer1.main(Integer1.java:9)

Java Conditions and If Statements


The if Statement
Use the if statement to specify a block of Java code to be executed if a
condition is true.

Syntax
if (condition) {

// block of code to be executed if the condition is true

Note that if is in lowercase letters. Uppercase letters (If or IF) will generate an
error.

In the example below, we test two values to find out if 20 is greater than 18. If
the condition is true, print some text:

Example
if (20 > 18) {

System.out.println("20 is greater than 18");

The else Statement


Use the else statement to specify a block of code to be executed if the condition
is false.
Syntax
if (condition) {

// block of code to be executed if the condition is true

} else {

// block of code to be executed if the condition is false

Example
int time = 20;

if (time < 18) {

System.out.println("Good day.");

} else {

System.out.println("Good evening.");

// Outputs "Good evening."

Example explained
In the example above, time (20) is greater than 18, so the condition is false.
Because of this, we move on to the else condition and print to the screen "Good
evening". If the time was less than 18, the program would print "Good day".

The else if Statement


Use the else if statement to specify a new condition if the first condition
is false.
Syntax
if (condition1) {

// block of code to be executed if condition1 is true

} else if (condition2) {

// block of code to be executed if the condition1 is false and


condition2 is true

} else {

// block of code to be executed if the condition1 is false and


condition2 is false

Example
int time = 22;

if (time < 10) {

System.out.println("Good morning.");

} else if (time < 20) {

System.out.println("Good day.");

} else {

System.out.println("Good evening.");

// Outputs "Good evening."

Example explained
In the example above, time (22) is greater than 10, so the first
condition is false. The next condition, in the else if statement, is also false,
so we move on to the else condition since condition1 and condition2 is
both false - and print to the screen "Good evening".

However, if the time was 14, our program would print "Good day."
Java Switch Statements
Use the switch statement to select one of many code blocks to be executed.

Syntax
switch(expression) {

case x:

// code block

break;

case y:

// code block

break;

default:

// code block

This is how it works:

 The switch expression is evaluated once.


 The value of the expression is compared with the values of each case.
 If there is a match, the associated block of code is executed.
 The break and default keywords are optional, and will be described later
in this chapter

The example below uses the weekday number to calculate the weekday name:

Example
int day = 4;

switch (day) {

case 1:

System.out.println("Monday");
break;

case 2:

System.out.println("Tuesday");

break;

case 3:

System.out.println("Wednesday");

break;

case 4:

System.out.println("Thursday");

break;

case 5:

System.out.println("Friday");

break;

case 6:

System.out.println("Saturday");

break;

case 7:

System.out.println("Sunday");

break;

// Outputs "Thursday" (day 4)

The break Keyword


When Java reaches a break keyword, it breaks out of the switch block.
This will stop the execution of more code and case testing inside the block.

When a match is found, and the job is done, it's time for a break. There is no
need for more testing.

A break can save a lot of execution time because it "ignores" the execution of all
the rest of the code in the switch block.

The default Keyword


The default keyword specifies some code to run if there is no case match:

Example
int day = 4;

switch (day) {

case 6:

System.out.println("Today is Saturday");

break;

case 7:

System.out.println("Today is Sunday");

break;

default:

System.out.println("Looking forward to the Weekend");

// Outputs "Looking forward to the Weekend"

Note that if the default statement is used as the last statement in a switch
block, it does not need a break.
Java While Loop

Loops
Loops can execute a block of code as long as a specified condition is reached.

Loops are handy because they save time, reduce errors, and they make code
more readable.

Java While Loop


The while loop loops through a block of code as long as a specified condition
is true:

Syntax
while (condition) {

// code block to be executed

In the example below, the code in the loop will run, over and over again, as long
as a variable (i) is less than 5:

Example
int i = 0;

while (i < 5) {

System.out.println(i);

i++;
}

Note: Do not forget to increase the variable used in the condition, otherwise the
loop will never end!

The Do/While Loop


The do/while loop is a variant of the while loop. This loop will execute the
code block once, before checking if the condition is true, then it will repeat the
loop as long as the condition is true.

Syntax
do {

// code block to be executed

while (condition);

The example below uses a do/while loop. The loop will always be executed at
least once, even if the condition is false, because the code block is executed
before the condition is tested:

Example
int i = 0;
do {

System.out.println(i);

i++;

while (i < 5);


Java For Loop

Java For Loop


When you know exactly how many times you want to loop through a block of
code, use the for loop instead of a while loop:

Syntax
for (statement 1; statement 2; statement 3) {

// code block to be executed

Statement 1 is executed (one time) before the execution of the code block.

Statement 2 defines the condition for executing the code block.

Statement 3 is executed (every time) after the code block has been executed.

The example below will print the numbers 0 to 4:

Example
for (int i = 0; i < 5; i++) {

System.out.println(i);

Java For Each Loop


For-Each Loop
There is also a "for-each" loop, which is used exclusively to loop through
elements in an array:

Syntax
for (type variableName : arrayName) {

// code block to be executed

The following example outputs all elements in the cars array, using a "for-
each" loop:

Example
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};

for (String i : cars) {

System.out.println(i);

Java Break and Continue

Java Break
You have already seen the break statement used in an earlier chapter of this
tutorial. It was used to "jump out" of a switch statement.

The break statement can also be used to jump out of a loop.

This example stops the loop when i is equal to 4:


Example
for (int i = 0; i < 10; i++) {

if (i == 4) {

break;

System.out.println(i);

Java Continue
The continue statement breaks one iteration (in the loop), if a specified
condition occurs, and continues with the next iteration in the loop.

This example skips the value of 4:

Example
for (int i = 0; i < 10; i++) {

if (i == 4) {

continue;

System.out.println(i);

Type Casting in Java


In Java, type casting is a method or process that converts a data type into
another data type in both ways manually and automatically. The automatic
conversion is done by the compiler and manual conversion performed by the
programmer. In this section, we will discuss type casting and its
types with proper examples.

Type casting
Convert a value from one data type to another data type is known as type
casting.

Types of Type Casting


There are two types of type casting:

o Widening Type Casting


o Narrowing Type Casting

Widening Type Casting


Converting a lower data type into a higher one is called widening type
casting. It is also known as implicit conversion or casting down. It is done
automatically. It is safe because there is no chance to lose data. It takes
place when:

o Both data types must be compatible with each other.


o The target type must be larger than the source type.

1. byte -> short -> char -> int -> long -> float -> double
For example, the conversion between numeric data type to char or Boolean
is not done automatically. Also, the char and Boolean data types are not
compatible with each other. Let's see an example.

WideningTypeCastingExample.java

1. public class WideningTypeCastingExample


2. {
3. public static void main(String[] args)
4. {
5. int x = 7;
6. //automatically converts the integer type into long type
7. long y = x;
8. //automatically converts the long type into float type
9. float z = y;
10.System.out.println("Before conversion, int value "+x);
11.System.out.println("After conversion, long value "+y);
12.System.out.println("After conversion, float value "+z);
13.}
14.}

Output

Before conversion, the value is: 7


After conversion, the long value is: 7
After conversion, the float value is: 7.0

In the above example, we have taken a variable x and converted it into a


long type. After that, the long type is converted into the float type.

Narrowing Type Casting


Converting a higher data type into a lower one is called narrowing type
casting. It is also known as explicit conversion or casting up. It is done
manually by the programmer. If we do not perform casting then the compiler
reports a compile-time error.

1. double -> float -> long -> int -> char -> short -> byte

Let's see an example of narrowing type casting.


In the following example, we have performed the narrowing type casting two
times. First, we have converted the double type into long data type after that
long data type is converted into int type.

NarrowingTypeCastingExample.java

1. public class NarrowingTypeCastingExample


2. {
3. public static void main(String args[])
4. {
5. double d = 166.66;
6. //converting double data type into long data type
7. long l = (long)d;
8. //converting long data type into int data type
9. int i = (int)l;
10.System.out.println("Before conversion: "+d);
11.//fractional part lost
12.System.out.println("After conversion into long type: "+l);
13.//fractional part lost
14.System.out.println("After conversion into int type: "+i);
15.}
16.}

Output

Before conversion: 166.66


After conversion into long type: 166
After conversion into int type: 166

You might also like