UNIT-1
I. Program Structure in Java:
1. Introduction
2. Writing Simple Java Programs
3. Elements or Tokens in Java Programs
4. Java Statements
5. Command Line Arguments
6. User Input to Programs
7. Escape Sequences
8. Comments
9. Programming Style.
II. Data Types Variables and Operators :
1. Introduction Data Types in Java
2. Declaration of Variables Data Types
3. Type Casting
4. Scope of Variable Identifier
5. Literal Constants, Symbolic Constants
6. Formatted Output with printf() Method
7. Static Variables and Methods
8. Attribute Final
9. Introduction to Operators
10. Precedence and Associativity of Operators
11. Assignment Operator ( = )
12. Basic Arithmetic Operators
13. Increment (++) and Decrement (- -) Operators
14. Ternary Operator Relational Operators
15. Boolean Logical Operators
16. Bitwise Logical Operators.
III. Control Statements:
1. Introduction
2. if Expression
3. Nested if Expressions
4. if else Expressions
5. Ternary Operator?:
6. Switch Statement
7. Iteration Statements
8. while Expression
9. do while Loop
[Link] Loop
11. Nested for Loop
12. For Each for Loop
[Link] Statement
14. Continue Statement.
1
I. Program Structure in Java:
1. Introduction
Java is an Object Orient and high-level programming language, originally developed by
Sun Microsystems and released in 1995. Java runs on a variety of platforms, such as
Windows, Mac OS, Linux etc.
In Java, there are three types of programs as follows:
Stand- aline application programs : These programs are made and run on users
computers
Applet programs : These programs are meant to run in a web page on the Internet.
Java Servlets : These programs run in computers that provide web services. They are
also oftern called server isde programs or servlets.
2. Writing Simple Java Programs
Java is an Object oriented language. Every java program imports packages which
are provides necessary classes and interfaces.
For example:
import [Link].*;
import [Link].*;
After import statement, every java program starts with the declaration of the class.
A program may have one or more classes.
A class declaration starts with the keyword class, followed by the identifier or name of the
class. Giving the name of a package at the top is optional.
Class declarion contains name of the class and body of the class. The body of the
class may consist of several statements and is enclsed between the braces {}.
A sample of class declarions is as follows.
Here:
public is access specifier. This class is accessible to any ouside code. Otherwise the
class is accessibe to only same package classes.
class is a keyword of java language which is used to declare the class.
The class body starts with the left brace { and ends with the right colsing brace }.
// are comments which are neglected by the compiler.
2
A class body may comprise statements for declaration of variables. constants,
expressions, and methods.
Simple program in Java [Link]
public class Start()
{
public static void main()
{
[Link]( );
}
}
Here:
class is a keyword
Start is a name the class. Here class is declared as public, so it is available to
all the classes.
main() is the method which initiate and terminate the program ( in java
functions are called as Methods)
println() is method of object out . out is the object of class System .
println() prints the string Hello World on the screen/monitor.
Compiling and Running Java program
Java compiler first converts the source code into an intermediate code, known as
bytecode or virtual machine code. To run the bytecode, we need the Java Virtual
Machie (JVM). JVM exists only inside the computer memory and runs on top of
the Operating System. The bytecode is not machine specific. The Java interpreter
converts the bytecode into Machine code. The following diagram illustrates the
process of compiling and running Java programs.
For compiling the program, the Java compiler javac is run, specifying the name of
the source file on the command line as depicted here:
javac [Link]
The Java compiler creates a file called [Link] containing the bytecode version
of the program. The java interpreter in JVM executes the instructions contained in
3
this intermediate Java bytecode version of the program. The Java interpreter is
C:\> java Start
Output:
Hello World
Here java command calls the Java interpreter which executes the [Link]
(bytecode of [Link]).
3. Elements or Tokens in Java Programs
Java program contains different types of elements like white spaces, comments and
tokens. A token is the smallest program element which is recognized by the
compiler and which treats them as defined for the compiler. A program is a set of
tokens which comprise the following elements:
Identifiers or names: Identifier is the name of variables, methods, classes etc.
Rules for framing Names or Identifiers.
It should be a single word which contains alphabets a to z or A to Z, digits 0 to 9,
underscore (_).
It should not contain white spaces and special symbols.
It should not be a keyword of Java.
It should not be Boolean literal, that is, true or false.
It should not be null literal.
It should not start with a digit but it can start with an underscore.
It can comprise one or more unicode characters which are characters as well as digits.
Conventions for Writing Names
Names of packages are completely in lower-case letters such as mypackage,
[Link].
Names of classes and interfaces start with an upper-case letter.
Names of methods start with a lower-case character.
Names of variables should start with a lower-case character.
Keywords: These are special words defined in Java and represent a set of
instructions.
The keywords represent groups of instructions for the compiler.
These are special tokens that have a predefined meaning and their use is
restricted.
keywords cannot be used as names of variables, methods, classes, or packages.
These are written in the lower case.
Keywords of Java Language are as follows:
4
Literals: These are values represented by a set of character, digits, etc.
A literal represents a value which may be of primitive type, String type, or null
type.
The value may be a number (either whole or decimal point number) or a
sequence of characters which is called String literal, Boolean type, etc.
A literal is a constant value.
Types of Literals:
i. Integer literals
Sequences of digits.
The whole numbers are described by different number systems such as decimal
numbers, hexadecimal numbers, octal numbers, and binary numbers.
Each number has a different set of digits.
Decimal Integer Literals
These are sequences of decimal digits which are 0, 1, 2, 3, 4, 5, 6, 7, 8, and 9.
Examples of such literals are 6, 453, 34789, etc.
Hex Integral Literals
These are sequences of hexadecimal digits which are 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
A, B, C, D, E, and F.
The values 10 to 15 are represented by A, B, C, D, E, and F or a, b, c, d, e, and
f.
The numbers are preceded by 0x or 0X. Examples are 0x56ab o0X6AF2, etc.
Octal Integer Literals
These are sequences of octal digits which are 0, 1, 2, 3, 4, 5, 6, and 7.
These numbers are preceded by 0. Examples of literals are 07122, 04, 043526.
Binary Literal
These are sequences of binary digits.
Binary numbers have only two digits 0 and 1 and a base 2.
Examples of such literals are 0b0111001, 0b101, 0b1000, etc.
5
ii. Floating point literal
These are floating decimal point numbers or fractional decimal numbers
with base 10. Examples are 3.14159, 567.78, etc.
iii. Boolean literal
These are Boolean values. There are only two values true or false.
iv. Character literal
These are the values in characters.
v. String literal
These are strings of characters
vi. Null literal
There is only one value of Null Literal, that is, null.
Separators: These include comma, semicolon, period(.), Parenthesis (), Square
brackets [], etc
6
Operators: Operators are mostly represented by symbols such as +, -, *, etc
Types of Operators:
Arithmetic Operators:
Operator Description
+ Addition or Unary plus
- Subtraction or Unary minus
* Multiplication
/ Division
% Modulus
Relational Operators:
Operator Description
> Greater than
>= Greater than or equal to
< Less than
<= Less than or equal to
== Equal to
!= Not equal to
Logical Operators:
Operator Description
&& Greater than
|| Greater than or equal to
! Less than
Assignment Operators:
Operator Description
+= Add and assign to
-= Subtract and assign to
*= Multiply and assign to
/= Divide and assign to
%= Modulus and assign to
Increment / Decrement Operators:
Operator Description
++ Increment by one
-- Decrement by one
7
Bitwise Operators:
Operator Description
& Bitwise AND
| Bitwise OR
^ Bitwise exclusive OR
~ Bitwise compliment
>> Shift Right
<< Shift Left
>>> Shift right with Zero fill
Conditional Operators:
Operator Description
?: Used to construct Conditional expression
4. Java Statements
A Statement is a instruction to the computer. A program is a set of statements or
instructions. The statements specify the sequence of actions to be performed when
some method or constructor is invoked. The statements are executed in the sequence
in the specified order. The important Java statements are as follows.
Statement Description
Empty statement These are used during program development.
Variable declaration It defines a variable that can be used to store the values.
statement
Labeled statement A block of statements is given a label. The labels should not
be keywords, previously used labels, or already declared
local variables.
Expression statement Most of the statements come under this category. There are
seven types of expression statements that include
assignment, method call and allocation, pre-increment, post
increment, pre-decrement, and post decrement statements.
Control statement This comprises selection, iteration, and jump statements.
Selection statement In these statements, one of the various control flows is
selected when a certain condition expression is true. There
are three types of selection statements including if, if-else,
and switch.
Iteration statement These involve the use of loops until some condition for the
termination of loop is satisfied. There are three types of
iteration statements that make use of while, do, and for
Jump statement In these statements, the control is transferred to the
beginning or end of the current block or to a labeled
statement. There are four types of Jump statements including
break, continue, return, and throw.
Synchronization These are used with multi-threading
statement
Guarding statement These are used to carry out the code safely that may cause
exceptions (such as division by zero, and so on). These
statements make use of try and catch block, and finally
8
5. Command Line Arguments
A Java application can accept any number of arguments from the command line.
These arguments can be passed at the time of running the program. This enables a
programmer to check the behavior of a program for different values of inputs.
When a Java application is invoked, the runtime system passes the command line
arguments to the application's main method through an array of strings.
It must be noted that the number of arguments
in an array. To ensure this, we can make use of the length property of the array. This is
illustrated in
Program 2.2: Example showing command line argument
class vehicle
public static void main(String args[])
{
int x = [Link];
for(int i=0; i<x; i++)
{
[Link](args[i]);
}
}
Output
(After compiling, type the following lines on the command prompt. It produces the output as)
C:\> Java vehicle Car Cycle Motorbike"
Car
Cycle
Motorbike
9
Program 2.3: Illustration of command line
class Sum
{
public static void main{String args)
int s=1;
for(int i e; icargs length; 1++){
s=s+[Link](args(1]);
[Link](" The addition of passed arguments 15" );
Output
After compiling, the following lines are typed on the command
prompt: It produces the output as
C:\> Java Sun 20 15 17
Declaration of Variables
A program may involve variables: variables are objects whose values may change in the
program.
A variable is declared by first writing its type, followed by its name or identifier as
illustrated here.
However, a variable should also be initialized, that is, a value should be assigned to it
before it is used in an expression. The line ends with a semicolon (:) as shown in the
above figure.
Examples:
double price = 28.5;
char ch = "C":
String name - "John";
10
Program 2.4 illustrates the declaration and output of some data types
class PrintOut
{
public static void main (String args[])
{
String name = "Sunita"; //"name" is variable, value is "Sunita"
String str = "Hello"; //String set has value- "Hello!"
int length = 50; // Variable name "length", value 50
int width = 8; // Variable name "width" value 8
[Link]("Name= " + name);
[Link]("Str = "+ str); //print statement
System. [Link]();
[Link]("Length "+ length);
System. [Link]("Width " + width);
[Link](str + name); // println statement
}
}
c:\>javac [Link]
c:\>java PrintOut
Name= SunitaStr = Hello
Length 50
Width 8
HelloSunita
6. User Input to Programs
The class Scanner of package [Link] to carry out input to the program.
Java Scanner class is a text scanner that breaks the input into tokens using a delimiter.
The delimiter is whitespace by default.
Importing the class is the first step.
import [Link];
The object of the class Scanner is declared as follows.
Scanner scaninput = new Scanner (System. in);
scaninput nextInt() which reads the value typed
by the user. This value is assigned to n. The value of m is similarly obtained.
The other useful methods of Scanner class are nextDouble() and nextLine().
11
Program 2.6: Illustration of a user's input from keyboard into
program
import [Link];
public class Arithmetic
{
public static void main(String[] args)
{
Scanner scaninput = new Scanner (System. in);
int n;
int m;
[Link]. print( "Enter the value of n : ");
n=[Link]();
[Link]. print( "Enter the value of m : ");
m=[Link]();
[Link]("Sum of two numbers is ="+(n+m));
[Link]("Product of two numbers is ="+ n*m);
[Link]("Modulus of (n % m) is =" + n%m);
[Link]("Division of two numbers is =" + n /m );
}
}
Output
C:\>javac [Link]
C:\>java Arithmetic
Enter the value of n : 10
Enter the value of m : 3
Sum of two numbers is =13
Product of two numbers is =30
Modulus of (n % m) is =1
Division of two numbers is =3
C:\>
12
7. Escape Sequences
Escape Sequences character is preceded by a backslash (\)has a special meaning to
the compiler. Escape sequences are as follows.
Program 2.9: Program on Escape Sequences
class Escape
{
public static void main(String[] args)
{
int n=256, a=0, b=70;
[Link]("Value of a =" + a + "\n b= "+b +"\n");
[Link]("\u0041 \t" + " \u0042 \t"+"\132");
[Link]("\"Value of b\" = "+b);
[Link]("\'Value of n\' = " +n);
}
}
Output:
C:\>javac [Link]
C:\>java Escape
Value of a =0
b= 70
A B Z
"Value of b" = 70
'Value of n' = 256
13
8. Comments
Comments are Line of Text which is not a part of the compiled program.
Comments are used for documentation to explain source code.
They are added to the source code of the program.
Java supports three types of comments as:
1. Single-line comment: These comments are started with two front slash
characters (//)
Example:
// This is Single line comment
2. Multi-line comment : These comments are enclosed with /* and */
Example:
/* It is Multi line
Comments */
3. Documentation comment: These comments are enclosed with /** and */. It
is different from multi line comments in that it can extracted by javadoc utility
to generate an HTML document for the program.
Example:
/** It is documentation
Comments */
9. Programming Style.
An analysis of the programming exercises will throw some light on the look and feel of a
program. The team members should easily understand each other's code.
For a beginner, it is better to develop a habit of writing a program in a proper style so that
there is no conflict between the current habits and the company's imposition of style rule
at a later stage.
There are no set patterns of good style and bad style: however, if the programmer takes
care of a few requirements on the programs as discussed, the resulting style will be better
1. The program should present a clean and orderly look. In order to develop a clean
program, the programmer can adapt the following measures:
(a) The white spaces are neglected by the compiler.
(b) Indenting is another method often used to improve the looks and readability
(c) Use of Lambda expression and method reference of Java 8 enhances the look
(d) Include a space before and after operators
14
2. The program should be easy to understand. The programmer should take care of the
following aspects:
(a) If it is team work, certain conventions about naming should be preset so that a team
member can easily identify an item.
(b) The makers of Java have a set of rules which are followed in the Java library. The same
rules or an even better convention may be set.
(c) Judicial use of comments can increase understandability. Use of too many comments
makes confusion in the program.
(d) It is better to use already defined and tested library methods rather than user-defined
methods
(e) Expressions like z = x++ + - - c*++k; should be avoided.
3. Debugging should be easy. The programmer may adopt the following measures to
ensure easy debugging.
(a) The vertical alignment of a similar item enhances the ability to find errors.
(b) The code line should not be too long.
(c) The variables should be declared close to the places of their use
(d) If it is a big program, it should be divided into small segments. In Java, it is easy because
the program may comprise separate classes.
(e) The methods should not be too big.
(f) Each source code file should have one class.
(g) The braces should be vertically aligned, if possible.
4. The program should be easy to use. The following points
(a) The input into program should be easy,
(b) The output should be self-explanatory should be taken care of
(c) The names used should imply the output type such as price, weight, length, and so on.
(d) Confusing and long names must be avoided.
5. The program should be easy to maintain
(a) The program should be easily modifiable to ensure simplicity in fixing errors.
(b) The comments can help in modification of the program, fixing errors.
6. The program should be fail-safe. The failure of a program should not be catastrophic.
15