Java Programming
Java Programming
18CS653
MODULE-1
AN OVERVIEW OF JAVA
TOPICS
1.1 Introduction to Java
1.2 Bytecode
1.3 The Java Buzzwords
Simple
Secure
Portable
Object-Oriented
Robust
Multithreaded
Architecture-Neutral
Interpreted and High Performance
Distributed
Dynamic
1.4 Object-Oriented Programming
1.4.1 Two Paradigms
1.4.2 Abstraction
TOPICS
1.5 The Three OOP Principles
1.6 A First Simple Program
Entering the Program
Compiling the Program
A Closer Look at the First Sample Program
1.7 Two Control Statements
1.7.1 The if Statement
1.7.2 The for Loop
1.8 Using Blocks of Code
1.9 Lexical Issues
1.9.1 Whitespace
1.9.2 Identifiers
1.9.3 Literals
1.9.4 Comments
1.9.5 Separators
1.10 The Java Keywords
TOPICS
1.11 Java Is a Strongly Typed Language
1.12 The Primitive Data Types
1.12.1 Integers
1.12.2 byte
1.12.3 short
1.12.4 int
1.12.5 long
1.13 Floating-Point Types
1.13.1 float
1.13.2 Double
1.14 Characters
1.15 Booleans
1.16 A Closer Look at Literals
1.16.1 Integer Literals .
1.16.2 Floating-Point Literals
1.16.3 Boolean Literals
1.16.4 Character Literals
1.16.5 String Literals
TOPICS
1.17 Variables
1.17.1 Declaring a Variable
1.17.2 Dynamic Initialization
1.17.3 The Scope and Lifetime of Variables
1.18 Type Conversion and Casting
1.18.1 Java’s Automatic Conversions
1.18.2 Casting Incompatible Types
1.19 Automatic Type Promotion in Expressions
1.19.1 The Type Promotion Rules
1.20 Arrays
1.20.1 One-Dimensional Arrays
1.20.2 Multidimensional Arrays
1.20.3Alternative Array Declaration Syntax
1.1 INTRODUCTION TO JAVA
( WORA).
Java is the name of a beautiful island in Indonesia. It is also said that the
first coffee was named right here after java coffee.
JAVA PLATFORM EDITIONS
Vs
Vs
1) Simple
2) Secure
3) Portable
4) Object-oriented
5) Robust
6) Multithreaded
7) Architecture-neutral
8) Interpreted
9) High performance
10) Distributed
11) Dynamic
1) Simple : Java is a very simple programming language, it is easy to learn,
read and write in Java. The syntax of Java is clean and easy to understand.
2) Secure : Java is more secure than C/C++ as does not allow developers to
create pointers, thus it becomes impossible to access a variable from outside if
it’s not been initialized.
3) Portable: Java code that is written on one machine can run on another
machine. The platform independent byte code can be carried to any platform
for execution that makes java code portable.
4) Object-oriented: Object oriented programming is a way of organizing
programs as collection of objects, each of which represents an instance of a
class
5) Robust: Robust means reliable. Java programming language is developed
in a way that puts a lot of emphasis on early checking for possible errors,
that’s why java compiler is able to detect errors that are not easy to detect in
other programming languages.
The main features of java that makes it robust are:
Garbage collection , Exception Handling , Memory allocation.
6) Multithreaded: Multithreading is a Java feature that allows concurrent
execution of two or more parts of a program for maximum utilisation of CPU.
Code and Data are the two paradigms that governs how programs are
constructed.
Programs can be conceptually organized around its code and data
means:
-- some programs are written around “what is happening” and others are
written around “who is being affected.”
.
PRINCIPLES OF OOPS
1.5.2 Inheritance: Inheritance is a method in which one object
acquires/inherits another object’s properties, and inheritance also supports
hierarchical classification. The idea behind this is that we can create new
classes built on existing classes, i.e., when you inherit from an existing class,
we can reuse methods and fields of the parent class. Inheritance represents the
parent-child relationship.
Example: In real life a Child can inherits many things from parents like
colour, height, way of walking etc. but, the child also have its own properties
like education, playing etc.
PRINCIPLES OF OOPS
1.5.3 Encapsulation: Encapsulation is the process that binds together the data
and code into a single unit and keeps both from being safe from outside
interference and misuse.
Encapsulation is achieved by declaring the variables as private and providing
public setter and getter methods to modify and view the variable values.
PRINCIPLES OF OOPS
1.5.4 Polymorphism: Polymorphism refers to many forms, or it is a process
that performs a single action in different ways.
Example: a add() Method can be used to add two integers, add three float, add
two int and one float etc.
1.7 TWO CONTROL STATEMETS
if Statement and for loop : used to explain how to use block of code.
class ifExample{
public static void main(String args[]) {
int age=10; // variable declared and initialized
if(age>=18)
System.out.println( “You are eligible to vote”);
}
}
Example of if statement
class ifExample{
public static void main(String args[ ]) {
int x=10; // variable declared and initialized
int y=20; // variable declared and initialized
if( x> y)
System.out.println( “X is greater than Y”);
if( x < y)
System.out.println( “X is Smaller than Y”);
if( x= = y)
System.out.println( “X is equal to Y”);
}
}
1.7.2 for loop
for loop: The syntax of for loop is:
for(initialization; condition; iteration)
statement ;
The initialization portion of the loop sets a loop control variable to an initial
value.
The condition is a Boolean expression that tests the loop control variable.
if the outcome of that test is true, the for loop continues to iterate. If it is
false, the loop terminates.
The iteration expression determines how the loop control variable is
changed each time the loop iterates.
for loop
Example of for loop:
class ForTest
{
public static void main(String args[])
{
int x;
for(x = 0; x<10; x = x+1)
System.out.println("The value of x is : " + x);
}
}
Using Block of Code
In java we can group two or more statements in block of code, also called
code block.
The statements are written between the open curly bracket and close curly
bracket.
We use code block when we need to execute multiple statement when
particular condition is evaluated to true.
Example:
if( x> y)
{
x=y;
y=0;
}
1.8 Using Block of Code
In java we can group two or more statements in block of code, also called
code block.
The statements are written between the open curly bracket and close curly
bracket.
We use code block when we need to execute multiple statement when
particular condition is evaluated to true.
Example:
if( x> y)
{
x=y;
y=0;
}
1.9 LEXICAL ISSUES
1.19.1 Whitespace: Java is a free form language. This means that you do not
need to follow any special indentation rules. In java , white spaces is a
space , tab or new line.
1.19.2 Identifiers: Identifiers are used for class names , method names and
variable names.
Rules to define the identfiers
Names can contain letters, digits, underscores, and dollar signs
Names must begin with a letter
Names should start with a lowercase letter and it cannot contain
whitespace
Names can also begin with $ and _
Names are case sensitive ("myVar" and "myvar" are different variables)
Reserved words (like Java keywords, such as int or boolean) cannot be
used as names
1.19.3 Literals: A constant value that is assigned to a variable is called
Literals. Example: integer literal
int num =21; // 21 is an integer literal
1.19.4 Comments: Comments in Java are the statements that are not
executed by the compiler and interpreter.
comments can be used to provide information or explanation
about the variable, method, class or any statement.
There are 3 types of comment in java.
single line comment that begins with double slash //
multi line comment. That begins with /* and ends with */
documentation comment This type of comments is used generally when
you are writing code for a project/ software package. It helps you to
generate a documentation page for reference, which can be used for
getting information about methods present, its parameters, etc.It begins
with a /** and ends with a*/.
1.19.5 Separators: There are few symbols in java that are used as
separators.The most commonly used separator in java is the semicolon ' ;
'. some other separators are Parentheses '( )' , Braces ' {} ' , Bracket ' []
' , Comma ' , ' , Period ' . ' .
1.10 KEYWORDS
Keywords are predefined which have a unique meaning and functionality
in Java programming language. These keywords are also known as
reserved keywords which mean they cannot be used as a variable name,
class, method or any other identifier. There are 57 reserved keywords in
Java.
1.11 Java Is a Strongly Typed Language
1.12 Primitive Data Types
Java defines eight primitive types of data: byte, short, int, long, char, float,
double, and boolean.
The size of the primitive data types does not change with changing the
operating system These can be put in four groups:
Integers: This group includes byte, short, int, and long, which are for
whole-valued signed numbers.
Floating-point numbers: This group includes float and double, which
represent numbers with fractional precision.
Characters: This group includes char, which represents symbols in a
character set, like letters and numbers.
Boolean: This group includes boolean, which is a special type for representing
true/false values.
1.12.1 Integer Data Types
byte: The byte data type is commonly used when we want to store very
small numbers of very limited size. For example, the index record of the
notebook.
The byte data type can have data value in the range of -128 to 127.
The byte data values require 1 bytes memory space in the computer’s
memory.
The default value of the byte is 0.
Synatx: byte variable_name = value;
Example: byte b =10;
Note: We should initialize the value to byte variable within -128 to 127. if
not compiler will give error.
short: The short data type is commonly used when we want to save
memory in large arrays. For example, we can use a short data type for storing
the admission number of the students of the school.
The short data type can have data value in the range of -32,768 to 32,767.
The short data values require 2 bytes memory space in the computer’s
memory.
The default value of the byte is 0.
Synatx: short variable_name = value;
Example: short s =128;
1.16.1 Integral Literals : These types of literals are the sequence of digits. There
are four types of intergral literals.
Decimal
Octal.
Hexadecimal.
Binary
Decimal Integer: These are the set of numbers that consist of digits from 0 to 9.
It may have a positive (+) or negative (-) Note that between numbers commas and
non-digit characters are not permitted. For example, 5678, +657, -89, etc.
Binary Integer: Base 2, whose digits consists of the numbers 0 and 1 (you can
create binary literals in Java SE 7 and later). Prefix 0b represents the Binary
Output:
1.16.2 Floating Point Literals:
The values that contain decimal are floating literals. In Java, float and double
primitive types fall into floating-point literals.
Floating-point literals for float type end with F or f. For example, 6f, 8.354F, etc.
It is a 32-bit float literal.
Floating-point literals for double type end with D or d. It is optional to write D or
d. For example, 6d, 8.354D, etc. It is a 64-bit double literal.
It can also be represented in the form of the exponent.
Floating: float length = 155.4f;
Decimal: double interest = 99658.445;
Decimal in Exponent form: double val= 1.234e2;
Example of Floating Point Literals:
Output:
1.16.3 Boolean Literals:
Boolean literals are the value that is either true or false. It may also have values 0
and 1. For example, true, 0, etc.
boolean isEven = true;
1.16.4 Null Literals:
Null literal is often used in programs as a marker to indicate that reference type
object is unavailable. The value null may be assigned to any variable, except
variables of primitive types.
String stuName = null;
Student age = null;
1.16.5 String Literals:
String literals are the value that is enclosed in double quotes. For
example, ”Welcome”.
String name = ”Ramesh”;
Example of boolean, null and String Literals:
Output:
1.17 VARIABLES
Variables:
Declaring a Variable
Dynamic Initialization
The Scope and Lifetime of Variables
the variable
Global Variable: Variables that are declared outside the class are called Global
variables.
Instance Variable: Variables that are defined inside the class but outside the
Local Variable: Variables that are declared insde the methods are called local
variables.
1.17.3 SCOPE AND LIFE TIME OF VARIABLES
In java we can define the variables in any block.
Block defines the scope.
Each block defines the new scope.
A scope determines that objects are visible to other parts of your program. It
also determines the lifetime of those objects.
Variables declared inside a scope are not visible (that is, accessible) to
code that is defined outside that scope.
Therefore when we declare a variable within a scope, we are localizing that
variable and protecting it from unauthorized access and/or modification.
Example on Scope of the variable
Example on Scope of the variable
1.18 TYPE CONVERSION AND CASTING
Type Conversion: The process of converting data of one type to another type
int x = b;
The data type of 12 which was byte has been converted to int. but 12 will remain
same.
In java it is possible for the programmer to convert data of one type to another.
If both the datat ypes are compatible then java perform automatic type
conversion.
1.18.1 Automatic Type Conversion :
Conversion .
Automatic Type conversion is the process of converting the data type with
lower values to data types with higher values without incurring any data loss.
Implicit type conversion is automatically done by the compiler. When both data
types are compatible. That is destination type is larger than source type
Type Casting :
Conversion .
Type Casting is the process of converting the data type with higher values to
data types with lower values without incurring any data loss.
Example:
byte b= 20, c=12, m;
m = b*c; // here the result of expression b*c value is promoted to int.
Example: int x=10;
float y= 12.9f, d;
d = (x* 2)/y; // here the result of expression (x*2)/y is promoted to float
TYPE PROMOTION RULES
Example:
byte a = 40;
byte b = 50;
byte c = 100;
int d = a * b / c; // result of a*b/c is converted to int
Example:
byte b = 10;
b = b * 2; // Error here the result of expression b*2 is promoted to
int by default , which cant be stored into b variable since
it is byte.
SUMMARIZE : TYPE CONVERSION AND CASTING
Type Conversion:
1.19 ARRAYS
Example:
month_days = new int[12]; // This example allocates
a 12-element array of integers and links them to month_days.
Once you have allocated an array, you can access a specific element in the array
by specifying its index within square brackets. All array indexes start at zero.
For example: the statement assigns the value 28 to the second element of
month_days.
month_days[1] = 28;