Java Unit-1 Final
Java Unit-1 Final
JAVA INTRODUCTION:
Java is a general-purpose object-oriented programming language.
James Gosling, Mike Sheridan, Patrick Naughton initiated the java language
project in June 1991 at sun Microsystems. The small team of sun engineers
called Green Team.
Initially this language was called as “Green talk”, after sometimes it was
renamed as “Oak”.
“Oak” is nothing but, it is the national tree of many countries like USA,
France. Oak is the symbol of strength.
In 1995, Oak was renamed as “Java”.
Originally developed by James Gosling at Sun Microsystems (Which is now a
subsidiary of Oracle Corporation) and released in 1995.
Originally java was designed for small, embedded systems in electronic
appliances like set-top boxes, interactive Television etc.,
In 1995, Time magazine called Java one of the Ten Best Products of 1995.
JDK 1.0 released in(January 23, 1996).
Versions of Java:
There are many java versions that have been released.
1. JDK Alpha and Beta (1995)
2. JDK 1.0 (23rd Jan, 1996)
3. JDK 1.1 (19th Feb, 1997)
4. J2SE 1.2 (8th Dec, 1998)
5. J2SE 1.3 (8th May, 2000)
6. J2SE 1.4 (6th Feb, 2002)
7. J2SE 5.0 (30th Sep 2004)
8. Java SE 6 (11th Dec, 2006)
9. Java SE 7 (28th July, 2011)
10.Java SE 8 (18th March, 2014)
11.Java SE 9 (21st Sep, 2017)
FEATURES OF JAVA:
The following are the important features of Java.
1. Simple
2. Object Oriented
3. Compiled and Interpreted
4. Portable
5. Platform Independent
6. Secured
7. Robust
8. Dynamic
9. High Performance
10.Multi-threaded
11.Distributed
Page 1 of 21
JAVA PROGRAMMING UNIT-I
1. Simple:
Java is a simple language, because its syntax was similar to C and C++.
Java removes some of the confusing concepts of C++ like operator
overloading, multiple inheritance, pointers, go to statement etc.
2. Object Oriented:
Java is an object-oriented language.
Everything in Java is an object.
OOP concepts are implemented in Java programs.
3. Compiled and Interpreted:
Java is both compiled and interpreted language.
In case of C/C++, the source code is directly converted to binary code
by the compiler that can be executed by the OS to get output. This
binary code generated on one OS does not execute on other OS. That
is, the binary code generated on UNIX machine must be executed on
UNIX only and similarly code generated on windows must be
executed on Windows only. For this reason, C/C++ are known as
“platform-dependent languages”.
Java is a platform-independent language. This independency achieved
by two phases:
i. Compilation
ii. Interpretation
i. Compilation:
Converting Java source code to bytecode is in known as
compilation. The bytecode is not in a readable format by the
Microprocessor.
ii. Interpretation:
Java interpreter converts the bytecode into processor readable
binary code. This phase is called as Interpretation.
Page 2 of 21
JAVA PROGRAMMING UNIT-I
4. Portable:
When we are compiling our Java program, bytecode was created. This
bytecode can be transferred through Internet, and it can be executed
by any machine.
This concept is known as “Write Once, Run Anywhere (WORA)”.
5. Platform Independent:
At the time of compilation, Java compiler produces bytecode. This
bytecode can run on any JVM (Java Virtual Machine).
JVM is a software virtual machine that interprets compiled java code
(bytecode) for currently running computer’s processor or hardware
platform. JVM is responsible for converting that bytecode to machine
code before running it.
We can run same Java code on Windows JVM, Linux JVM, Mac JVM or
any other JVM practically and get same result every time.
6. Secured:
Java is designed to be secure in a networked environment. The Java
run-time environment uses a bytecode verification process to ensure
that code loaded over the network does not violate Java security
constraints.
Java ensures that no viruses are communicated with an applet.
Java does not support pointers. So, the programmer cannot access the
memory location without proper rights.
7. Robust:
Robust means strong. Java is a strong programming language because
of it has the capability to handle compile time and runtime checking
of data types, Run-time Error, automatic garbage collection, the lack
of pointer concept, Exception Handling.
8. Dynamic:
Java is a dynamic language which means it can link new Java class
libraries, Java objects, and native methods dynamically. It also
supports functions from its native languages such as C and C++.
Page 3 of 21
JAVA PROGRAMMING UNIT-I
9. High Performance:
Java is a high-performance language, because it was designed to
support “Just-in-time” compilers, which dynamically compile
bytecode to machine code.
10. Multi-threaded:
Multi-threaded means handling multiple tasks simultaneously. Java
supports multi-threaded programs. We need not wait for one
application to close before start another application.
For example, we can download the applet while listening the music
and typing some text at the same time.
11. Distributed:
Using Java, we can create applications on networks. Java applications
can open and access remote objects on Internet as easily as they can
do in a local system.
This enables multiple programmers at different locations to
collaborate and work together on a single project.
Page 4 of 21
JAVA PROGRAMMING UNIT-I
Page 5 of 21
JAVA PROGRAMMING UNIT-I
Student.result(regno);
Information
Object Method
Communication operator
Programming with objects follows the following step:
1. Declaring the class that defines data and methods.
2. Declaring the objects for the class.
3. Establishing the relationship between the objects.
BENEFITS OF OOP:
Through inheritance, we can eliminate redundant code and extend the use
of existing classes.
We can build programs from the standard working modules that
communicate with one another. This leads to saving of development time
and higher productivity.
The principle of data hiding helps the programmer to build secure
programs.
It is possible to have multiple objects to co-exist without any interference.
It is possible to map objects in the problem domain.
It is easy to partition the work in a project.
Object-oriented systems can be easily upgraded from small to large systems.
Message passing techniques for communication between objects make the
interface descriptions with external systems much simpler.
Software complexity can be easily managed.
APPLICATIONS OF OOP:
The most popular application of Object-Oriented Programming is in the area
of user interface design such as windows. OOP can simplify a complex problem.
For example, Real-business systems contain many more objects with complicated
attributes and methods.
The area for application of OOP includes:
Real-time systems
Simulation and modeling
Object-oriented databases
Hypertext, hypermedia and expertext
AI and expert systems
Neural networks and parallel programming
Decision support and office automation systems
CAD Systems
Page 6 of 21
JAVA PROGRAMMING UNIT-I
Page 7 of 21
JAVA PROGRAMMING UNIT-I
JAVA TOKENS:
Smallest individual units in a program are known as tokens.
A JAVA program is a collection of tokens, comments and white spaces.
It includes five types of tokens. They are,
1. Keywords
2. Identifiers
3. Literals
4. Operators
5. Separators
Smallest units of java language are the characters used to write java
tokens.
The characters are defined by the Unicode character set.
Unicode is a 16-bit character coding system.
We have used only ASCII character set (a subset of UNICODE character set)
in the program.
Page 8 of 21
JAVA PROGRAMMING UNIT-I
Keywords:
Keywords have specific meaning in java. All keywords are to be written in
lower-case letters.
JAVA is case sensitive.
We can’t use keywords as names for variables, classes, methods and so on.
For example,
case inct class false float goto double default
for break new while Final void import do
Identifiers:
Identifier must be meaningful, short enough to be quickly and easily typed.
Identifiers are used for naming classes, methods, variables, objects, labels,
packages and interfaces in a program.
For example: average, sum
All classes and interfaces start with a uppercase letter.
For example: Student, Vehicle, employee.
Variables that represent constant values use all uppercase letters.
For example: TOTAL, AMOUNT
Literals:
Literals in java are a sequence of characters that represent constant values
to be stored in variables.
It specifies five major types of literals. They are,
1. Integer literals
2. Floating- point literals
3. Character literals
4. String literals
5. Boolean literals.
Operators:
An operator is a symbol that takes one or more arguments and operates on
them to produce a result.
For example: c = a + b;
Separators:
Separators are symbol used to indicate where groups of code are divided
and arranged.
For example: ( ), { }, [ ], ; , , , .
Page 9 of 21
JAVA PROGRAMMING UNIT-I
CONSTANTS:
Constants refer to fixed values that do not change during the execution of a
program.
JAVA supports several types of constants.
JAVA CONSTANTS
Page 10 of 21
JAVA PROGRAMMING UNIT-I
String Constants:
A string constant is a sequence of characters enclosed between double
quotes. For example: “Hello Java” “1997” “?....!” “5+3”
Backslash Character Constant:
JAVA supports some special backslash character constants that are used in
output methods. For example,
‘\n’ stands for new line.
‘\b’ stands for back space.
‘\r’ stands for carriage return.
‘\t’ stands for horizontal tab.
‘\’’ stands for single quote.
‘\”’ stands for double quote.
‘\\’ stands for backslash.
DATA TYPES:
Every variable in JAVA has a data type. Data types specify the size and type
of values that can be stored.
The variety of data types available.
Primitive Non-Primitive
(Built-in) (Derived)
Numeric Non-numeric
Page 11 of 21
JAVA PROGRAMMING UNIT-I
Integer Types:
Integer types can hold a sequence of digits. JAVA supports four types of
integers. They are,
1. Byte
2. Short
3. Int
4. Long
Page 12 of 21
JAVA PROGRAMMING UNIT-I
1. Float:
The float type values are single precision numbers.
It was 32-bits of storage.
Single precision are faster.
Float are useful for a fractional component.
For example: float x; float a = 1.23f
2. Double:
Double precision as noted by the double keyword.
It was 64-bits to store a value.
All mathematical functions such as sin, cos and sqrt return double type
values. For example: double x = 3.14;
Character Type:
JAVA provides a character data type called char.
JAVA char is a 16-bit type.
But it can hold only a single character. For example: char name = ‘d’;
Boolean Type:
Boolean type is used when we want to test a particular condition during the
examination of the program.
There are only two values that Boolean type can take true or false.
It uses only one bit of storage. For example: Boolean b = false;
Sample program for Data Types in JAVA:
import java.io.*;
class samplepgm
{
public static void main(String args[ ])
{
char a = ‘G’;
int i = 89;
byte b = 4;
short s = 56;
double d = 4.355454542;
float f = 4.7333434f;
boolean x = true;
String y = “Hello JAVA”;
System.out.println(“Integer : “+i);
System.out.println(“Byte : “+b);
System.out.println(“Short : “+s);
System.out.println(“Double : “+d);
System.out.println(“Float : “+f);
System.out.println(“Boolean : “+x);
System.out.println(“Character : “+a);
System.out.println(“String : “+y);
}
}
Page 13 of 21
JAVA PROGRAMMING UNIT-I
VARIABLES:
A variable is an identifier that denotes a storage location used to store a data
value.
A variable may take different values at different times during the execution
of the program.
A variable must be meaningful, short enough to be quickly and easily type.
A variable should not be a keyword and it must not begin with a digit.
For example: avg, total_height, sum.
Declaration of Variables:
A variable must be declared before it is used in the program.
A variable can be used to store a value of any data type.
Syntax: type var1, var2, ………, varn;
For example: int count; float x, y; char c1,c2,c3; byte b;
A declaration must end with a semicolon(;).
Giving Values to Variables:
A variable must be given a value after it has been declared but before it is
used in an expression.
This can be achieved in two ways:
1. Assignment Statement
2. Read Statement
1. Assignment Method:
The process of giving initial values to variables is known as
initialization.
Syntax: type varname = value;
For example: int i = 10; double total = 75.36; char yes = ‘d’;
2. Read Statement:
We may also give values to variables interactively through the
keyboard using readLine( ) method.
The readLine( ) method reads the input from the keyboard as a string
which is then converted to the corresponding data type.
For example:
DataInputStream in = new DataInputStream(System.in);
n = Integer.parseInt(in.readLine( ));
Scope of Variables:
Variables declared and used inside methods are called local variables.
It can also be declared inside the program blocks that are defined between
{ and }.
A block defines a scope.
At a each time you start a new block you are creating a new scope.
Scope contains two general categories.
1. Global
2. Local
When we declare a variable within a scope, we are localizing that variable
and protecting it from unauthorized access and its modification.
Page 14 of 21
JAVA PROGRAMMING UNIT-I
Scopes can be nested. This means that object declared in the outer scope
will be variable to code within the inner scope. However the reverse is not
true.
The object declared within the inner scope will not be variable outside it.
For example:
class scope
{
public static void main(String args[ ])
{
int x;
x = 10;
int y = 5;
System.out.println(x); => we can access x within the block
}
System.out.println(y); => give error
}
Getting Values of Variables:
JAVA supports two output methods that can be used to send the results to
the screen.
1. print( ) method //print and wait.
2. println( ) method //print a line and move to next line.
1. print( ) method:
The print( ) method prints output on one line until a newline
character is encountered.
For example: System.out.print(“Hello ”);
System.out.print(“JAVA!”);
Will display the words Hello JAVA!
2. println( ) method:
The println( ) method takes the information provided and displays it
on a line followed by a line feed(Carriage-return).
For example: System.out.println(“Hello ”);
System.out.println(“JAVA!”);
Will display the words:
Hello
JAVA!
The statement, System.out.println( ); will print a blank line.
TYPE CASTING:
The process of converting one data type to another is called type casting.
Syntax: typevar1 = (type) var2;
For example: int i = 50;
byte n = (byte) i;
It is also possible to assign a value of one type to a variable of a different
type without a cast.
Page 15 of 21
JAVA PROGRAMMING UNIT-I
OPERATORS:
JAVA supports a rich set of operators.
An operator is a symbol that tells the computer perform certain
mathematical or logical manipulations.
Operators are used in programs to manipulate data and variables.
JAVA operators can be classified into several categories. They are,
1. Arithmetic operators
2. Relational operators
3. Logical operators
4. Assignment operators
5. Increment and decrement operators
6. Conditional operators
7. Bitwise operators
8. Special operators
1. Arithmetic Operators:
Arithmetic operators are used in mathematical expressions.
JAVA provides all the basic arithmetic operators. They are,
+ addition
- subtraction
* multiplication
/ division
% modulo division (modules)
For example,
import java.io.*;
class arithmetic
{
public static void main(String args[ ])
{
int a = 5, b = 3;
float f, g;
int c, d, e;
c = a + b;
d = a – b;
e = a * b;
f = a / b;
g = a % b;
System.out.println(“Add = “+c);
System.out.println(“Sub = “+d);
System.out.println(“Mul = “+e);
System.out.println(“Div = “+f);
Page 16 of 21
JAVA PROGRAMMING UNIT-I
System.out.println(“Mod = “+g);
}
}
It will displays,
Add = 8
Sub = 2
Mul = 15
Div = 1.6667
Mod = 2
2. Relational Operators:
The comparisons can be done with the help of relational operators.
The value of relational expression is either true or false.
Operators Meaning
< is less than
<= is less than or equal to
> is greater than
>= is greater than or equal to
== is equal to
!= is not equal to
Relational expressions are used in decision statements such as if and
while to decide the course of action of a running program.
For example:
import java.io.*;
class relational
{
public static void main(String args[ ])
{
int a = 25, b = 36;
if (a == b)
System.out.println(“BOTH ARE EQUAL”);
else
{
if (a > b)
System.out.println(“A IS BIGGER”);
else
System.out.println(“B IS BIGGER”);
}
}
}
It will displays, B IS BIGGER.
3. Logical Operators:
A combination of two or more relational expressions is called as logical
expressions.
Logical expressions also yield a value of true or false.
In JAVA,
Page 17 of 21
JAVA PROGRAMMING UNIT-I
Operator Meaning
&& logical AND
|| logical OR
^ logical XOR (exclusive OR)
! logical Unary NOT
&= AND assignment
|= OR assignment
?: Ternary if-then-else
Truth Table:
Value of Expression
A B
A&&B A||B A^B !A
True TrueTrue True False False
True False
False True True False
False True
False True True True
False False
False False False True
For example,
A company insures its drivers,
I. If the driver is married
II. If the driver is unmarried, male and above 30 years
III. If the driver is unmarried, female and above 25 years
In all other cases the driver is not insured. Write a program to determine
whether the driver is to be insured or not.
import java.io.*;
class insure
{
public static void main(String args[ ])
{
char status = ‘S’, sex = ‘F’;
int age = 26;
if (status == ‘M’) ||
((status == ‘S’) && (sex == ‘F’) && (age > 25)) ||
((status == ‘S’) && (sex == ‘M’) && (age > 30))
System.out.println(“DRIVER IS INSURED”);
else
System.out.println(“DRIVER IS NOT INSURED”);
}
}
The second condition is true, so it will be display, DRIVER IS INSURED.
4. Assignment Operators:
Assignment operators are used to assign the value of an expression to a
variable.
Syntax: var operator= expression here, operator is shorthand
assignment operator
For example: x += y+1; a += 1;
This is same as the statement x=x+(y+1); a=a+1;
Page 18 of 21
JAVA PROGRAMMING UNIT-I
Page 19 of 21
JAVA PROGRAMMING UNIT-I
ie, y = 5, m = 6.
=> first assigned the value of m then only increased it.
import java.io.*;
class incrdecr
{
public static void main(String args[ ])
{
int m = 10, n = 20;
System.out.println(“m = “+m);
System.out.println(“n = “+n);
System.out.println(“++m = ”+ ++m);
System.out.println(“n++ = “+ n++);
System.out.println(“m = “+m);
System.out.println(“n = “+n);
}
}
It will displays,
m = 10
n = 20
++m = 11
n++ = 20
m = 11
n = 21
6. Conditional Operators:
The character pair ?: is a Ternary Operator. This operator is used to
construct conditional operator.
Syntax: exp1 ? exp2 : exp3
Here, exp1 is evaluated first.
If exp1 = true then exp2 is evaluated
If exp1 = false then exp3 is evaluated
For example,
import java.io.*;
class condop
{
public static void main(String args[ ])
{
int a = 10, b = 5, c;
c = (a > b) ? a : b;
System.out.println(“ a = ”+a);
System.out.println(“ b = ”+b);
System.out.println(“ c = ”+c);
}
}
It will display,
a = 10
Page 20 of 21
JAVA PROGRAMMING UNIT-I
b=5
c = 10
7. Bitwise Operators:
Bitwise operators for manipulation of data at values of bit level.
These operators are used for testing the bits, or shifting them to the right or
left.
Bitwise operators may not be applied to float or double.
Operators Meaning
& bitwise AND
! bitwise OR
^ bitwise exclusive OR
~ one’s complement
<< shift left
>> shift right
>>> shift right with zero fill
8. Special Operators:
Special Operators are instance of and operators.
i. instanceof Operator:
The instance allows us to determine whether the object belongs to a
particular class or not.
Example: person instanceof student
is true if the object person belongs to the class student;
Otherwise it is false.
ii. Dot ( ) Operator:
The dot operator is used to access the variables and methods of class
objects.
Examples: person1.age => Reference to the variable age.
person1.salary( ) => Reference to the method salary( ).
Page 21 of 21