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

JAVA

Created By
Manvendra Mishra
HISTORY OF JAVA
 James Gosling, Mike Sheridan, and Patrick
Naughton initiated the Java language project in June 1991.
 The language was initially the name Green and was finally
renamed Java, from Java coffee. Gosling designed Java with a
C/C++-style syntax that system and application programmers
would find familiar.
Sun Microsystems released the first public implementationas Java
1.0 in 1995. It promised "Write Once, Run Anywhere" (WORA),
providing no-cost run-times on popular platforms. Fairly secure
and featuring configurablesecurity, it allowed network- and file-
access restrictions. Major web browsers soon incorporated the
ability to run java applets within web pages, and Java quickly
became popular.
SIMPLE
 Java is very easy to learn and its syntax is simple,clean
and easy to understand.
OBJECT
O RIENTED
 Java is Object-oriented programming language. Everything in
Java is an object. Object-oriented means we organize our software
as a combination of different types of objectsthat incorporates
both data and behaviour. Object-oriented programming(OOPs) is
a methodology that simplifies software development and
maintenance by providing somerules. Basic concepts of OOPs
are:
 Object
 Class
 Inheritance
 Polymorphism
 Abstraction
 Encapsulation
PLATFORM
INDEPENDENT
 Java is platform independent because it is differentfrom
other languages like C, C++ etc. which are compiled
into platform specific machines while Java is a write
once, run anywhere language. A platform is the
hardware or software environment in which a program
runs.
SECUR
E
 Java is best known for its security. With Java, wecan
develop virus-free systems.

OS

App JVM
PORTABL
E
 Java is portable because it facilitates you to carrythe
java bytecode to any platform.
WHAT HAPPENS AT COMPILE TIME?

 At compile time, java file is compiled by Java


Compiler (It does not interact with OS) and
converts the java code into bytecode.

Source code Byte Code


Compiler (Abc.class)
(Abc.java)
WHAT HAPPENS AT
RUNTIME?
checks the
code
Class loader is the fragments for
subsystem of JVM illegal code
that is used to load that canviolate
class files. access right to
objects.

read bytecode
stream then
execute the
instructions.
DIFFERENCE BETWEEN JDK, JRE AND
JVM
 JVM (Java Virtual Machine) is an abstract machine.It is a
specification that provides runtime environment in which
java bytecode can be executed.
 JRE is an acronym for Java Runtime Environment. It is
used to provide runtime environment. It is the
implementation of JVM. It physically exists. It contains
set of libraries + other files that JVM usesat runtime.
 JDK is an acronym for Java Development Kit. It
physically exists. It contains JRE + development
tools.
UNICODE
SYSTEM
Unicode is a universal international standard character encoding that iscapable

of representing most of the world's written languages.
 Why java uses Unicode System?
 Before Unicode, there were many language standards:ASCII (American
Standard Code for Information Interchange) for the United States.
 ISO 8859-1 for Western European Language.
 KOI-8 for Russian.
 GB18030 and BIG-5 for chinese, and so on.
 Problem
 This caused two problems:A particular code value corresponds to
different letters in the various language standards.
 The encodings for languages with large character sets have variable
length.Some common characters are encoded as single bytes, other require
two or more byte.
 Solution
 To solve these problems, a new language standard was developed i.e. Unicode
System.In unicode, character holds 2 byte, so java also uses 2byte for
characters.
lowest value: \u0000 highest value: \uFFFF
WHAT IS JAVA TOKENS?
 Tokens are the various Java program elements which are
identified by the compiler. A token is the smallest
element of a program that is meaningful tothe compiler.
Tokens supported in Java include keywords, variables,
constants, special characters, operators etc.
TOKENS ARE THE SMALLEST UNIT OF
PROGRAMTHERE IS FIVE TYPES OF TOKENS
 Reserve Word or Keywords
 Identifier
 Literals
 Operators
 Separators
 White space
WHITESPAC
E
 Whitespace in Java is used to separate the tokens in a Java
source file. Whitespace is required in some places,such as
between access modifiers, type names and Identifiers, and is
used to improve readability elsewhere.

Java whitespace consists of the


 space character ' ' (0x20),
 the tab character (hex 0x09),
 the form feed character (hex 0x0c),
 the line separators characters newline (hex 0x0a) or
carriage return (hex 0x0d) characters.
KEYWORD
S
 keyword is a word with a predefined meaning in Java
