Download as pdf or txt
Download as pdf or txt
You are on page 1of 20

Chapter 2: Basics in Java Programming

Chapter 2
Basics in Java Programming
This chapter outlines the core syntax and constructs of the Java language.
Structure of java Program
Java is a pure object oriented language, and hence everything is written within a class block. The
structure of a java program is:
[Documentation] ­­­­­­­­­ suggested
[package statement] ­­­­­­ optional
[import statements] ­­­­­­ optional
[interface statements] ­­­­­­ optional
[class definitions] ­­­­­­ optional
[main­method class] ­­­­­­ Essential 
main method class definition
Creating, Compiling and Running a Java Program
To create java program, you will:
 Create a source file and write in the Java program.
 Compile the source file into a bytecode file using the compiler, javac.
 Run the program contained in the bytecode file using The Java interpreter
installed on your computer.
Note:
 The file name should be the same as the name of the class containing our main-
method. Eg. A main-class named MyFirstClass has to be in the file called
MyFirstClass.java
 A program can contain one or more class definitions but only one public class
definition. This class is called main-class because it contains the main method.
 The program can be created in any text editor.
 If a file contains multiple classes, the file name must be the class name of the
class that contains the main method.
Example:
public class MyFirstJavaProgram {

public static void main(String []args) {


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

C : > javac MyFirstJavaProgram.java


C : > java MyFirstJavaProgram

Hello World

Note: we are using the System and String class directly, because they are found in the
package java.lang in which it is automatically included in any java program.

Page 1 of 20
Chapter 2: Basics in Java Programming

public (access modifier) makes the item visible from outside the class. static
indicates that the main() method is a class method not an instant method. It allows
main() to be called without having to instantiate a particular instance of the class.

Lexical Components of Java Tokens


Java program = Comments + java statements + white space
Java statements are also combinations of java Token(s).
Java tokens are meaningful words and symbols of java programming language.

Java Tokens
Tokens are meaningful words and symbols used by a programming language. They are
the smaller individual units inside a program the compiler recognizes when building up
the program. There are five types of Tokens in Java: Reserved keywords, Identifiers,
Literals, operators, separators.
1. Reserved words (Keywords)
abstract float public
boolean for return
break if short
byte implements static
case import super
catch instanceof switch
char int synchronized
class interface this
continue long throw
default native throws
do new transient
double null try
else operator void
extends package volatile
final private while
finally protected

These reserved words are words with special meaning to the compiler. They could not be
used as constant or variable or any other variable/identifier names.
2. Identifiers
Identifiers are programmer defined tokens. They include names used to identify classes,
methods, variables, objects, packages, and interfaces. Java programming language is
case sensitive language. Example: Mathvar, mathVar, MathVar, etc… are different
identifiers/variables.

Page 2 of 20
Chapter 2: Basics in Java Programming

 Rules in naming Identifier :


The name must begin with
 Letters or
 Underscore characters ( _ ) or
 Any currency symbol (e.g $)
Remaining characters of the name of identifiers could be :
 Letters
 Digits
Example: legal identifiers name: age, $salary, _value, __1_value
illegal identifiers: 123abc, -salary

 Identifiers’ naming conventions


Class names: starts with capital letter and should be inter-capital
Variable names: start with lower case and should be inter-capital
Method names: start with lower case and should be inter-capital
Constants: often written in all capital and use underscore if you are using more
than one word.

3. Literals
Literals are values to be stored in variables. They are a sequence of characters (digits,
letters, & other characters).
4. Operators
Operators are a symbol that take one or more arguments (operands) and operates on them
to produce a result. Eg. +, *, -, /, %...
In general, there are 8-kinds of operators. Categories of operators are as follows:

 Arithmetic operators  Conditional operators


 Logical operators  Increment and decrement operators
 Relational operators  Bit wise operators
 Assignment operators  Special operators

5. Separators
Separators are symbols used to indicate where groups of codes are divided and arranged.
They define the shape and function of our code. Some of them are:

Name Symbol Description


Parenthesis ()
braces {}

Page 3 of 20
Chapter 2: Basics in Java Programming

brackets []
semicolon ;
comma ,
period .
Java Comments
Java allows putting our comments for making clarifications to our java codes. The
compiler skips comments during compiling. These comments can be written using three
ways.

Start End Purpose


/* */ The enclosed text is treated as a comment.
// (none) The rest of the line is treated as a comment.
/** */ The enclosed text is treated as a comment by the
compiler but is used by JavaDoc to automatically
generate documentation.
Example:
/* This is a comment that will span multiple source code lines. */
// This is a comment that will span multiple source code lines.
/** This is a comment that will span multiple source code lines. */
White space: Java white spaces include: space, tab, newline.
Java Statements
Statements are roughly equivalent to sentences in natural languages. A statement is
terminated using a semi colon. It forms a complete unit of execution. Java statements are
categorized as follows
Java statements

Synchronization Guarding
Labeled statement Control statement statement statement

Selection Iteration/loop
Jump statement
statement statement

If( ) While( ) break

If( )… else do…while() continue

Switch( ) for( ) return

Page 4 of 20
Chapter 2: Basics in Java Programming

Labeled statements
Labeled statements are any statements beginning with the key word “label”. The “label”
key word is in combination with “goto”.
Synchronization statement
Are statements used for handling issues related with multi-threading (multi tasking).

Guarding statements
Guarding statements are statements used for handling errors (exceptions). The three key
words used in handling exceptions are: try, catch, and finally.

Blocks
A block is a group of zero or more statements between a pair of braces and can be used
anywhere even for a single statement. Example:
if ( Character.isUpperCase(aChar) ) {
System.out.println("The character " + aChar + " is upper case.");
}
else {
System.out.println("The character " + aChar + " is lower case.");
}

Constants, Variables and Data Types


Constants
Constants are fixed values (literals to be stored in variables) that do not change during the
execution of a program.
Java constants

Non-numeric
Numeric constants
constants

Character
Integer constants Real constants String constants
constants

Examples of constants:
23411--- integer constant
O425 --- octal constants(begin with ‘A’ ---- character constants
the letter ‘O’) ‘7’---- character constants
0x7 ---- hexadecimal constants ‘\’ ---- character constants
00X---- hexadecimal constants “WELCOME” ---- string constatns
0A2B---- hexadecimal constants “THE-END” ---- string constatns
0.0234 ---- real constants “BYE …BYE” ---- string constatns
0.777 ---- real constants “A” ---- string constatns
-1.23 ---- real constants

Page 5 of 20
Chapter 2: Basics in Java Programming

Variables
Variables are identifiers that denote a storage location t store a data values. i.e. they are
names of storage locations.

Data types
All kinds of data that can be stored in computer do not take the same space and the same
operations cannot be made on them. Example let’s take the name “Alexander” and the
number “20”. The two items (data) do not take the same memory space and also
operations. Multiplication operation can be made on the number item but not on the
string item.
So, to handle these issues, a mechanism is devised known as “data typing” system.

Data type means “item type to be stored in memory”. They are used to identify
 amount of memory size that should be assigned to a given data/item and
 kinds of operations that could be made on the item.

Based on java programming language, data types are categorized as primitive/built-in and
derived/user-defined.

Integer types
Integer data-type can hold the numbers (the number can be positive number or negative
number). In Java, there are four types of integers: byte, short, int, and long.

Floating types

Page 6 of 20
Chapter 2: Basics in Java Programming

It is also called as Real number and when we require accuracy then we can use it. It is
used to represent decimal numbers. There are two types of decimal numbers: float and
double.

Character data type


It is used to store single character in memory.

Boolean data type


It is used when we want to test a particular condition during the execution of the
program. There are only two values that a boolean type can hold: true and false. Boolean
type is denoted by the keyword boolean and uses only one bit of storage.

The following table shows the data-types with their memory size they take and ranges of
values they can hold.

Variable declaration
Variable declaration does three things:
 Tells the compiler what the variable name is.
 It specifies what type of data(value) the variable will hold.
 The place of declaration in the program decides the scope of the variable.

Syntax to declare a variable is: data-type variable_name;


Syntax to initialize a variable is: variable_name= value;
Initialization and declaration can be done at a time as: data-type variable_name= value;

int a, b, c; // Declares three ints, a, b, and c.


int a = 10, b = 10; // Example of initialization
byte B = 22; // declares and initializes a byte type variable B.
double pi = 3.14159; // declares and assigns a value of PI.
char a = 'a'; // the char variable a is initialized with value 'a'

Giving values to variables is done in two ways:

Page 7 of 20
Chapter 2: Basics in Java Programming

 By using assignment statement: variable_name= value;


 By using readLine() function.

To initialize characters, the characters are placed under single quotes while strings are
under double quotes.

Following program shows the use of datatypes:


import java.io.DataInputStream;
class cc2
{
public static void main(String args[])
throws Exception
{
DataInputStream s1=new
DataInputStream(System.in);
byte rollno;
int marks1,marks2,marks3;
float avg;
System.out.println("Enter roll
number:");
rollno=Byte.parseByte(s1.readLine());
System.out.println("Enter marks m1,
m2,m3:");
marks1=Integer.parseInt(s1.readLine());
marks2=Integer.parseInt(s1.readLine());
marks3=Integer.parseInt(s1.readLine());
avg = (marks1+marks2+marks3)/3;
System.out.println("Roll number
is="+rollno);
System.out.println("Average is="+avg);
}
}
Output:
Enter roll number:
07 Roll number is=7
Enter marks m1, m2,m3: Average is=77.0
66 21 77 88

Page 8 of 20
Chapter 2: Basics in Java Programming

Symbolic constants
Symbolic constants are names given to numbers instead of using the numbers in
programs directly.
Example: instead of using 3.14, we may name it as PI & use the word PI instead of 3.14
in our programs.
Symbolic constants
 Should be in capital letters
 Re-assigning after declaration is illegal
 Cannot be declared inside methods
 Are declared as:
final var_type symbolic_name= value;
Eg: final float PI=3.14;

Backslash character constant:


Java supports some special character constants in which if we want to display them from
our program. These constants are given in following table.

Scope and life time of variables


Java variables are three types:
 Instance variables
 Class variables
 Local variables
Instance variables:
Instance variables are created when objects are instantiated. They are associated
with objects. They take different values for different object.
Class variables:
Class variables are global to a class and belong to the entire set of objects that the
class creates. Only one memory location is created for each class variable. They
are declared as “static” data members.
Local variables:
Are declared and used inside methods/functions. And their scope and life time is
inside the body of the function.

A variable's scope is the region of a program within which the variable can be referred to
by its simple name. A scope also determines when the system creates and destroys

Page 9 of 20
Chapter 2: Basics in Java Programming

memory for the variable. A block defines a scope. Each time you create a block of code,
you are creating a new, nested scope.
Variables are created when their scope is entered, and destroyed when their scope is left.
Thus, the lifetime of a variable is confined to its scope.
Objects declared in the outer block will be visible to code within the inner block down
from the declaration. (The reverse is not true).

Operators
 An operator performs a function on one, two, or three operands. An operator that
requires one operand is called a unary operator. The unary operators support either
prefix or postfix notation. Prefix notation means that the operator appears before its
operand. Postfix notation means that the operator appears after its operand
operator operand; //prefix notation
operand operator; //postfix notation

1. Conditional operator
The character pair ?: is a conditional which is ternary operator of Java, which is
used to construct conditional expressions of the following form:
Expression1 ?Expression3 : Expression3
variable x = (expression) ? value if true : value if false

The operator ? : works as follows:


Expression1 is evaluated if it is true then Expression3 is evaluated and becomes
the value of the conditional expression. If Expression1 is false then Expression3 is
evaluated and its value becomes value of the conditional expression.

public class Test {

public static void main(String args[]){


int a , b;
a = 10;
b = (a == 1) ? 20: 30;
System.out.println( "Value of b is : " + b );

b = (a == 10) ? 20: 30;


System.out.println( "Value of b is : " + b );
}
}

This would produce the following result:

Value of b is : 30
Value of b is : 20

Page 10 of 20
Chapter 2: Basics in Java Programming

Java selection statements: if, if…else, and switch…case


There are two types of decision making statements in Java. They are:

 if statements
 switch statements
The if Statement:
An if statement consists of a Boolean expression followed by one or more statements.
Syntax: The syntax of an if statement is:
if(Boolean_expression)
{
//Statements will execute if the Boolean expression is true
}
If the Boolean expression evaluates to true then the block of code inside the if statement
will be executed. If not the first set of code after the end of the if statement (after the
closing curly brace) will be executed.
Example:

public class Test {

public static void main(String args[]){


int x = 10;

if( x < 20 ){
System.out.print("This is if statement");
}
}
}
This would produce the following result:

This is if statement

The if...else Statement:


An if statement can be followed by an optional else statement, which executes when the Boolean
expression is false.
Syntax: The syntax of an if...else is:
if(Boolean_expression){
//Executes when the Boolean expression is true
}else{
//Executes when the Boolean expression is false
}

Page 11 of 20
Chapter 2: Basics in Java Programming

Example:
public class Test {
public static void main(String args[]){
int x = 30;

if( x < 20 ){
System.out.print("This is if statement");
}else{
System.out.print("This is else statement");
}
}
}
This would produce the following result:

This is else statement

The if...else if...else Statement:


An if statement can be followed by an optional else if...else statement, which is very
useful to test various conditions using single if...else if statement.
When using if , else if , else statements there are few points to keep in mind.
 An if can have zero or one else's and it must come after any else if's.
 An if can have zero to many else if's and they must come before the else.
 Once an else if succeeds, none of the remaining else if's or else's will be tested.
Syntax: The syntax of an if...else is:
if(Boolean_expression 1){
//Executes when the Boolean expression 1 is true
}else if(Boolean_expression 2){
//Executes when the Boolean expression 2 is true
}else if(Boolean_expression 3){
//Executes when the Boolean expression 3 is true
}else {
//Executes when the none of the above condition is true.
}
Example:

public class Test {

public static void main(String args[]){


int x = 30;

if( x == 10 ){
System.out.print("Value of X is 10");
}else if( x == 20 ){
System.out.print("Value of X is 20");
}else if( x == 30 ){
System.out.print("Value of X is 30");

Page 12 of 20
Chapter 2: Basics in Java Programming

}else{
System.out.print("This is else statement");
}
}
}
This would produce the following result:

Value of X is 30

Nested if...else Statement:


It is always legal to nest if-else statements which means you can use one if or else if
statement inside another if or else if statement.
Syntax: The syntax for a nested if...else is as follows:

if(Boolean_expression 1){
//Executes when the Boolean expression 1 is true
if(Boolean_expression 2){
//Executes when the Boolean expression 2 is true
}
}
You can nest else if...else in the similar way as we have nested if statement.

Example:

public class Test {

public static void main(String args[]){


int x = 30;
int y = 10;

if( x == 30 ){
if( y == 10 ){
System.out.print("X = 30 and Y = 10");
}
}
}
}
This would produce the following result:

X = 30 and Y = 10

The switch Statement:


A switch statement allows a variable to be tested for equality against a list of values. Each
value is called a case, and the variable being switched on is checked for each case.
Syntax: The syntax of enhanced for loop is:

Page 13 of 20
Chapter 2: Basics in Java Programming

switch(expression){
case value :
//Statements
break; //optional
case value :
//Statements
break; //optional
//You can have any number of case statements.
default : //Optional
//Statements
}
The following rules apply to a switch statement:
 The variable used in a switch statement can only be a byte, short, int, or char.
 You can have any number of case statements within a switch. Each case is
followed by the value to be compared to and a colon.
 The value for a case must be the same data type as the variable in the switch and it
must be a constant or a literal.
 When the variable being switched on is equal to a case, the statements following
that case will execute until a break statement is reached.
 When a break statement is reached, the switch terminates, and the flow of control
jumps to the next line following the switch statement.
 Not every case needs to contain a break. If no break appears, the flow of control
will fall through to subsequent cases until a break is reached.
 A switch statement can have an optional default case, which must appear at the
end of the switch. The default case can be used for performing a task when none
of the cases is true. No break is needed in the default case.

Example:
public class Test {
public static void main(String args[]){
//char grade = args[0].charAt(0);
char grade = 'C';

switch(grade)
{
case 'A' :
System.out.println("Excellent!");
break;
case 'B' :
case 'C' :
System.out.println("Well done");
break;
case 'D' :
System.out.println("You passed");
case 'F' :
System.out.println("Better try again");
break;
default :

Page 14 of 20
Chapter 2: Basics in Java Programming

System.out.println("Invalid grade");
}
System.out.println("Your grade is " + grade);
}
}
Compile and run above program using various command line arguments. This would
produce the following result:

$ java Test
Well done
Your grade is a C
$

Java Loops/Iteration and jump statements:


for, while and do...while & break, continue, return
There may be a situation when we need to execute a block of code several number of
times, and is often referred to as a loop. Java has very flexible three looping mechanisms.
You can use one of the following three loops:
- while Loop
- do...while Loop
- for Loop
As of Java 5, the enhanced for loop was introduced. This is mainly used for Arrays.

The while Loop:


A while loop is a control structure that allows you to repeat a task a certain number of
times.
Syntax: The syntax of a while loop is:

while(Boolean_expression)
{
//Statements
}
When executing, if the boolean_expression result is true, then the actions inside the loop
will be executed. This will continue as long as the expression result is true.
Here, key point of the while loop is that the loop might not ever run. When the expression
is tested and the result is false, the loop body will be skipped and the first statement after
the while loop will be executed.

Example:

Page 15 of 20
Chapter 2: Basics in Java Programming

public class Test {

public static void main(String args[]) {


int x = 10;

while( x < 20 ) {
System.out.print("value of x : " + x );
x++;
System.out.print("\n");
}
}
}
This would produce the following result:

value of x : 10 value of x : 15
value of x : 11 value of x : 16
value of x : 12 value of x : 17
value of x : 13 value of x : 18
value of x : 14 value of x : 19

The do...while Loop:


A do...while loop is similar to a while loop, except that a do...while loop is guaranteed to
execute at least one time.
Syntax: The syntax of a do...while loop is:

do
{
//Statements
}while(Boolean_expression);

Notice that the Boolean expression appears at the end of the loop, so the statements in the
loop execute once before the Boolean is tested.
If the Boolean expression is true, the flow of control jumps back up to do, and the
statements in the loop execute again. This process repeats until the Boolean expression is
false.
Example:

public class Test {

public static void main(String args[]){


int x = 10;

Page 16 of 20
Chapter 2: Basics in Java Programming

do{
System.out.print("value of x : " + x );
x++;
System.out.print("\n");
}while( x < 20 );
}
}
This would produce the following result:

value of x : 10 value of x : 15
value of x : 11 value of x : 16
value of x : 12 value of x : 17
value of x : 13 value of x : 18
value of x : 14 value of x : 19

The for Loop:


A for loop is a repetition control structure that allows you to efficiently write a loop that
needs to execute a specific number of times. A for loop is useful when you know how
many times a task is to be repeated.
Syntax: The syntax of a for loop is:

for(initialization; Boolean_expression; update)


{
//Statements
}
Here is the flow of control in a for loop:

 The initialization step is executed first, and only once. This step allows you to declare
and initialize any loop control variables. You are not required to put a statement here,
as long as a semicolon appears.

 Next, the Boolean expression is evaluated. If it is true, the body of the loop is
executed. If it is false, the body of the loop does not execute and flow of control
jumps to the next statement past the for loop.

 After the body of the for loop executes, the flow of control jumps back up to the
update statement. This statement allows you to update any loop control variables.
This statement can be left blank, as long as a semicolon appears after the Boolean
expression.

Page 17 of 20
Chapter 2: Basics in Java Programming

 The Boolean expression is now evaluated again. If it is true, the loop executes and the
process repeats itself (body of loop, then update step, then Boolean expression). After
the Boolean expression is false, the for loop terminates.
Example:

public class Test {

public static void main(String args[]) {

for(int x = 10; x < 20; x = x+1) {


System.out.print("value of x : " + x );
System.out.print("\n");
}
}
}
This would produce the following result:
value of x : 10 value of x : 15
value of x : 11 value of x : 16
value of x : 12 value of x : 17
value of x : 13 value of x : 18
value of x : 14 value of x : 19
Enhanced for loop in Java:
As of Java 5, the enhanced for loop was introduced. This is mainly used for Arrays.
Syntax: The syntax of enhanced for loop is:

for(declaration : expression)
{
//Statements
}
Declaration: The newly declared block variable, which is of a type compatible with the
elements of the array you are accessing. The variable will be available within the for
block and its value would be the same as the current array element.
Expression: This evaluates to the array you need to loop through. The expression can be
an array variable or method call that returns an array.
Example:

public class Test {

public static void main(String args[]){


int [] numbers = {10, 20, 30, 40, 50};

Page 18 of 20
Chapter 2: Basics in Java Programming

for(int x : numbers ){
System.out.print( x );
System.out.print(",");
}
System.out.print("\n");
String [] names ={"James", "Larry", "Tom", "Lacy"};
for( String name : names ) {
System.out.print( name );
System.out.print(",");
}
}
}
This would produce the following result:

10,20,30,40,50,
James,Larry,Tom,Lacy,

The break Keyword:


The break keyword is used to stop the entire loop. The break keyword must be used
inside any loop or a switch statement.
The break keyword will stop the execution of the innermost loop and start executing the
next line of code after the block.
Syntax: The syntax of a break is a single statement inside any loop:

break;
Example:

public class Test {


public static void main(String args[]) {
int [] numbers = {10, 20, 30, 40, 50};
for(int x : numbers ) {
if( x == 30 ) {
break;
}
System.out.print( x );
System.out.print("\n");
}
}
}
This would produce the following result:

10
20

Page 19 of 20
Chapter 2: Basics in Java Programming

The continue Keyword:


The continue keyword can be used in any of the loop control structures. It causes the loop
to immediately jump to the next iteration of the loop.
In a for loop, the continue keyword causes flow of control to immediately jump to the
update statement.
In a while loop or do/while loop, flow of control immediately jumps to the Boolean
expression.
Syntax: The syntax of a continue is a single statement inside any loop:

continue;
Example:

public class Test {

public static void main(String args[]) {


int [] numbers = {10, 20, 30, 40, 50};

for(int x : numbers ) {
if( x == 30 ) {
continue;
}
System.out.print( x );
System.out.print("\n");
}
}
}
This would produce the following result:

10
20
40
50

Page 20 of 20

You might also like