0% found this document useful (0 votes)
20 views21 pages

Java Unit-1 Final

Uploaded by

rajfelix1969
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
20 views21 pages

Java Unit-1 Final

Uploaded by

rajfelix1969
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 21

JAVA PROGRAMMING UNIT-I

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.

Compile and Runtime Environment

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.

Java Virtual Machine


JVM Window
---- ----
---- Javac ---- JVM
Window
---- ---- MAC
---- ----
First.java First.class
JVM Linux

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.

JAVA DEVELOPMENT KIT(JDK):


 JDK is a software development environment. JDK consists of variety of
programming tools to develop, compile, debug and run Java applications
and applet programs.
 Some of the basic tools are,
1. javac
2. java
3. javadoc
4. jdb
5. javah
6. javap
7. appletviewer
1. javac:
 The Java compiler, which is used to converts source code into byte code.
2. java:
 The java interpreter which runs Java applications and applets by reading
and interpreting byte code files.
3. javadoc:
 It creates HTML format documentation from Java source code files.
4. jdb:
 The Java debugger, which is used to find errors in our programs.
5. javah:
 It produces C header and stub generator. It used to write native methods.
6. javap:
 It is class file disassembler. It is used to convert byte code files into a
program description.
7. appletviewer:
 It runs applets outside of a web browser.

Page 4 of 21
JAVA PROGRAMMING UNIT-I

OOP (OBJECT ORIENTED PROGRAMMING):


 Object Oriented programming is a programming style which is associated
with the concepts like class, object, Inheritance, Encapsulation, Abstraction.
 Java follows the oop style of programming.
 The important key concepts of oop are
1. Object
2. Class
3. Inheritance
4. Polymorphism
5. Abstraction
6. Encapsulation
7. Dynamic Binding
8. Message Passing
1. Object:
 Objects are the “basic unit” of any object-oriented programming
language. Objects are said to be a “real time entities” because an object
can be a person, a place, a book or anything that the computer must deal.
2. Class:
 Class is a grouping of variables and methods and its one or more
associated objects. Class is said to be a “logical entity”.
3. Inheritance:
 Inheritance is the process of creating a new class from the existing class.
New class inherits the properties and behavior of existing class.
 Inheritance provides “reusability”.
4. Polymorphism:
 One task is performed by different ways is called polymorphism.
 In java, we use method overloading and method overriding to achieve
polymorphism.
5. Abstraction:
 Hiding internal details and shows only the essential features is known as
abstraction.
 In Java, we use abstract class and interface to achieve abstraction.
6. Encapsulation:
 Binding (or wrapping) code and data together into a single unit is known
as encapsulation.
 In Java, we use class to achieve encapsulation.
7. Dynamic Binding:
 Binding refers to the “linking of procedure call to the code” is known as
dynamic binding.
 Dynamic binding means which code is to be executed is no known until
the time of the call at runtime.
8. Message passing:
 While the execution of programs, objects may communicate with each
other by means of sending and receiving messages between them.

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

JAVA PROGRAM STRUCTURE:


A JAVA program may contain many classes. Classes contain data members
and methods. Methods may contain data type declarations and executable
statements.
Documentation Section Suggested
Package Statement
Import Statements Optional
Interface Statements
Class Definitions
main method
{
main method definition essential
}
 Documentation Section:
The documentation section comprises a set of comment lines giving the
name of the program, the author and other details.
 /* ………………………………… */ known as documentation comment. It is
used for multi-line comments.
 // used for single-line comments.
 Package Statement:
 The first statement allowed in a java file is a package statement. It is
optional.
 For example, package student;
 Import Statements:
 Using import statements, we can have access to classes that are part
of other named packages.
 For example: import student.test;
 It instructs the interpreter to load the test class contained in the
package student.
 Interface Statements:
 An interface is like a class but includes a group of method
declarations.
 It is used only when we wish to implement the multiple inheritance
features.
 Class Definitions:
 Classes are the primary and essential elements of a java program.
 It is used to map the objects of real-world problems.
 main method Class:
 The JAVA program requires a main method as its starting point.
 The main method creates objects of various classes and establishes
communications between them.
 On reaching the end of main, the program terminates and the control
passes back to the operating system.

Page 7 of 21
JAVA PROGRAMMING UNIT-I

IMPLEMENTING A JAVA PROGRAM:


To implement the JAVA program must follow these steps are,
 Create the program
 Compile the program
 Run the program
Create the Program:
 We can create using any text editor. We must save this program as
classname.java
 For example,
All methods
class
keyword import java.io.*; used for print stream or read/write on disk
class test
{ packages
public static void main(String args[ ])
{
System.out.println(“Welcome”);
}
}
We must save as test.java
Compile the Program:
 To compile the program on the command line
javac test.java
 The javac compiler creates a file called test.class containing the
