1 - Introduction To Java Programming
1 - Introduction To Java Programming
Learning Objective :
● Basics of Java
● JDK
● Java magic : Byte Code
● Difference between JDK, JRE and JVM
● Primitive data types
● Literals and Variables
● Type conversion and Casting
● Different types of Operators
● Shorthand assignment
● Control statements : Loops and if-else ladder
● Break and Continue keywords
Basics of JAVA
In 1991, a group of people in Sun Microsystem led by Patric Naughton & James
Gosling, wanted to design a small computer language for consumer devices such as TV switch
boxes. Since these devices require small power & memory, the language had to be small and
tight. Also it is important that language not be tied to any single architecture. This project team
was named as “Green”.
Nikalus Writh, the inventor of Pascal, designed a portable language that generated
intermediate language for a hypothetical machine (often called virtual machine). Thus Green
1
Project used this Virtual machine, which solved their main problem. Finally it took 18 months to
develop the first working version. Gosling initially called this language “OAK” but was renamed
“JAVA” in 1995.
In 1992, the Green Project delivered its first product called “*7”. It was an intelligent remote
control. Unfortunately no one was interested in producing this at Sun. The Green Project with a
new name “First Person, Inc” spent all of 1993 and half of 1994 looking for people to buy its
technology, but no one was found. Thus First Person was dissolved in 1994.
About the time of Java being worked out at Sun, the World Wide Web part of the internet
was growing bigger & bigger. Java was then made use to advance the World Wide Web browser.
Sun released the first version of Java in early 1996.
Java is certainly a good programming language. There is no doubt that it is one of the better
languages available to serious programmers. But, Java was never just a language; rather it was a
whole Platform, with a huge library, containing lots of reusable code, and an execution
environment that provides services such as security, portability and automatic garbage collection.
Any object oriented programming language like C++, Java etc are designed to achieve,
In order to make the code simple and reusable, there are four pillars of object oriented
programming language,
1. Encapsulation
2. Abstraction
3. Polymorphism
4. Inheritance
2
Encapsulation: The property of binding the data and its behavior together. It ensures that
the data is safe and is not freely available for outside interference and misuse.
Abstraction: The Property of hiding internal implementation from external view. This
makes building applications easier.
Inheritance: The Property of acquiring qualities of one class into another class. This is
important because it supports the concept of hierarchical classification. By the use of
inheritance, a class has to define only those qualities that make it unique. The general
qualities can be inherited from the parent class.
JDK refers to a collection of tools that are used for developing and running Java
programs. JDK consists of a collection of tools such as,
A source program written in Java is compiled using “javac” and executed using “java”. The
“jdb” is used to locate errors if any in the source program.
class Example{
// Program begins with the call to main( )
public static void main(String [ ] args){
System.out.println("This is Simple Java Program");
}
}
3
Output:
This is Simple Java Program
The code of a java program must be saved in a file with .java as an extension. By
convention, the name of the file must be the name of the class that contains the main( ) method.
i.e., Example.java in the above example. To compile the java program, execute the compiler,
javac, specifying the name of the source file on the command line, i.e., javac Example.java
The javac compiler creates a file called Example.class, that contains the bytecode version
of the program. To actually run the program, use the java application launcher, called java. To
this java, pass class name as a command-line argument, i.e., java Example. When the program is
run, the respective output is obtained.
The concept of “Bytecode” is the main reason for Java to achieve portability. When the
source program is given as an input to the java compiler, the java compiler does not generate the
machine level language executable code. Rather it generates Bytecode.
Bytecodes are a highly optimized set of instructions designed to be executed by the Java
runtime system called JVM (Java Virtual Machine).
Translating a Java program into bytecode makes it much easier to run a program in a
wide variety of environments because only JVM needs to be implemented for each platform.
Hence portability of Java programs can be achieved.
4
JVM is software that accepts the intermediate bytecode as the input and generates the required
machine level language executable code as its output. SunMicrosystems developed different
versions of JVM for each environment (OS) and hence achieved portability.
JDK- Java Development Kit JVM – Java Virtual Machine JRE – Java Runtime Environment
JDK is a tool that JVM is a software to JRE is also a tool which can be
facilitates building and convert byte code to used to run java programs but
running java programs. machine code. can't be used to build the
program.
JDK can both compile JVM is specific to the JRE can only run the program.
and run the program. specific version of the
Operating System.
Java is a strongly typed language. The various data types supported by Java are as shown below,
Datatypes in Java
Integer char
byte boolean
short
int
long
Real Numbers
float
double
5
Java defines eight primitive types (simple types) of data: byte, short, int, long, char, float,
double and boolean.
Integer Types: are signed, positive and negative values. Java does not support unsigned values.
Integer types hold the whole numbers, they cannot hold real numbers. There are 4 data types
related to Integer groups such as- byte, short, int, long. The size (width) of Integer group is as
shown below,
Floating-Point Numbers (Real Types): can hold real numbers, there are 2 datatypes related to
floating-point numbers, such as, float and double. ‘Float’ stores real numbers using single
precision, whereas, ‘double’ stores real numbers using double precision. The size of these data
types are shown below,
Character Types: in Java are used to store characters. It occupies 2bytes in the memory unit and
uses Unicode (not ASCII) to represent characters.
Boolean: is used to deal with the logical values. It can have one of the two values namely ‘true’
or ‘false’. This is the type returned by all relational operators.
Variables
The variable is the basic unit of storage in a Java program. A variable is defined by the
combination of an identifier, a type, and an optional initializer. In addition, all variables have a
scope, which defines their visibility, and a lifetime.
In Java, all variables must be declared before they can be used. The basic form of a
variable declaration is shown below,
6
type identifier [ = value][, identifier [= value] ...] ;
The type is one of Java’s primitive types, or the name of a class or interface.
e.g., int a, b, c;
float x = 20.2;
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:
When these two conditions are met, a widening conversion takes place. For example, the
int type is always large enough to hold all valid byte values, so no explicit cast statement is
required.
To create a conversion between two incompatible types, you must use a cast. A cast is
simply an explicit type conversion. It has this general form:
(target-type) value
Here, target-type specifies the desired type to convert the specified value to. Consider the
following example,
7
Output:
Conversion of int to byte.
i and b 257 1
Operators
The operators are helpful to perform specific operations. There are rich set of operators
supported by like such as,
1. Arithmetic Operators
2. Bitwise Operators
3. Relational Operators
4. Logical Operators
5. Assignment Operator
6. Ternary Operator
Arithmetic Operators
Operator Result
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulus
8
Consider the following example,
Bitwise Operators
Bitwise operators, as the name suggests, operate upon the individual bits of the operand.
The operands to the bitwise operators must be of numeric or of character type. The bitwise
operators supported by Java is as given below,
Operator Result
~ Bitwise Unary NOT
& Bitwise AND
| Bitwise OR
^ Exclusive OR
>> Shift Right
>>> Shift Right Zero Fill
<< Shift Left
9
Relational Operators
Relational operators determine the relationship that one operand has with the other. The
outcome of the relational operator is a boolean value. The relational operators are more
frequently used in expressions that control the various loop statements and if statements. The
relational operators in Java are as listed below,
Operator Result
== Equal to
!= Not Equal to
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to
Logical Operators
Logical operators operate upon boolean operands. The list of logical operators supported by Java
is as given below,
Operator Result
! Logical NOT
&& Logical AND
|| Logical OR
^ Exclusive OR
The following table shows the effect of each logical operation,
10
True False False True True False
False True False True True True
True True True True False False
Consider the following example,
Assignment Operator
var =expression;
e.g., int a, b, c;
a = b = c = 9;
Using a chain of assignments is the simplest way to set a group of variables to a common
value.
The ? Operator
Java supports a special operator called ternary operator (?), which can be used instead of
certain types of if-then-else. The general form of ? operator is,
11
Here, Expression1 can be any expression that evaluates to a boolean value. If
Expression1 is true, then Expression2 is evaluated, otherwise Expression3 is evaluated.
Shorthand Assignment
Most of the binary operators can be combined with assignment operators to make the
code simple. These kinds of operators are called shorthand assignment operators.
12
Java supports various classes to read characters from the keyboard, one such simple and
most widely used class for this is Scanner, which is present in the package java.util.
The Scanner class provides methods to read integer, float, string, character etc.
Method Description
nextInt() Reads integer
nextLine() Reads string until new line character
next() Reads string until space
nextFloat() Reads floating point value
nextChar() Reads character value
✔ Selection Statement
✔ Iteration Statement
✔ Jump Statement
if while break
if-else do-while labeled break
if-else-if ladder for continue
switch for-each(enhanced for) labeled continue
nested switch return
13
Selection Statements
Java supports two selection statements: if and switch. These statements allow control of
the flow of program execution based upon conditions. The if statement is Java’s conditional
branch statement. It is used to route program execution through two different paths. There are
different versions of if-statements, such as,
✔ Simple if-statement
✔ if-else
✔ if-else-if ladder
✔ Nested if-else statement
Simple if-statement
if(condition){
…..
…..
}
if-else statement
if(condition){
…..
…..
}
else{
…..
…..
}
if-else-if ladder
if(condition){
…..
…..
}
else if{
14
…..
…..
}
else if{
…..
…..
}
else{
…..
…..
}
if(condition){
if(condition){
…..
…..
}
else{
…..
…..
}
}
else{
if(condition){
…..
…..
}
else{
…..
…..
}
}
The condition in the above general syntax is any expression that returns a Boolean value
or it is a Boolean type by itself. The below program illustrates the working of if-statements,
15
Output:
The season in month 4 is: Summer
Switch: The switch statement is Java’s multiway branch statement. The general form of
switch statement is as shown below,
switch(expression){
case value1: // statement sequence
break;
case value2: // statement sequence
break;
case value3: // statement sequence
break;
16
The ‘expression’ in switch statement 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. The
value of the expression in the switch statement is compared with each of the values in the case
statements. If a match is found, the code sequence following that case is executed. If none of the
constants matches the value of the expression, then the default statement is executed. The break
statement is used inside the switch to terminate a statement sequence.
Output:
i is zero.
i is one.
i is two.
i is three.
i is greater than 3.
i is greater than 3.
Iteration Statements
→ while loop
→ do-while loop
→ for loop
→ enhanced for loop (for each loop)
17
while Loop:
The while loop is Java’s fundamental loop statement. It repeats a statement or block of
statements until the expression is true in a while loop. The general form of while-loop is
as shown below,
while(condition){
//body of loop
}
Here ‘condition can be any boolean expression. Consider the following example,
Output:
tick 10
tick 9
tick 8
tick 7
tick 6
tick 5
tick 4
tick 3
tick 2
tick 1
Since the while loop evaluates its conditional expression at the top of the loop, the body
of the loop will not execute even once if the condition is false to begin with.
do-while Loop:
The do-while loop always executes its body at least once, because its conditional
expression is at the bottom of the loop. Its general form is
do {
// body of loop
} while (condition);
18
Each iteration of the do-while loop first executes the body of the loop and then evaluates
the conditional expression. If this expression is true, the loop will repeat. Otherwise, the loop
terminates.
Output:
tick 10
tick 9
tick 8
tick 7
tick 6
tick 5
tick 4
tick 3
tick 2
tick 1
for Loop:
19
Consider the following example,
Output:
tick 10
tick 9
tick 8
tick 7
tick 6
tick 5
tick 4
tick 3
tick 2
tick 1
Beginning with JDK 5, a new form of for-loop was defined as ‘for-each loop’. The
general form of enhanced for is as shown below,
for(type itr-var:collection)
Statement-block
Here, type specifies the data type and itr-var specifies the name of an iteration variable
that will receive the elements from a collection, one at a time, from beginning to the end. The
collection being cycled through is specified by collection.
20
Output:
Value is: 1
Value is: 2
Value is: 3
Value is: 4
Value is: 5
Value is: 6
Value is: 7
Value is: 8
Value is: 9
Value is: 10
Summation: 55
Jump Statement
→ break
→ continue
→ return.
break Statement:
By using break, we can force immediate termination of a loop, bypassing the conditional
expression and any remaining code in the body of the loop. When a break statement is
encountered inside a loop, the loop is terminated and program control resumes at the next
statement following the loop. For example,
21
Output:
i: 0
i: 1
i: 2
i: 3
i: 4
i: 5
i: 6
i: 7
i: 8
i: 9
Loop complete.
Using break as a form of ‘goto’ i.e., labeled break. The general form of the labeled break
statement is,
break label;
Here, label is the name of a label that identifies a block of code. When this form of break
executes, control is transferred out of the named block of code. The labeled block of code must
enclose the break statement, but it does not need to be the immediately enclosing block. This
means that you can use a labeled break statement to exit from a set of nested blocks. But you
cannot use break to transfer control to a block of code that does not enclose the break statement.
Output:
Before the break.
This is after second block.
22
continue Statement:
continue statement skip the remainder of the code in its body for a particular iteration. In
while and do-while loops, a continue statement causes control to be transferred directly to the
conditional expression that controls the loop. In a for loop, control goes first to the iteration
portion of the for statement and then to the conditional expression. For all three loops, any
intermediate code is bypassed.
Output:
0 1
2 3
4 5
6 7
8 9
Similar to a break statement, even a continue statement can be specified with a label.
Consider the following example,
The continue statement in this example terminates the loop counting j and continues with
the next iteration of the loop counting i. Here is the output of this program:
23
0 1
0 2 4
0 3 6 9
0 4 8 12 16
0 5 10 15 20 25
0 6 12 18 24 30 36
0 7 14 21 28 35 42 49
0 8 16 24 32 40 48 56 64
0 9 18 27 36 45 54 63 72 81
return Statement:
The return statement is used to explicitly return from a method. That is, it causes program
control to transfer back to the caller of the method.
At any time in a method the return statement can be used to cause execution to branch
back to the caller of the method. Thus, the return statement immediately terminates the method
in which it is executed.
Output:
Before the return.
24