programming language syntax. Reserved forJava,
keywords may not be used as identifiers fornaming
variables, classes, methods or other entities.
 There are 51 (in ICSE textbook ) reserved keywordsin
the Java programming language.
 Eg:- import, public, private, protected, class, void, int,
float, double etc.
IDENTIFIERS IN JAVA
 Identifiers are the names of variables, methods,
classes, packages and interfaces. Unlike literals they
are not the things themselves, just ways ofreferring to
them. Eg:- String, args,
main and println are identifiers.
NAME
R ULE
Should be single word. That is spaces are not allowed. Example:
mangoprice is valid but (mango price) is not valid.
 Should start with a letter (alphabet) or underscore or $ symbol.
Example: price, _price and $price are valid Identifiers.
 Other special characters or operators not allowed in name.
 Should not be a keyword of Java as keyword carries special meaningto the
compiler.
Example: class or void etc.
 Should not start with a digit but digit can be in the middle or at the end.
Example: 5mangoescost is not valid and mango5cost and mangocost5 are
valid.
 Identifiers are case-sensitive. That is both mango and Mango aretreated
differently.
 Can contain all uppercase letters or lowercase letters or a mixture. 
 We can use any length of characters as name.
MNEMONI
C
 Variable names should be short yet meaningful. The
choice of a variable name should be mnemonic- that is,
designed to indicate to the casual observer the intent of
its use.
CAMEL
NOTATION
 Camel notation is the practice of writing compound
words or phrases in which the words are joined without
spaces and are capitalized within the compound like
BreakFast, myName etc. Camel notation is so named
because each word in the Identifier is put together
without spaces, but with the first letter of each word
captilised, looking like humps of a camel.
COMPILE
R
 A compiler is a software program that transforms high-
level source code that is written by a developer in a
high-level programming language into a low level
object code (binary code) in machine language, which
can be understood by theprocessor. The process of
converting high-level programming into machine
language is known as compilation.
 It also check syntax error. If any error occur during
compilation it create list of those errors and provide us
this list at the end of compilation.
BYTECOD
E
 Bytecodes are the machine language of the Java virtual
machine. When a JVM loads a class file, it gets one
stream of bytecodes for each method in the class. The
bytecodes streams are stored in the method area of the
JVM. The bytecodes for a method are executed when
that method is invoked during the course of running the
program. They can be executed by intepretation, just-in-
time compiling,or any other technique that was chosen
by the designer of a particular JVM.
JAVA
C
 The javac tool reads class and interface definitions,
written in the Java programming language, and compiles
them into bytecode class files.
JAVA
COMMAND
 The java command starts a Java application. It does
this by starting a Java runtime environment,loading a
specified class, and calling that
class's main method.
JAVA VIRTUAL
MACHINE(JVM)
 Java Virtual Machine (JVM) is a virtual machine that
resides in the real machine (your computer) and the
machine language for JVM is byte code. This makes it
easier for compiler as it has to generate byte code for
JVM rather than different machine code for each type
of machine. JVM executes the byte code generated by
compiler andproduce output. JVM is the one that
makes java platform independent.
DATATYPE
S
 Java language has a rich implementation of datatypes.
Data types specify size and the type of values that can
be stored in an identifier.
 In java, data types are classified into two catagories :
 Primitive Data type
 Non-Primitive Data type
Primitive Data type
 A primitive data type can be of eight types :
 Primitive Data types
char, boolean, byte,short, int, long, float, double, Once a
primitive data type has been declared its type can never
change, although in most cases its value can change.
These eight primitive type can be put into four groups
 Integer
 byte, short, int, long
 Floating point Number
 float, double.
 Characters
 Char
 Boolean
 boolean
NON PRIMITIVE(REFERENCE
DATATYPE)
 A reference data type is used to refer to an object. A
reference variable is declare to be of specific andthat
type can never be change.
INTEGE
R
 This group includes byte, short, int, long
 byte : It is 1 byte(8-bits) integer data type. Value range
from -128 to 127. Default value zero. example:byte b=10;
 short : It is 2 bytes(16-bits) integer data type. Valuerange
from -32768 to 32767. Default value zero. example: short
s=11;
 int : It is 4 bytes(32-bits) integer data type. Value range
from -2147483648 to 2147483647. Default value zero.
example: int i=10;
 long : It is 8 bytes(64-bits) integer data type. Value range
from -9,223,372,036,854,775,808 to 9,223,372,
036,854,775,807. Default value zero. example: long
l=100012;
FLOATIN
G
 This group includes float, double
 float : It is 4 bytes(32-bits) float data type. Defaultvalue