bytecodes of the program.
Run the Program:
 To run the program, java test
 The JAVA interpreter looks for the main method, begin execution from it.
 When executed the program displays, Welcome

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

Numeric Constants Character Constants

Integer Constants Real Constants Character constants String Constants


Backslash Constants
Decimal integer Octal integer Hexadecimal integer
Integer Constants:
 An integer constant refers to a sequence of digits. There are 3 types of
Integers, namely
1. Decimal Integer
2. Octal Integer
3. Hexadecimal Integer
1. Decimal Integer:
Decimal integers consist of a set of digits, 0 through 9, preceded by an
optional minus sign. For example: 123 -789 0 654321
2. Octal Integer:
An Octal Integer constant consists of any combination of digits from
the set 0 through 7 with a leading 0. For example: 037 0 0435 0551
3. Hexadecimal Integer:
 A sequence of digits preceded by Ox or 0X is considered as hexadecimal
integer. It includes alphabet A through F.
 A letter A through F represents the numbers 10 trough 15.
For example : OX2 OX9F Oxbcd Ox.
Real Constants:
 The quantities like distances, heights, temperatures, prices and so on are
represented by numbers containing fractional parts like 17.548
 Such numbers are called real (or floating point) constants.
For example: 0.0083 -0.75 435.36
Single Character Constants: (Character Constants)
 A single character constant contains a single character enclosed within a
pair of single quote marks. For example: ‘5’ ‘X’ ‘;’ ‘a’
 The characters may be alphabets, digits, special characters and blank
spaces.

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.

DATA TYPES IN JAVA

Primitive Non-Primitive
(Built-in) (Derived)

Classes Interface Arrays

Numeric Non-numeric

Integer Floating-point Character Boolean

Byte Short Int Long Float Double

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

TYPE WIDTH/SIZE RANGE


Byte 8 – bit -128 to 127
Short 16 – bit -32,768 to 32,767
Int 32 – bit -2,147,483,648 to 2,147,483,647
-9,223,372,036,854,775,808 to
Long 64 – bit
9,223,372,036,854,775,807
1. byte:
 The smallest integer type is byte.
 Signed 8-bit type.
 A range from -128 to 127.
 We must use a byte variable to handle the number 50 to store.
For example: byte b = 50;
 It will improve the speed of execution of the program.
2. short:
 Short is a signed 16-bit type.
 It has a range from -32,768 to 32,767.
 It’s the least-used JAVA type. For example: short x;
3. int:
 The most commonly used integer type is int.
 It is a signed 32-bit type.
 It has a range from -2,147,483,648 to 2,147,483,648. For example: int c;
4. long:
 Long is signed 64-bit type.
 It is useful where an int type is not large enough to hold the desired
value.
 The range of a long is quite large. For example: long x =123L; long a=24l;
Floating-Point Types:
 Floating point type to hold numbers containing fractional parts. There are
two types of floating point storage in JAVA.
 Floating point data types support a special value known as
“Not-a-Number(NaN)”.
 NaN is used to represent the result of operations such as dividing zero by
zero.
TYPE WIDTH/SIZE RANGE
float 32 – bit 3.4e-038 to 3.4e+038
double 64 – bit 1.7e-308 to 1.7e+308

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

 JAVA does the conversion of the assigned value automatically is called as


automatic type conversion.
 For example: byte b = 75;
int a = b;

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

 The use of shorthand assignment operators has the following advantages:


1. What appears on the left hand side need not be repeated and
therefore it becomes easier to write.
2. The statement is more concise and easier to read.
3. Use of shorthand operator results in a more efficient code.
import java.io.*;
class assignment
{
public static void main(String args[ ])
{
int x = 6, y = 1;
x += 2;
y *= x/2;
System.out.println(x);
System.out.println(y);
}
}
In this program, x += 2; => it means x = x + 2;
ie, x=6+2=8
y *= x/2; => y = y*(x/2);
ie, y = 1 * (8/2) = 4
so it will displays, 8
4
5. Increment & Decrement Operators:
Increment and decrement operators are called as Unary Operators. The
operators are,
++(Increment Operator) is add or increase 1 to the operand
--(Decrement Operator) is subtract or decrease 1 to the operand
For example,
++m => m = m+1; or m += 1;
--m => m = m-1; or m -= 1;
These operators appear both in “Postfix” and “Prefix” form.
1. Postfix form:
Previous value is obtained for used in expressions and operand in
modified. For example: m++, a--
2. Prefix form:
Operand increment or decrement before the value is obtained for
use in the expression. For example: ++m, --a
Consider case
i. m = 5; y = ++m;
here, the value of m would be increased by 1 and also stored the
value of y.
ie, m = 6 and also y = 6.
ii. m = 5; y = m++;
here, the value of y would be 5 and m would be 6.

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

You might also like