Java_07_22_22
Java_07_22_22
Identifiers:
}
}
MyVariable
MYVARIABLE
myvariable
x
i
x1
i1
_myvariable
$myvariable
sum_of_array
geeks123
Examples of invalid identifiers :
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.
1. abstract
2. boolean:
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
7. char
: Java char keyword is used to declare a variable that can hold unsigned 16-
bit Unicode characters
8. 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
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
15. extends
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
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
22. import
: Java import keyword makes classes and interfaces available and accessible
to the current source code.
23. instanceof
24. int
: Java int keyword is used to declare a variable that can hold a 32-bit signed
integer.
25. interface
26. long
: Java long keyword is used to declare a variable that can hold a 64-bit
integer.
: 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
32. protected
33. public
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
38. super
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
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
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
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.
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":
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:
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:
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;
Other Types
A demonstration of how to declare variables of other types:
Example
int myNum = 5;
Literal in Java
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
Backlash \\ 92 0x5c
Newline \n 10 0x0a
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.
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
must be declared before its use. That is why we need to declare variable's type and name.
3.3K
Next
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:
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:
Example:
The int data type is generally used as a default data type for integral values
unless if there is no problem about memory.
Example:
Example:
1. long a = 100000L, long b = -200000L
Example:
1. float f1 = 234.5f
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:
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.
Arithmetic multiplicative * / %
additive + -
equality == !=
bitwise exclusive OR ^
bitwise inclusive OR |
logical OR ||
Ternary ternary ? :
Skip Ad
Output:
10
12
12
10
Output:
22
21
Output:
-11
9
false
true
Output:
15
5
50
2
0
21
Output:
40
80
80
240
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
The bitwise & operator always checks both conditions whether first condition
is true or false.
Output:
false
false
Output:
false
10
false
11
The bitwise | operator always checks both conditions whether first condition
is true or false.
Output:
true
true
true
10
true
11
Output:
Another Example:
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.
Output:
14
16
Output:
13
9
18
9
Output:
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).
Example
// This is a comment
System.out.println("Hello World");
Example
System.out.println("Hello World"); // This is a comment
This example uses a multi-line comment (a comment block) to explain the code:
Example
/* The code below will print the words Hello World
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 :
Syntax:
Syntax:
do
{
statements..
}
while (condition);
Flowchart:
{
public static void main(String[] args)
for (int i = 5; i != 0; i -= 2)
System.out.println(i);
int x = 5;
// is not provided.
while (x == 5)
}
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
import java.util.ArrayList;
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)
Syntax
if (condition) {
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) {
} else {
Example
int time = 20;
System.out.println("Good day.");
} else {
System.out.println("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".
} else if (condition2) {
} else {
Example
int time = 22;
System.out.println("Good morning.");
System.out.println("Good day.");
} else {
System.out.println("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
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;
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.
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:
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.
Syntax
while (condition) {
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!
Syntax
do {
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++;
Syntax
for (statement 1; statement 2; statement 3) {
Statement 1 is executed (one time) before the execution of the code block.
Statement 3 is executed (every time) after the code block has been executed.
Example
for (int i = 0; i < 5; i++) {
System.out.println(i);
Syntax
for (type variableName : arrayName) {
The following example outputs all elements in the cars array, using a "for-
each" loop:
Example
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
System.out.println(i);
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.
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.
Example
for (int i = 0; i < 10; i++) {
if (i == 4) {
continue;
System.out.println(i);
Type casting
Convert a value from one data type to another data type is known as type
casting.
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
Output
1. double -> float -> long -> int -> char -> short -> byte
NarrowingTypeCastingExample.java
Output