0.0f. example: float ff=10.3f;
 double : It is 8 bytes(64-bits) float data type. Defaultvalue
0.0d. example: double db=11.123;
CHARACTE
R
 This group represent char, which represent symbolsin a
character set, like letters and numbers.
 char : It is 2 bytes(16-bits) unsigned unicode
character. Range 0 to 65,535. example: char c='a';
BOOLEA
N
 This group represent boolean, which is a special type for
representing true/false values. They are defined constant
of the language. example: Boolean b=true;
TYPE
CASTING
 Assigning a value of one type to a variable of
another type is known as Type Casting.
 In Java, type casting is classified into two types,
 Widening Casting(Implicit)
 Narrowing Casting(Explicitly done)
WIDENING OR AUTOMATIC TYPE
CONVERSION
 Automatic Type casting take place when,
 the two types are compatible
 the target type is larger than the source type
 Eg:=
 int a=10; double s=a;
NARROWING OR EXPLICIT TYPE
CONVERSION
 When you are assigning a larger type value to a
variable of smaller type, then you need to perform
explicit type casting.
 Eg:-
 double d=1.4; int j=(int)d;
VARIABL
E
 When we want to store any information, we store itin an
address of the computer. Instead of remembering the
complex address where we have stored our information,
we name that address.The naming of an address is known
as variable. Variableis the name of memory location.
 Java Programming language defines mainly threekind
of variables.
 Instance variables
 Static Variables
 Local Variables
INSTANCE
VARIABLE
 Instance variables are variables that are declare inside
a class but outside any method,constructor or block.
Instance variable are also variable of object commonly
known as field or property. Theyare referred as object
variable. Each object has itsown copy of each variable
and thus, it doesn't effect the instance variable if one
object changesthe value of the variable.
STATIC
VARIABLE
 Static are class variables declared with static keyword.
Static variables are initialized only once. Static
variables are also used in declaring constantalong with
final keyword.
 Single copy of these variables shared by all
instances.
LOCAL
VARIABLE
 Local variables are declared in method, constructoror
block. Local variables are initialized when method,
constructor or block start and will be destroyed once its
end. Local variable reside in stack. Access modifiers are
not used for local variable.
OPERATORS
 Operators are special symbols that perform specific
operations on one, two, or threeoperands , and thenreturn
a result.
TYPES OF OPERATORS
Operator Precedence
Postfix A++, A--
Unary ++A,--A,~,!,-A,+A
Multiplicative *, /, %
Additive +,-
Shift >>, >>>, <<
Relational >, <, >=, <=
Equality ==, !=
Bitwise AND &
Bitwise Exclusive OR ^
Bitwise OR |
Logical AND &&
Logical OR ||
Ternary ?:
Assignment =, +=, -=, /=, %=, *=, &=, |=, ^=
ARITHMETIC
 They are used to perform simple arithmetic
operations on primitive data types.
 * : Multiplication
 / : Division
 % : Modulo
 + : Addition
 – : Subtraction
UNARY
O PERATORS
 Unary operators needs only one operand. They are used to
increment, decrement or negate a value.
 – :Unary minus, used for negating the values.
 + :Unary plus, used for giving positive values. Only used when
deliberately converting a negative value to positive.
 ++ :Increment operator, used for incrementing the value by 1. There
are two varieties of increment operator.
 Post-Increment : Value is first used for computing the result andthen
incremented.
 Pre-Increment : Value is incremented first and then result is
computed.
 - - : Decrement operator, used for decrementing the value by 1.There
are two varieties of decrement operator.
 Post-decrement : Value is first used for computing the result andthen
decremented.
 Pre-Decrement : Value is decremented first and then result is
computed.
 ! : Logical not operator, used for inverting a boolean value.
ASSIGNMENT
O‘=’
PERATOR
 Assignment operator is used to assign a value to any variable. It has aright to
left associativity, i.e value given on right hand side of operator is assigned to the
variable on the left and therefore right hand side value must be declared before
using it or should be a constant.
General format of assignment operator is,Var =
value
 In many cases assignment operator can be combined with other operators
to build a shorter version of statement called Compound Statement. For
example, instead of a = a+5 , we can write a += 5.
 +=, for adding left operand with right operand and then assigning it to variable
on the left.
 -=, for subtracting left operand with right operand and then assigning it to variable
on the left.
 *=, for multiplying left operand with right operand and then assigning it to
variable on the left.
 /=, for dividing left operand with right operand and then assigning it to
