0 ratings0% found this document useful (0 votes) 25 views30 pagesJava Research
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content,
claim it here.
Available Formats
Download as PDF or read online on Scribd
Features of Javal Java Buzzwords :
|
a
Pay
Java has become a popular and useful programming language because ofits excellent features,
‘which play a very important role in contributing to the popularity of this language. The Java
features are called “Java Buzz Words”.
‘Dr Kumaresh Shelovant, Associate Presse, CSE{AIML)
(00P With 308 Bcs206A
‘imate:
> Java is very easy to learn, and its syntax i simple, clean and easy to understand
> According to Sun Miero Systems, Java language is a simple programming language
because:
Java syntax is based on C++ (so easier for programmers to learn it fter C+).
Java has removed many complicated and rarely-used features, for example,
explicit pointers, operator overloading, et.
There is no need to remove unveferenced objects because there is an Automatic
Garbage Collection in Java,
Object Oriented:
> Java strongly supports the concepts of Object-Oriented Programming due to which it is
called a pure object-oriented language.
> Java supports major Object-Oriented programming features like Encapsulation,
‘Abstraction, and Inheritance
> Almost everything in Java is an object. All programs and data live within objects and
classes, “Objects” model Java rather than the “processes’ Java comes with an extensible
sat of classes organized in packages.
Platform Independent:
> The most significant feature of Java is that it provides platform independence which
leads toa facility of portability, which ultimately becomes its biggest strength.
> Being platform: independent means a program compiled on one machine can be executed
‘on any machine inthe world without any change.
> Java achieves platform independence by using the concept of the BYTE CODE,
> The Java compiler never converts the source code to machine code like that of the
cic compiler.
> Instead, it converts the source code nto an intermediate code called the byte code and
this byte code is futher translated to machine-dependent form by another layer of
software called JVM (Java Virtual Machine)
Intropret
> Usually, a computer language can be either compiled or interpreted. Java integrates the
ower of Compiled Languages with the flexibility of Interpreted Languages.
> Java compiler (avec) compiles the java source code into the bytecode
> Java Virtual Machine (JVM) then executes this bytecode which is executable on many
‘operating systems and is potable, The diagram below shows the above process‘Secured:
> Java is best known for is security. With Java, we can develop virus-free systems, Java is
secured because
+ No explicit pointer
+ Java Programs run inside a vitual machine sandbox-A separate environment that
allows users to execute their applications without affecting the underlying
system
thas a bytecode verifier that checks the code fragments for any illegal code that
violates the access right.
Portable:
> Java is portable because it facilitates the programmer to carry the Java bytecode to any
platform,
> In Java, the size of the primitive data types is machine-independent, which were
dependent in the case of C/C++. So, these provisions make Java programs portable
among different platforms such as Windows, Unix, Solaris, and Mac.
> Moreover, any changes and updates made in Operating Systems, Processors and System
resources will not enforce any changes in Java programs.
Architecture Neutral:
> This buzzword means that the program written on one platform or OS is independent of
‘other platforms oF environments and can run on any other Operating System without
recompiling them.
> mother words, tf based on the “Write-once-run-anywhere” (WORA) or “Write-onee
* (WORE) approach
> Byte-code is not dependent on any machine architecture and Java Virtual Machine
(GVM) can easily transtate bytecode into a machine-spcific code.
run-everywhet
‘Dr Kumarsh Sheeavan, Associate Professor, CSE(AIML) 4
(20° wh 30 acs2064
2 Robust simply means strong.
> Javais robust because:
uses strong memory management
There isa lack of pointers that avoids security problems,
There is automatic garbage collection in java which runs onthe Java Virtual
[Machine to gt rid of objects which are not being used by a Java application
anymore
There are exception handling andthe type checking mechanism in Java. All these
Points make Java robust.
‘Dynamic:
> Java is dynamic and extensible means with the help of OOPs, we can add classes and
‘add. new methods to clases, creating new classes through subclasses. This makes it
easier for us to expand out ov clases and even modify them.
> Java gives the facility of dynamically linking new class libraries, methods, and objects,
Itishighly dynamic as it can adapt to its evolving environment
> Java even supports functions written in other languages such as C and C+ to be written
in Java programs. These functions are ci
dynamically linked at euntime.
led “native methods”, These methods areHigh Performance:
> The performance of Java is impressive for an interpreted language because of its
intermediate bytecode.
> Java provides high performance with the use of “JIT — Just In Time con, 6/56
the compiler compiles the code on-demand basis, that is, it compiles only that method
which is being called. This saves time and makes it more efficient.
> Java architecture is also designed in such a way that it reduces overheads during
runtime, The inclusion of multithreading enhances the overall execution speed of Java
programs
> Bytecodes generated by the Java compiler are highly optimized, so Java Virtual Machine
can execute them much faster.
Dr-Kumaresh Sheelavant, Associate Professor, CSE(AIML) 5
(OOP With Java BCS206A,
Multi-Thre
> A thread is like a separate program, executing concurrently.
> We can write Java programs that deal with many tasks at once by defining
multiple threads.
> The main advantage of multi-threading is that it doesn’t occupy memory for
each thread. It shares a common memory area.
> Threads are important for multi-media, Web applications, etc.
Distributed:
> Java is distributed because it encourages users to create distributed applications.
> In Java, we can split a program into many parts and store these parts on different
computers,
> A Java programmer sitting on a machine can access another program running on the
other machine. This feature in Java gives the advantage of distributed programming,
which is very helpful when we develop large projects.
> Java helps us to achieve this by providing the concept of RMI (Remote Method
Invocation) and EB (Enterprise JavaBeans).
> Java comes with an extensive library of classes for interacting, using TCP/IP protocols
such as HTTP and FTP, which makes creating network connections much easier than in
cic++
> It also enables multiple programmers at many locations to work together on a single
project.Object Oriented:
‘© Object oriented programs are written based on -Who is being affected! around,
which manages the increasing complexity.
‘© Itorganises program around data and well defined interfaces of that data.
* Characterised as data controlling access to code. Ex: C++, JAVA, Small Talk etc
The Three OOP:
The three important features of OOP are:
+ Encapsulation
+ Inheritence
«Polymorphism
Encapsulation:
‘* Encapsulation is the mechanism that binds together code and data it manipulates,
and keeps both safe from outside interference and misuse.
‘© In Java the basis of encapsulation is the class. A class defines the state and behavior (
data & code) that will be shared by set of objects.
‘+ Each object contains the structure and behavior defined by the class. The data
defined by the class are called instance variables(member variables), the code that
‘operates on that data are called methods(member functions).
inheritence:
‘+ Inheritence is the process by which one object acquires the properties of another
‘object. This is important as it supports the concept of hierarchical classification.
‘By the use of inheritence, a class has to define only those qualities that make it
‘unique. The general qualities can ber derived from the parent class or base class.
‘© Ex: A child inheriting properties from parents.
Polymorphism
Polymorphism (meaning many forms) is a feature that allows one interface to be
used for a general class of actions. The specific action determined by the exact
nature of the situation. This concept is often expressed as — one interface, multiple
methods!
‘+ Ex: -til can be used for addition of 2 numbers and also concatenation of 2 strings.
System out printin(2+4); /! outputs 6 as answer
Dr.Kumaresh Sheelavant, Associate Professor, CSE(AIML) 7
‘OOP With Java BCS306A
‘System.out printin(-Hellol + ~Gautham!); // outputs Hello Gautham as answerPolymorphism, Encapsulation and Inheritence work Together
‘© The 3 principles of OOP Polymorphism, Encapsulation and Inheritence combines
together to make the programming robust and scalable
‘© Encapsulation allows to migrate the implementation without disturbing the code that
depends on class.
‘* Polymorphism allows to create clean, sensible, readable, resilient code.
‘© Inheritence mainly deals with the code reusabilityJava programs are a collection of whitespace, identifiers, literals, comments, operators,
separators, and keywords.
* Java is a free from language- means no need to follow any indentation rules.
© Whitespace is a space, tab, or newline.Key Words:
Java program is basically a collection of classes. A class is defined by a set of declaration
statements and methods containing executable statements. Most statement contains an
expression that contains the action carried out on data. The compiler recognizes the tokens
for building up the expression and statements. Smallest individual units of programs are
known as tokens. Java language includes five types of tokens, They are
(a) Reserved Keyword
(b) Identifiers
(c) Literals.
(d) Operators
(e) Separators,Identifiers:
Identifiers are programmer-designed token used for naming classes methods variable,
objects, labels etc. The rules for identifiers are
They can have alphabets, digits, dollar sign and underscores.
. They must not begin with digit.
. Uppercase and lower case letters are distinct.
They can be any lengths.
}. Name of all public method starts with lowercase.
. In case of more than one word starts with uppercase in nextword.
. Alll private and local variables use only lowercase and underscore.
. All classes and interfaces start with leading uppercases.
CP RNFHBAWHE
. Constant identifier uses uppercase letters only.
Example for valid identifiers:
Var_1, count, $value etc
identifiers:
6name, var@value, my/name etc
Literals in Java are sequence of characters that represents constant values to be stored in
variables. Java language specifies five major types of Literals. They are:
1. Integer Literals.
Floating-point Literals.
Character Literals.
String Literals.
oF wD
Boolean Literals
Operators:
An operator is a symbol that takes one or more arguments and operates on them to produce
an result.Separators:
Separators are the symbols that indicates where group of code are divided and arranged.
Some of the operators are:
‘Symbol Name [Purpose
0 Parentheses |Used to contain lists of parameters in method definition and invocation.
|Also used for defining precedence in expressions, containing expressions
|in control statements, and surrounding cast types.
0 Braces Used to contain the values of automatically initialized arrays. Also used
|to define a block of code, for classes, methods, and local scopes.
u [Brackets [Used to declare array types. Also used when dereferencing array values.
a Semicolon _ [Terminates statements.
w ‘Comma ‘Separates consecutive identifiers in a variable declaration. Also used to
[chain statements together inside a for statement.
Period Used to separate package names from subpackages and classes. Also
lused to separate a variable or method from a reference variable.The Scope and Lifetime of Variables
+ Java allows variables to be declared within any block. A block is begun with an
opening curly brace and ended by a closing curly brace. A block defines a scope.
‘* Ascope determines what objects are visible to other parts of your program. It also
determines the lifetime of those objects
* Many other computer languages define two general categories of scopes: global
and local. However, these traditional scopes do not fit well with Java_s st
object-oriented model
ct,
+ Asa general rule, variables declared inside a scope are not visible (that is, accessible)
to code that is defined outside that scope. Thus, when you declare a variable within a
Dr.Kumaresh Sheelavant, Associate Professor, CSE(AIML) 24
(OOP with Java BCS306A
scope, you are localizing that variable and protecting it from unauthorized access
and/or modification.
class Scope
{
public static void main(String argsf))
{
int x; known to all code within main x
if(x == 10) IT start new scope
{
int y = 20; // known only to this block
x and y both known here
‘System. out printin(’x and y: "+x" + y);x
Jy = 100; // Error! y not known here
11x still known here, System out println("x is * + x);
Note:
‘© There should not be two variables with the same name in different scope.
‘+ The variable at outer scope can be accessed in inner scope but vice versa is not
possiblefe C20) ieee bo
} for G= OQ > ji Syngit ty. aohhee
. Ltt prot ae eee 2 Jty J
| : Ae
5 3
4 CAblecation iss Mone
| Cl piteeonise pati at Bi >
OW ie ae
“AO stable cil dei) 2S
( (8-19 leclass BasieMath
public static void main(String argst))
(
OUTPUT:
// arithmetic using integers
ie nea Integer Arithmetic
System.out printin("Integer Arithmetic”);
ima=1+1;
im b=a*3;
ime=b/4;
int d=c-a;
inte =-4;
System.out printin("a =" + a)
System.out printin("b =" +b);
System,out printin("e =" +0)
System.out printin("d =" +d);
System.out printin("e =" +e)
r. Kumaresh 5, Assoc ProfTYPES OF OPERATORS IN JAVA
¥ Java provides rich set of operators.
Y Mainly divided into four groups, Arithmetic, Bitwise, Relational and Logical
Pein Prey
oe)
| A
ARITHMETIC OPERATORS
“Arithmetic operators are used in mathematical expressions in the same way
that they are used in algebra
Operator Result
he operands of the arithmetic
operators must be of a numeric type or
You cannot use them on boolean types, [s a
but you can use them on char types
since the char type in Java is a subset of
Arithmetic Operators
Sr ee
+ Addition 10+2 2
Subtraction 30-2 8
+ Multiplication 10*2 20
1 Diwision 10/2
% —— Medulus(remainder) 10% 2
4+ Increment 10)
= Decrement ‘a= (consider a= 10)
+= AdditionAssignment a= 10 (consider
“= Subtractionassignment a= 10 (consid
‘= Multipliation assignment a *= 10 (consider
/= —Divisionassignment ——_a/= 10 considera = 10)
X= Modulusassignment a %= 10 (consider = 10),
» stiri comRELATIONAL OPERATORS
+The relational operators determine the relationship that one operand has to the other.
“ Specifically, they determine equality and ordering.
“The outcome of these operations is a boolean value.
The relational operators are most frequently used in the expressions that control the if
statement and the various loop statements. Result
Equal to
Not ey
+*Example:
inta=4;
int b=1;
boolean c= acb:
RELATIONAL OPERATORS
OPERATOR | MEANING as RESULT
< Less than 1<2 True
Note:
a Greater than b2 False > Integers, Floating, Characters and
<= Less than or 1<=2 True boolean values can be compared
equal to using equality operators
>= Greater than 1>=2 False >Only numeric types can be
or equal to compared using the _ ordering
operators,
ss Equal to 1==2 False
l= Not equal to
resh SUAUSc Prof. 106BOOLEAN LOGICAL OPERA
+The Boolean logical operators shown here operate only on boolean operands
“All of the binary logical operators combine two boolean values to form a resultant
boolean value.
Operior Resut
1
n
7 [oR agi
~ OR aim
a
TearASSIGNMENT OPERATOR
‘The assignment operator is the single equal sign,
+P The assignment operator works in Java much as it does in any other computer language
Ithas this general form
var = expressi
“Here, the type of var must be compatible with the type of expression,
“The assignment operator can create a chain of assignments.
+ For example, consider this fragment:
int x,y, 2
== 100; // set x, y, and z to 100
+ This fragment sets the variables x, y, and z to 100 using a single statement.
This works because the = is an operator that yields the value of the right-hand expres
n.
“Thus, the value of z = 100 is 100, which is then assigned to y, which in turn is assigned to x.
eUsi
1g a chain of assignment is an easy,snayelosat.a.eroup of variables to a common valug,
TERNARY OPERATOR
“Java includes a special ternary (three-way) operator that can replace certain types of
if- then-else statements,
“This operator is the ? Or 2:
eneral form:
sxpression1 ? expression2 : expression3
> Here, expression can be any expression that evaluates to a boolean value.
> Ifexpressiont is true, then expression? is evaluated; otherwise, expression3 is evaluated
> Both expression2 and expression3 are required to return the same type, which can‘t be void.TERNARY OPERATOR
class Tern
{
7
public static void main(String args[])
// get absolute value of i
System.out.print("Absolute value of "); OUTPUT:
System.out.printin(i + "is" +k); ‘Absolute value of 10 is 10
Absolute value of -10 is 10
“10;
<02-i: is // get absolute value of i
System.out.print("Absolute value of "
System.out.printin(i +" 8*4°KSs
BITWISE OPERATORS
J->Bitwise operators act upon the individual bits of their operands [apa est
Java defines binvise operators that can be applied to | sey NOT
€ ie AND
and byte. T ine OR
{ine integer types, long, int, short,
the bitwise operators operate on individual bits of the De mADECR:
Stig
Integer types. > Ssh eo
It is better to know how integer types are represented = =
i ise ANDanigment
J<> Binary numbers > Integers E Tie ORaignnent
ine eacuive ORasignment
Sigh angen
Sl igh eo BaigentSemele wel}
isin an iter valet either left orgh a specified numberof tines
refered to as Let Right Shift Operator
‘Types of Shift Operators in Java
shit
Operators
SIGNED LEFT SHIFT OPERATOR
Let shift operator shifts the all of the bits in valve
>The symbol for this operator is <<, a
FAs a result, the left-mo
bit (mostsignificam) is
Aiscarded and the right-most positon(east-signifcant)
remains vacant, Tis vacancy i illed with Os
SIGIR CT am Mela ie eke sg
> Right shift operator shifts the all ofthe Dts na value towards FIgh a specified numberof positions
> The symbol for this operators >>.
>General Form:
1 the meaning is to shift the bits of
towards right
specified postions
>>> shifts the bts towards the right and also preserve the sign bit, which isthe leftmost bit
>The |
bit represents the sign of the number. The sign bit @ represents a positive number,
and I represents a negative number
>So after performing >> on a positive number, we get « postive value inthe result also. When we
perform > ve number, again wees .negatne salve
GC USO
the op (lfros) bi filled with the previous content ofthe top it
> Thin is called sgn extension ans needed to preserve he sgn of native numbers when we sift them ht.
ea fhifip poppe
ebb P 4 von fifa pape]Control Statements
‘© Java's program control statements can be put into the following categories: selection,
iteration, and jump.
'* Selection statements allow your program to choose different paths of execution based
upon the outcome of an expression or the state of a variable.
‘* Iteration statements enable program execution to repeat one or more statements (that
is
iteration statements form loops)
‘+ Jump statements allow your program to execute in a nonlinear fashion,
Java's Selection Statements
‘* Java supports two selection statements:
f and switch.
The if statement
‘+ The if statement executes a block of code only if the specified expression is true.
‘+ Ifthe value is false, then the if block is skipped and execution continues with the rest
of the program.
‘+ You can either have a single statement or a block of code within an if statement.
‘+ Note that the conditional expression must be a Boolean expression.
Syntax:
if () {
Example:
public class Example {
public static void main(String[] args) {
int a=10,
if (@>b)
‘System. out printin("a > b”
if (@ a");«The if statement is Java’s conditional branch statement. It can be used to route
program execution through two different paths.
* Here is the general form of the if statement:
Syntax:
if (condition)
statement;
else statement2;
‘* Here, each statement may be a single statement or a compound statement enclosed in
curly braces (that is, a block).
‘* The condition is any expression that returns a boolean value. The else clause is
optional
‘© The if works like this: If the condition is true, then statement is executed. Otherwise,
statement2 (if it exists) is executed
Example:
public class Example {
public static void main(String[] args) {
inta = 10, b= 20;
if (@>b)
‘System. out.printin(“a > b");
else
‘System.out.printin("b > a");‘The switch statement
‘The switch case statement is a mult-way branch with several choices. switch is
easier to implement than a series of ilelse statements
Structure of Switch:
+The site statement begins with a keyword, followed by an expression that equates
too long integral value.
+ Following the controling expression is a code block that contains zero or more
labeled cases
+ Each label must equate oan iteger constant and each must be unigue
Working of switch case:
‘When the switch statement executes, it compares the value ofthe controlling
expression to the values ofeach case label
Dr umaresh Shela, Associate Profesor, CSE(AIML)
(00° with Jv cs3068
‘© The program wil select the value of the case label that equals the value of the
contrlling expression and branch down that path to the end ofthe code block.
+ If none of the case label values match, then none of the codes within the siteh
statement code block will be executed Java includes a default label to use in cases
here there are ro matches,
‘© We an havea nested switch within acase block of an outer switch
‘syntax:
‘witch (; break
ase label2: ; break;
ase label: ; break;
default:
}
Exampl
Public class Example {
publi static void meinStig( ars) {
inta=10,=20,
intstaus =
Warbawaroe 43/56
status = 1
Jelse if (0> 0) {
suas =2
else {
staus=3
>
‘switch (status) {
case
‘Systm. out pritin"a is te greatest)
break;
caseSystem out.prntin("bis the greatest’);
break;
case 3
System. out print ‘cis the greatest’);
break;
default
System out printin(*Cannot be determined”)
‘+The break statement is optional. If you omit the break, execution will continue on
into the next case.
‘+ Itis sometimes desirable to have multiple cases without break statements between
them.
‘© For example, consider the following program:
1 Ina switch, break statements are optional
class MissingBreak {
public static void main(String argsQ) {
for(int i=0; i<12; i++)
switeh(i) {
case 0:
case:
case 2
case 3:
case 4:
System. out printin("
break;
is less than 5")
case 5:
case 6:
case 7
case 8:
case 9)
Dr.Kumaresh Sheelavant, Associate Professor, CSE(AIML)
44/56 _
(00? with Java BCS306A,
System.out.printin(”
break;
is less than 10");
default
‘System. out.printin(" is 10 or morThe while loop
‘* The while statement is a looping construct control statement that executes a block of
code while a conditi
true.
+ You can either have a single statement or a block of code within the while loop.
+ The loop will never be executed if the testing expression evaluates to false.
* The loop condition must be a boolean expression.
Syntax:
while () {
Example:
public class Example {
public static void main(String{] args) {
int count = 1;
System.out.printin( "Printing Numbers from 1 to 10");
while (count <= 10) {
‘System.out.printIn(count++);She do-while loop
‘+ The doswhile loop is similar to the while loop, except that the test is performed at the
end of the loop instead of at the beginning.
‘© This ensures thatthe loop will be executed at least once.
dot
} while ();
Dr.Kumaresh Sheelavant, Associate Professor, CSE(AIML)
0? with Java BCS306A
‘Example
public class Example {
public static void main(String(] args) {
int count = 1;
‘System.out printin( "Printing Numbers from 1 to 10");
do{
System.out printin(count++)
} while (count <= 10);
The for loop
+ The for loop is a looping construct which can execute a set of instructions a specified
number of times. I's a counter controlled Loop.
for (; ; ) {
Example:
public class Example {
public static void main(String[] args) {
‘System.out printin( "Printing Numbers from 1 to 10");
for (int count = 1; count <= 10; count++) {
System.out.printin(count);
} 47/56The continue statement
© A continue statement stops the iteration of a loop (while, do or for) and causes
execution to resume at the top of the nearest enclosing loop.
+ You use a continue statement when you do not want to execute the remaining
statements in the loop, but you do not want to exit the loop itself
You can also provide a loop with a label and then use the label in your continue
statement
‘The label name is optional, and is usually only used when you wish to return to the
outermost loop in a series of nested loops.
Syntax:
continue; / the unlabeled form
continue