Java Naming Conventions:
Java is case sensitive, which means identifier Hello and hello would have different meaning in Java.
It is very important to follow the naming conventions given below while coding a Java program.
• Class Names - For all class names, the first letter should be in Upper Case. If several words are used to form
a name of the class, each inner word's first letter should be in Upper Case.
E.g., class MyFirstJavaClass
• Method Names - All method names should start with a Lower Case letter. If several words are used to form
the name of the method, then each inner word's first letter should be in upper case.
E.g., public void myMethodName()
• Program File Name - Name of the program file should exactly match the class name.
The file should be saved using the class name (Java is case sensitive) and append '.java' to the end of the name
(if the file name and the class name do not match, the program will not compile).
E.g., : Assume 'MyFirstJavaProgram' is the class name, then the file should be saved as
'[Link]'
(*optional) Java Identifiers: All Java components require names. Names used for classes, variables and methods
are called identifiers.
The following Identifiers naming rules :
➢ All identifiers should begin with a letter (A to Z or a to z), currency character ($) or an underscore (_).
➢ After the first character, identifiers can have any combination of characters.
➢ A keyword cannot be used as an identifier.
➢ Most importantly identifiers are case sensitive.
➢ Examples of legal identifiers:age, $salary, _value, __1_value
➢ Examples of illegal identifiers: 123abc, -salary
-*-*-*-*-
(*optional) Java Keywords: The following are Java reserved words . These should not be used as constant /
variable or any other identifier names and class, or method names.
*The keywords are sorted row-wise.
Page 1 of 8
Data Types in Java : Java is a strongly typed language. Every variable has a type, every expression has a type,
and every type is strictly defined. All assignments, whether explicit or via parameter passing in method calls, are
checked for type compatibility. There are no automatic coercions or conversions of conflicting types in Java.
Java defines eight primitive types of data: byte, short, int, long, char, float, double, and boolean.
The primitive types are also referred to as simple types.
These can be put in four groups:
1. Integers: This group includes byte, short, int, and long, which are for whole-valued signed numbers.
2. Floating-point numbers: This group includes float and double, which represent numbers with fractional
precision.
3. Characters: This group includes char, which represents symbols in a character set, like letters and numbers.
4. Boolean: This group includes boolean, which is a special type for representing true/false values.
All data types have a strictly defined range.
Width
Name Range
in Bits
byte 8 128 to 127
short 16 –32768 to 32767
int 32 –2,147,483,648 to 2,147,483,647
long 64 –9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
float 32 1.4e–045 to 3.4e+038
double 64 4.9e–324 to 1.8e+308
char 16 0 to 65,536
Variables: The variable is the basic unit of storage. It is defined by the combination of an identifier, a type, and
an optional initializer. All variables have a scope, which defines their visibility, and a lifetime.
The variables must be declared before they are used.
type identifier [ = value][, identifier [= value] ...] ;
The type is an primitive type, or the name of a class or an interface.
A variable can be initialized at the time of declaration.
Eg., double side = 2.7;
A variable can be initialized dynamically, using any expression valid at the time the variable is declared.
Eg., int a =10;
int b = 20;
int c = a*b; // dynamic initialization.
Automatic Conversions: When one type of data is assigned to another type of variable, an automatic type
conversion will take place if the following two conditions are met:
• The two types are compatible.
• The destination type is larger than the source type.
When these two conditions are met, a widening conversion takes place.
There are no automatic conversions from the numeric types to char or boolean.
Page 2 of 8
Casting: If int value to assign an a byte variable, automatic type conversion does not take place. Because a byte
is smaller than an int. To convert between incompatible types, explicit cast should be done. This kind of
conversion is called narrowing conversion, since it explicitly makes the value narrower so that it will fit into the
target type.
A cast is simply an explicit type conversion. The general form is –
(target-type) value
Eg., int a;
byte b;
// ...
b = (byte) a;
A different type of conversion will occur when a floating-point value is assigned to an integer type: truncation.
When a floating-point value is assigned to an integer type, the fractional component is lost.
Eg., int a = 1.234; // a value is 1. The fractional part, 0.234 is truncated.
(*optional) Operators:
Arithmetic Operators:
(*optional) Bitwise Operators: The bitwise operators that can be applied to the integer types, long, int, short,
char, and byte. These operators act upon the individual bits of their operands.
Page 3 of 8
(*optional) Relational Operators: The relational operators determine the relationship that one operand has to
the other.
Specifically, they determine equality and ordering. The outcome of these operations is a boolean value. The
relational operators are most frequently used in the expressions that control the if statement and the various
loop statements.
(*optional) Boolean Logical Operators: The Boolean logical operators operate only on boolean operands.
All of the binary logical operators combine two boolean values to form a resultant boolean value.
(*optional) Follow the steps given below to type and run a Java program:
o Open notepad
o Type the Java Program code.
o Save the file having extension .java and file name should be the same as the class having the main()
method.
o Open command prompt window and go o the directory where program file saved.
o Type ' javac file_name.java ' (if file name is [Link], type javac [Link]) to compile the
program.
o If there are no errors in the code, the command prompt will take to the next line.
o Type ' java file_name ' (if file name is [Link], type java MyClass) to run the program.
Comments: Java allows to enter a remark in a program’s source file. A comment describes the purpose of the
program and key points in the program for further communication to the readers of the program. The comments
are ignored by the compiler while compiling the program.
Java supports three types of comments.
1. // comment text : This is used for single line comments. The text after // to end of the line ignored while
compiling.
2. /* comment line – 1
comment line – 2
:
*/ :
Page 4 of 8
This is used for multi-line comments. The text existing between the characters /* and */ will be ignored while
compiling the program.
3. /** comment text */ :
The third type is called a documentation comment. It begins with the character sequence /** and ends with
*/.
Documentation comments allows to embed information about the program into the program itself.
javadoc utility program (supplied with the JDK) used to extract the information and put it into an HTML file.
(*optional) Control Statements:
if Statement : if statement can be used to execute a block of statements based on the given condition.
if(condition)
statement;
The statements block executed if the given condition returns true.
Eg., if(num < 100)
[Link]("num is less than 100");
if-else statement can be used to execute an alternate statement block if the given condition returns false.
if(condition)
statements-t;
else
statements-f;
The statements-t block executed when the given condition (logical expression) returns ‘true’. Otherwise (if the condition
returns ‘false’), the statements-f block executed..
Eg. if ( num % 2 == 0 )
[Link] ("num is even");
else
[Link] ("num is odd");
(*optional) Switch: The switch statement is a multiway branch statement.
It provides an easy way to dispatch execution to different parts of the code based on the value of an expression.
It provides a better alternative for a large series of if-else-if statements. The general form of switch statement is –
switch (expression) {
case value1:
// statement sequence
break;
case value2:
// statement sequence
break;
...
case valueN:
// statement sequence
break;
default:
// default statement sequence
}
Page 5 of 8
The expression must be of type byte, short, int, or char; each of the values specified in the case statements must be of a
type compatible with the expression.
An enumeration value can also be used for a switch statement.
Each case value must be a unique literal. It must be a constant, not a variable.
Duplicate case values are not allowed.
The value of the expression is compared with each of the literal values in the case statements. If a match is found, the
code sequence following that case statement is executed.
If none of the constants matches the value of the expression, then the default statement is executed.
The default statement is optional.
The break statement is used inside the switch to terminate a statement sequence .
o The switch differs from the if in that switch can only test for equality, whereas if can evaluate any type of Boolean
expression.
o No two case constants in the same switch can have identical values.
o A switch statement is usually more efficient than a set of nested ifs.
(*optional) for Loop : A for loop can be used to execute a block of statements for a definite number of times.
for(initialization; condition; iteration)
statement;
o The initialization portion of the loop sets a loop control variable to an initial value.
o The condition is a Boolean expression that tests the loop control variable. If the outcome of that test is true,
the loop iterates. If it is false, the loop terminates.
o The iteration expression determines how the loop control variable is changed each time the loop iterates.
Note: Java provides for-each version of for loop that can be used to process elements of a collection data type.
(*optional) while: The while loop is repeats a statement or block while its controlling expression is true.
Its general form:
while(condition) {
// body of loop
}
The condition can be any Boolean expression.
The body of the loop will be executed as long as the conditional expression is true. When condition becomes false, control
passes to the next line of code immediately following the loop.
The body of the loop may not execute even once if the condition is false at the first time iteration.
(*optional) do..while: The do-while loop evaluates its conditional expression is at the bottom of the loop. It always
executes its body at least once (first time). The general form is –
do
{
// body of loop
} while (condition);
Each iteration of the do-while loop first executes the body of the loop and then evaluates the conditional expression. If the
expression is true, the loop will repeat. Otherwise, the loop terminates.
(*optional) break: break keyword in a loop can be used to terminate the execution of the current loop. Generally, break
applied in association with a condition that differs from loop’s condition.
(*optional) continue: it is forces an early iteration of a loop.
In while and do-while loops, a continue transfers control to the conditional expression that controls the loop.
In a for loop, control goes first to the iteration portion and then to the conditional expression.
Page 6 of 8
Arrays: An array is a group of like-typed variables that are referred to by a common name.
Arrays groups related information.
Arrays of any type can be created and may have one or more dimensions.
A specific element in an array is accessed by its index.
A one-dimensional array is a list of like-typed variables.
The general form of a one-dimensional array declaration is -
type var-name[ ];
Eg., int month_days[];
type declares the base type of the array that is what type of values stored in each element of the array.
The above declaration does not create array physically. The array name is set to null, indicating no valid data exists.
o To create a physical array memory should be allotted using new operator.
The general form is -
array-var = new type[size];
Eg.,month_days = new int[12];
Now, the array allotted memory to store 12 int values and all the elements are initialized to zero.
o The array declaration and memory allocation can be combined within a single statement.
int month_days = new int[12];
o An array can be initialized with desired values at the time of declaration. The values can be put in a pair of braces.
Eg., int age[5] = { 22, 21, 20, 19, 21};
****
for-each model loop: Java provides a second form of for loop known as “for-each” style loop.
It is also referred to as the enhanced for loop.
The general form of the for-each version of the for loop is given below:
for (type itr-var : collection)
statement-block;
▪ itr-var specifies the name of an iteration variable.
▪ type specifies the data type of iteration variable.
▪ collection is a variable that contains the list of data, it can be an array or a collection of framework.
With each iteration, the next element in the collection is retrieved and stored in itr-var.
The loop repeats until all elements in the collection have been obtained.
The type must be the same as (or compatible with) the elements stored in the collection.
The for-each style eliminates –
▪ the need for a loop counter,
▪ specifying starting and ending values of loop counter and
▪ manually index the array.
It automatically cycles through the entire array, obtaining one element at a time, in sequence, from beginning
to end.
/* For each loop for 1-D Array */
class ForEach {
public static void main (String args[]) {
int nums [] = {1, 2, 3, 4, 5 };
int sum = 0;
Page 7 of 8
// use for-each style for to display and sum the values
for (int x : nums) {
[Link]("Value is: " + x);
sum += x;
}
[Link]("Summation: " + sum);
}
}
Multidimensional Arrays: In Java, a multidimensional array is an array of arrays.
A multidimensional array can be declared by specifying each dimension size in a separate pair of brackets.
type var-name[ dim-1] [dim-2];
A multidimensional array can be allotted memory using new operator.
Eg., int a[][] = new int [2][3];
Alternative Array Declaration Syntax:
There is a second form that may be used to declare an array:
type[ ] var_name;
The square brackets follow the type specifier, and not the name of the array variable.
Eg., int[] a2 = new int[3];
The above declaration is identical to –
int al[] = new int[3];
Similarly, the declaration of following two ways of 2-dimensional array is same.
char twod1[][] = new char[3][4];
char[][] twod2 = new char[3][4];
This notation is useful to declare multiple array variables within a single line.
int[] nums, nums2, nums3; // create three arrays
Also, it is a useful notation to specify return type of a method is an array.
Alternatively, the above declaration can be done as shown below –
int nums[], nums2[], nums3[]; // create three arrays
/* For each loop for 2-D Array */
class ForEach2D {
public static void main(String args[]) {
int sum = 0;
int nums[][] = new int[3][4];
//Store values into array
for(int i = 0; i < 3; i++)
for(int j=0; j < 4; j++)
nums[i][j] = i*j;
// use for-each for to display and sum the values
for(int x[] : nums) {
[Link]();
for(int y : x) {
[Link](" " + y);
Su m += y;
}
}
[Link]("\nSum : " + sum);
}
}
Page 8 of 8