variable on the left.
 ^=, for raising power of left operand to right operand and assigning it to
variable on the left.
 %=, for assigning modulo of left operand with right operand and then
assigning it to variable on the left.
RELATIONAL
O PERATORS
 These operators are used to check for relations like equality, greater
than, less than. They return boolean result after the comparison and
are extensively used in looping statements aswell as conditional if
else statements. General format is, variable relation_operator value
Some of the relational operators are-
 == , Equal to : returns true of left hand side is equal to right handside.
 != , Not Equal to : returns true of left hand side is not equal toright
hand side.
 < , less than : returns true of left hand side is less than right handside. 
 <= , less than or equal to : returns true of left hand side is less than or
equal to right hand side.
 > , Greater than : returns true of left hand side is greater than righthand
side.
 >= , Greater than or equal to: returns true of left hand side is
greater than or equal to right hand side.
LOGICAL
OPERATORS
 These operators are used to perform “logical AND”and
“logical OR” operation, i.e. the function similarto AND
gate and OR gate in digital electronics. Onething to keep
in mind is the second condition is notevaluated if the
first one is false, i.e. it has short- circuiting effect. Used
extensively to test for several conditions for making a
decision. Conditional operators are-
 && , Logical AND : returns true when both
conditions are true.
 || , Logical OR : returns true if at least one conditionis
true.
TERNARY
OPERATOR
 Ternary operator is a shorthand version of if-else
statement. It has three operands and hence the name
ternary. General format is-condition ? if true :if false
 The above statement means that if the condition
evaluates to true, then execute the statements afterthe ‘?’
else execute the statements after the ‘:’.
BITWISE
O PERATORS
 These operators are used to perform manipulation of
individual bits of a number. They can be used with any of
the integer types. They are used when performing update
and query operations of Binary indexed tree.& , Bitwise
AND operator: returns bit by bit AND of input values.
 | , Bitwise OR operator: returns bit by bit OR of input
values.
 ^ , Bitwise XOR operator: returns bit by bit XOR of
input values.
 ~ , Bitwise Complement Operator: This is a unary
operator which returns the one’s compliment
representation of the input value, i.e. with all bits
inversed.
SEPARATORS IN
JAVA
Separators help define the structure of a program. The table lists the
seven Java separators (ten if you count opening andclosing
separators as two).
 Separator Purpose
( ) Encloses arguments in method definitions and calling; adjusts
precedence in arithmetic expressions; surrounds casttypes and
delimits test expressions in flow control statements
{ } defines blocks of code and automatically initializes arrays[ ]
declares array types and dereferences array values
; terminates statements
, separates successive identifiers in variable declarations;chains
statements in the test, expression of a for loop
. Selects a field or method from an object; separates packagenames
from sub-package and class names
: Used after labels
THE BREAK AND CONTINUE STATEMENT

 Using break statement : When a break statement is


encountered inside a loop, the loop is terminated and
program control resumes at the next statementfollowing
the loop. Here is a simple example:
 /** * This program demonstrates * break to exit a loop.
*/ public class BreakDemo { public static void
main(String[] args) { for (int i = 1; i <= 10; i++) { if (i
== 5) { break; // terminate loop if i is 5 } System.out.
print(i + " "); } System.out.println("Loop is over."); } }
Output :
 1 2 3 4 Loop is over.
CONTINUE STATEMENT
 Using continue statement : When a continue statement is
encountered inside the body of a loop,remaining
statements are skipped and loop proceeds with the next
iteration. Here is a simple example.
 /** * This program demonstrates continue * to skip
remaining statements of iteration. */ public class
ContinueDemo { public static void main(String[] args) {
for (int i = 1; i <= 10; i++) { if (i % 2 == 0) { continue; //
skip next statement if i is even } System.out.println(i + "
"); } } }
Output :
 1 3 5 7 9
IF...ELSE STATEMENT

 if (testExpression)
{ // statements }
The if statement evaluates the test expression inside theparenthesis.
 If the test expression is evaluated to true , statementsinside
the body of if is executed.
 If the test expression is evaluated to false , statements inside
the body of if is skipped from execution.
 If(testExpression)
{Statements}
 Else
{Statements}
 If test expression is true, codes inside the body
of if statement is executed and, codes inside the bodyof else
statement is skipped.
 If test expression is false, codes inside the body
of else statement is executed and, codes inside the bodyof if
statement is skipped.
NESTED
IF
 (If with in called nested if). A nested if is an if statement
that is the target of another if statement.Nested if
statements means an if statement insideanother if
statement.
 If(test)
{
 If(test)
{

}
else{ }
}
MULTIPLE IF
STATEMENT
 If else if is called multiple if statement.
 If(test)
{
 Else{
If(test)
{
}
}
}
SWITCH
STATEMENT
Switch case statements are a substitute for long if statements that compare a variable to several integral

values
 The switch statement is a multiway branch statement. It provides an easy way to dispatch execution
to different parts of code based on the value of the expression.
 Switch is a control statement that allows a value to change control of execution.
 Syntax:
 switch (n) { case 1: // code to be executed if n = 1; break; case 2: // code to be executed if n = 2; break;
default: // code to be executed if n doesn't match any cases }Important Points about SwitchCase Statements:
 The expression provided in the switch should result in a constant value otherwise it would not bevalid.
Valid expressions for switch:
 // Constant expressions allowed switch(1+2+23) switch(1*2+3%4)Invalid switch expressions for switch:
 // Variable expression not allowed switch(ab+cd) switch(a+b+c)
 Duplicate case values are not allowed.
 The default statement is optional.Even if the switch case statement do not have a default statement,
it would run without any problem.
 The break statement is used inside the switch to terminate a statement sequence. When a breakstatement is
reached, the switch terminates, and the flow of control jumps to the next line following the switch
statement.
 The break statement is optional. If omitted, execution will continue on into the next case. The flow of control
will fall through to subsequent cases until a break is reached.
 Nesting of switch statements are allowed, which means you can have switch statements inside another
switch. However nested switch statements should be avoided as it makes program morecomplex and less
readable.
LOOPS
 Loops in programming comes into use when we need to repeatedlyexecute
a block of statements.
 In computer programming, a loop is a sequence of instructions that is repeated
until a certain condition is reached.
An operation is done, such as getting an item of data and changing it, and then
some condition is checked such as whether a counter has reached a prescribed
number.
 Counter not Reached: If the counter has not reached the desired number, the next
instruction in the sequence returns to the first instruction in the sequence and
repeat it.
 Counter reached: If the condition has been reached, the next instruction “falls
through” to the next sequential instruction or branches outside theloop.
 There are mainly two types of loops:
 Entry Controlled loops: In this type of loops the test condition is testedbefore
entering the loop body. For Loopand While Loop are entry controlled loops.
 Exit Controlled Loops: In this type of loops the test condition is tested or
evaluated at the end of loop body. Therefore, the loop body will execute atleast
once, irrespective of whether the test condition is true or false. do
– while loop is exit controlled loop.
FOR
L OOP
A for loop is a repetition control structure which allows us to write a loop
that is executed a specific number of times. The loop enables usto perform n
number of steps together in one line.
Syntax:
 for (initialization expr; test expr; update expr) { // body of the loop //
statements we want to execute } In for loop, a loop variable is used to control
the loop. First initialize this loop variable to some value, then check whether
this variable is less than or greater than counter value.If statement is true,
then loop body is executed and loop variable gets updated . Steps are
repeated till exit condition comes.
 Initialization Expression: In this expression we have to initialize theloop
counter to some value. for example: int i=1;
 Test Expression: In this expression we have to test the condition. If the
condition evaluates to true then we will execute the body of loop and go to
update expression otherwise we will exit from the for loop.For example: i
<= 10;
 Update Expression: After executing loop body this expression
increments/decrements the loop variable by some value. for example:i++;
WHILE
L OOP
 While studying for loop we have seen that the number of
iterations is known beforehand, i.e. the number of times the
loop body is needed to be executed is known to us. while
loops are used in situations where we do not know the exact
number of iterations of loop beforehand. The loop execution is
terminated on the basis of test condition.
 Syntax:
We have already stated that a loop is mainly consisted ofthree
statements – initialization expression, test expression, update
expression. The syntax of the three loops – For, while and do
while mainly differs on the placement of these three
statements.
 initialization expression; while (test_expression) { //
statements update_expression; }
DO WHILE
L OOP
 In do while loops also the loop execution is terminated on
the basis of test condition. The main difference between do
while loop and while loop is indo while loop the condition
is tested at the end of loop body, i.e do while loop is exit
controlled whereasthe other two loops are entry controlled
loops.
Note: In do while loop the loop body will execute atleast
once irrespective of test condition.
 Syntax:
 initialization expression;do
{
// statements update_expression;
} while (test_expression);

You might also like