Вы находитесь на странице: 1из 46

Module - 2

Overview of Java
 Java is an object-oriented programming language with its own runtime
environment.
 Java is a programming language and a platform. Java is a high level, robust,
secured and object-oriented programming language.
 Platform: Any hardware or software environment in which a program
runs is known as a platform. Since Java has its own runtime environment
(JRE) and API, it is called platform.
 Java was developed by Sun Microsystems Inc. in 1991, later acquired by Oracle
Corporation. It was conceived by James Gosling and Patrick Naughton. It took

.in
18 months to develop the first working version. (The initial name was Oak but it
was renamed to Java in 1995 as OAK was a registered trademark of another
Tech company).
 Java programs are platform independent which means they can be run on any

available on that system. ac


operating system with any type of processor as long as the Java interpreter is

 A Java interpreter executes lines of byte code as commands to be


tu
executed. The byte code is executed. The JVM takes the byte code and
generates machine code. The byte code is compiled to machine code, and
the machine code is executed.
.v

 Java code that runs on one platform does not need to be recompiled to run on
another platform, it’s called “Write Once, Run Anywhere” (WORA).
w

 Java Virtual Machine (JVM) executes Java code, but is written in platform
specific languages such as C/C++/ASM etc. JVM is not written in Java and hence
w

cannot be platform independent and Java interpreter is actually a part of


JVM.
 The latest release of the Java Standard Edition is Java SE 8. With the
w

advancement of Java and its widespread popularity, multiple configurations


were built to suit various types of platforms. For example: J2EE for Enterprise
Applications, J2ME for Mobile Applications.

History of Java Technology?


 History of Java programming language is usually associated with origin
predates the web.
 James Gosling, Patrick Naughton, Chris Warth, Mike Sheridan and Ed
Frank initiated the Java language project in June 1991. The idea was to

Jagadeesh A Y, Dept. of CSE SPCE 1


develop a language which was platform-independent and which could create
embedded software for consumer electronic devices. The language took 18
months to develop and had an initial name as “Oak” which was renamed to
Java in 1995, due to copyright issues. Originally, developed by James Gosling
at Sun Microsystems (which has since merge into Oracle Corporation) and
released in 1995. JDK 1.0 released In January 23, 1996.
Where is Java being used?
Earlier, Java was only used to design and program small computing devices but
later adopted as one of the platform independent programming language and now
according to Sun, 3 billion devices run Java.
 JSP – Java is used to create web applications like PHP and ASP, JSP (Java
Server Pages) used with normal HTML tags, which helps to create dynamic
web pages.

.in
 Applets – This is another type of Java program that used within a web page
to add many new features to a web browser.
 J2EE – The software Java 2 Enterprise Edition are used by various


another. ac
companies to transfer data based on XML structured documents between one

JavaBeans – This is something Visual Basic, a reusable software component


tu
that can be easily assemble to create some new and advances application.
 Mobile – Besides the above technology, Java is also used in mobile devices to
build various kinds of applications.
.v

Types of Java Applications


w

 Web Application: Java is used to create server-side web applications.


w

Currently, servlets, jsp, struts, jsf etc. technologies are used.


 Standalone Application: It is also known as desktop application or
window-based application. An application that need to be installed on every
w

machine or server such as media player, antivirus etc. AWT and Swing are
used in Java for creating standalone application.
 Enterprise Application: An application that is distributed in nature, such
as banking applications etc. It has the advantage of high level security, load
balancing and clustering. In java, EJB is used for creating enterprise
applications.
 Mobile Application: Java is used to create application for mobile devices.
Currently Java ME is used for creating applications for small devices.

Jagadeesh A Y, Dept. of CSE SPCE 2


Features of Java
 Object Oriented – In java everything is an Object. Object oriented
programming is a way of organizing programs as collection of objects, each
of which represents an instance of a class.
 Platform independent –During compilation, the compiler converts java
program to its byte code. This byte code can run on any platform such as
Windows, Linux, Mac / OS etc. which mean a program that is compiled on
windows can run on Linux and vice-versa. This is why java is known as
platform independent language.
 Easy to learn – Java is simple because, syntax is based on C or C++.
 Secure – It provides a virtual firewall between the application and the
computer. Java codes are confined within Java Runtime Environment
(JRE). Thus, it does not grant unauthorized access on the system

.in
resources.

ac
tu
.v
w

 Architectural-neutral – Java compiler generates an architecture-


w

neutral object file format which makes the compiled code to be executable
on many processors, with the presence of java runtime system.
w

 Portable – Java code that is written on one machine can run on another
machine. The platform independent byte code can be carried to any
platform for execution that makes java code portable.
 Multi-threaded – With Java’s multi-threaded feature it is enabled a
program to perform several tasks simultaneously.
 High Performance – With the use of Just-In-Time compilers Java
enables high performance.

Jagadeesh A Y, Dept. of CSE SPCE 3


Java Editors

To write java programs, you will need a text editor. There are even more
sophisticated IDE available.
 Notepad – On Windows machine you can use any simple text editor like
Notepad, TextPad.
 Netbeans – is a Java IDE that is open source and free which can be
downloaded from https://www.netbeans.org/index.html.
 Eclipse – A Java IDE developed by the open-source community and can be
downloaded from https://www.eclipse.org/.
Environment Setup and Java Program Structure

.in
Before Installation and setting up of environment variable, let us know about Java
SE Development Kit (JDK). It contains
1. JDK (Java Development Kit)
2. JRE (Java Run Time Environment)
3. JVM (Java Virtual Machine)
Java Development Kit (JDK)
ac
tu
 JDK contains everything that will be required to develop and run Java
application.
.v

 JDK includes a complete JRE (Java Runtime Environment) plus tools for
Developing, Debugging, and Monitoring Java applications. JDK is needed to
develop Java applications and Applets as well as run them. It contains
w

o Java Run time Environment (JRE)


w

o Interpreter / Loader (java)


o Compiler (javac)
w

o Archiver (jar)
o Documentation Generator (java doc)
 javac: javac is the compiler for the Java programming language, it’s used
to compile .java file.
Example: c:\> javac TestFile.java
 java: command is used to compile a java program, it creates a class file
which can be run by using java command.
Example: c:\> java TestFile.class

Jagadeesh A Y, Dept. of CSE SPCE 4


 javadoc: JavaDoc is a API documentation generator for the Java
language, which generates documentation in HTML format from Java
source code.
 appletviewer: Applet viewer run and debug applets without a web
browser, its standalone command-line program to run Java applets.
 jar: A jar is (manage Java archive) a package file format that contains
class, text, images and sound files for a Java application or applet
gathered into a single compressed file.
Java Runtime Environment
 JRE contains everything required to run Java application which has already
been compiled.
 It doesn’t contain the code library required to develop Java application.

.in
Java Virtual Machine (JVM)
The Java Virtual Machine is called JVM, is an abstract computing machine or
virtual machine interface that drives the java code.


ac
Mostly in other Programming Languages, compiler produce code for a
particular system but Java compiler produces Bytecode for a JVM.
Bytecode is an intermediary language between Java source and the host
tu
system.
 JVM interprets the bytecode to OS specific instructions.
.v

 JVM is platform independent.


 JVM is responsible to allocate the necessary memory needed by the java
program.
w

 JVM is responsible to de allocate a memory.


w

 The JVM is the heart of the Java language’s developed based on "write-once, run-
anywhere" principle.
w

“JRE = JVM + Required Library to run Application.”


“JDK = JRE + Required Library to develop Java Application.”

Jagadeesh A Y, Dept. of CSE SPCE 5


First Program in Java

.in
Let us create HelloWorld.java program,
class HelloWorld
{

{ ac
public static void main(String args[])

System.out.println("HelloWorld!!!");
tu
}
}
In the above program,
.v

 class is a keyword used to declare a class in java.


 public is a keyword used to specify access modifier. Public means it is
w

visible to all.
 static is a keyword, if we declare any method as static, it is known as
w

static method. The advantage of static method is that there is no need to


create an object to invoke the static method. The main method is executed
by the JVM, so it doesn't require to create object to invoke the main
w

method.
 void is the return type of the method, it means it doesn't return any value.
 main represents beginning of the program.
 String[] args is used for command line argument.
 System.out.println() is used print statement.
Note: Name of the file & name of a class must be same.
How to Compile and Execute java program
 To Compile: javac helloWorld.java
 To Execute: java helloWorld

Jagadeesh A Y, Dept. of CSE SPCE 6


Data types and other tokens
Data type: It specifies type of data to be stored in variables. Whereas variables are
the names given to memory locations in which values can be stored.
There are two different data types in Java, namely
 Primitive Data type
 Reference / Object Data type
Primitive Data Type
By default, primitive data types are supported by Java. Each type is represented
using keyword. There are eight different primitive data types, namely
 byte
 short

.in
 int
 long
 float
 double
 char
ac
tu
 boolean
The following should be understood for every data type:
.v

1. Memory size allocated.


2. Default value.
w

3. Range of values it can represent.


4. Minimum values can be represented.
w

5. Maximum value can be represented.


Boolean
w

1. Allocated Memory Size: 1 bit


2. Default value: False
3. Keyword: boolean
4. Example: boolean a = TRUE;
5. It represents either TRUE or FALSE

Jagadeesh A Y, Dept. of CSE SPCE 7


Byte

 Allocated Memory Size: 1 byte or 8 bits


 Default value: Zero
 Keyword: byte
 Example: byte a = 100
 Minimum Value can be represented: -128 (-27)
 Maximum Value can be represented: 127
Char

 Allocated Memory Size: 2 bytes or 16 bits


 Default value: '\u0000'

.in
 Keyword: char
 Example: char ch = 'A';


Short
ac
Minimum Value can be represented: '\u0000' (0)
Maximum Value can be represented: '\uffff' (65,535)
tu
 Allocated Memory Size: 2 bytes or 16 bits
 Default value: Zero
.v

 Keyword: short
 Example: short s = 1000;
w

 Minimum Value can be represented: -32,768 (215)


w

 Maximum Value can be represented: 32,767 (215 - 1)


Int
w

 Allocated Memory Size: 4 bytes or 32 bits


 Default value: Zero
 Keyword: int
 Example: int a = 10;
 Minimum Value can be represented: - 2,147,483,648 (-231)
 Maximum Value can be represented: 2,147,483,647 (231)

Jagadeesh A Y, Dept. of CSE SPCE 8


Float

 Allocated Memory Size: 4 bytes or 32 bits


 Default value: 0.0f
 Keyword: float
 Example: float x = 2.3f;
 Minimum Value can be represented: 1.4E-45
 Maximum Value can be represented: 3.4028235E38
Long

 Allocated Memory Size: 8 bytes or 64 bits


 Default value: 0L

.in
 Keyword: long
 Example: long b = 100000L;


Double
ac
Minimum Value can be represented: -9223372036854775808
Maximum Value can be represented: 9223372036854775807
tu
 Allocated Memory Size: 8 bytes or 16 bits
 Default value: 0.0d
.v

 Keyword: double
 Example: double d = 3.1428571
w

 Minimum Value can be represented: 4.9E-324


w

 Maximum Value can be represented: 1.7976931348623157E308


Tokens
w

Tokens are group of characters combined to form meaningful word.


There are five types of tokens, namely
1. Keywords
2. Identifiers
3. Literals
4. Operators
5. Separators

Jagadeesh A Y, Dept. of CSE SPCE 9


Keywords
 Keywords are also called as reserved words.
 Keywords have predefined meaning in Java language.
 There are 49 keywords are currently available in Java language.

abstract assert boolean break byte

case catch char class const

continue default do double else

extends false final finally float

.in
for goto if implements import

instanceof int interface long native

new package privateac protected public


tu
return short static super switch

synchronized this throw transient true


.v

try void volatile while


w

Identifiers
w

Identifiers are the names given for variables, classes, functions, objects, packages,
interfaces in Java program.
w

Rules to write variables


1. It may consists of letters, digits or underscore ( _ ).
2. First character must be either letter or underscore.
3. Identifiers are case sensitive.
4. Identifiers can be of any length.

Literals (Constants)
It is sequence of characters (includes letters, digits, special characters) that
represent constant values to be stored in variable. There are five types of literals,
namely

Jagadeesh A Y, Dept. of CSE SPCE 10


1. Boolean Literals
2. Integer Literals
3. Floating Literals
4. Character Literals
5. String Literals
Boolean Literals
 Boolean literals have values TRUE or FALSE
 In Java, “1” is not considered as TRUE & “0” is not considered as FALSE as like
in C.
 Example: boolean b = TRUE
 Boolean values should not be enclosed in double quotes.

.in
Integer Literals
 Integers are whole numbers do not contain fractional part.

 ac
The sign + & - is used to denote positive and negative numbers respectively.
The integer literals are classified into following categories
▪ Decimal Literals (Base 10 Numbers)
tu
 It is a combination of digits between 0 to 9.
 The sign + and - is used to denote positive and negative numbers
.v

respectively.
 Ex: 10, 200, 20000 etc. are valid decimal literals.
w

▪ Octal Literals (Base 8 Numbers)


w

 It is a combination of digits between 0 to 7 with a prefix 0 (zero).


 It is a base 8 number with prefix 0.
w

 Ex: 0123, 0345, 067 etc. are valid octal literals.


▪ Hexadecimal Constant (Base 16 number)
 It is a combination of numbers between 0 to 9 along with A to F or a
to f.
 Hexadecimal numbers must precede with 0X or 0x.
 Ex: 0X12AF, 0x34EA etc are valid hexadecimal number.

Jagadeesh A Y, Dept. of CSE SPCE 11


Floating Literals
 Floating point literals are base 10 numbers with fractional part.
 The sign + and - is used to denote positive and negative floating point
numbers respectively.
 The floating literals are classified into following categories
float
▪ The suffix “F” or “f” is appended to value to designate data type as
float.
▪ Example: float x = 3.142f
double

.in
▪ By default floating point literal is double.
▪ The suffix “D” or “d” is appended to value to designate data type as
double.
▪ Example: double d = 3.1428571d
Character Literals

ac
It is a single 16-bit Unicode character.
tu
 Character literals are enclosed in single quotes.
 Example: char ch = 'A';
.v

Character Unicode
w

Value

A '\u0041'
w

a '\u0061'
w

0 '\u0030'

String Literals
 It is sequence of characters.
 String literals should be enclosed in double quotes.
 Example: String str = “Hello”;

Jagadeesh A Y, Dept. of CSE SPCE 12


Operators
Operators are a character which denotes type of operation to be performed on the
operands.
There three types of operators based on number of operands, namely
1. Unary operators (Uses one operand): ++a, a++, --a, a--
2. Binary operators (Uses two operands): a+b, a*b
3. Ternary operators (Uses three operands): a?b:c
Separators
 Separators in Java programming is used to define the structure of the
program's.
 Java supports below separators

.in
Separator Name Use

,
Period

Comma ac
Separate packages, access class members

Separate variables, parameters


tu
; Semicolon Terminate statements.
.v

() Parenthesis Actual parameters, Formal parameters

{} Braces To define block, function definition, class


w

[] Brackets To declare array


w

Arrays
w

It is collection of elements of similar data type.


There are two types of arrays, namely
1. One Dimensional Arrays
2. Multi-Dimensional Arrays
One Dimensional Array
 It is collection of elements of similar data type, where elements are stored in
contiguous memory locations.
 By default, array locations are initialized to zero.

Jagadeesh A Y, Dept. of CSE SPCE 13


Syntax to declare one dimensional array
data_type[] variable_name; OR
data_type []variable_name; OR
data_type variable_name[];
Memory allocation to array
data_type[] variable_name = new data_type[size];
Where
data_type → short, int, long, float, double
variable_name → valid identifier
new → keyword

.in
size → size of the array
Example: int[] array1 = new int[10];
In the above example, array1 holds 10 values.
Array Initialization
ac
Initialization is a method in which array is declared and values are assigned to
array at the same line.
tu
Method 1
Example: int array1[] = {31, 28, 31, 30, 31, 30, 31, 31};
.v
w

Program 1: To initialize one dimensional array & print


elements.
w

public class OneDimensionalArray {


public static void main(String[] args) {
w

int array1[] = {5, 6, 7, 8, 9};


for(int i=0; i<4; i++)
{
System.out.println(array1[i]);
}
}
}
Output:

Jagadeesh A Y, Dept. of CSE SPCE 14


Method 2
Program 2: To initialize one dimensional array & print elements.
public class OneDimensionalArray {
public static void main(String[] args) {
int[] array1 = new int[] {5, 6, 7, 8, 9};
for(int i=0; i<4; i++)
{
System.out.println(array1[i]);
}
}
}

.in
Output:

Two Dimensional Arrays


 ac
It is collection of elements of similar data types, where elements are arranged
in rows and columns.
tu
 By default, array locations are initialized to zero.
 Syntax to declare one dimensional arrays
.v

data_type[][] variable_name; OR
data_type [][]variable_name; OR
w

data_type variable_name[][];
Memory allocation to array
w

data_type[][] variable_name = new data_type[row_size][column_size];

Where
w

data_type → short, int, long, float, double


variable_name → valid identifier
new → keyword
row_size → number of rows
column_size → number of columns
Example: int[][] array1 = new int[3][3];
In the above example, array1 holds three rows & three columns.

Jagadeesh A Y, Dept. of CSE SPCE 15


Method 1
Example: int array1[][] = { {31, 28, 31},
{30, 31, 30,},
{31, 31, 30}
};
Program 3: To initialize two dimensional array & print elements.
public class TwoDimensionalArray {
public static void main(String[] args) {
int[][] array1 = new int[][] {{31, 28, 31},
{30, 31, 30,},
{31, 31, 30}

.in
};
for(int i = 0; i<3; i++)
{

ac
for(int j=0; j<3; j++)
{
tu
System.out.print("\t"+array1[i][j]);
}
.v

System.out.println();
}
w

}
}
w

Output:
w

Method 2
Example: int[][] array1 = new int[][]
{ {31, 28, 31},
{30, 31, 30},
{31, 31, 30}
};

Jagadeesh A Y, Dept. of CSE SPCE 16


Program 4: To initialize two dimensional array & print elements.
public class TwoDimensionalArray {
public static void main(String[] args) {
int array1[][] = {{31, 28, 31},
{30, 31, 30,},
{31, 31, 30}
};
for(int i = 0; i<3; i++)
{
for(int j=0; j<3; j++)
{

.in
System.out.print("\t"+array1[i][j]);
}

}
}
ac
System.out.println();
tu
}
Output:
.v
w

Assigning Values
w

 The values to variables are assigned using assignment operator (=).


 Example: int a = 100;
w

 In above example, value 100 is stored in the variable a.


Access Modifiers
Access modifiers are used to specify visibility of class, variables, methods &
constructors. There are four access modifiers in java, namely
1. Default
2. Private
3. Public
4. Protected

Jagadeesh A Y, Dept. of CSE SPCE 17


Access Modifiers Default Private Protected Public

Accessible inside the class Yes Yes Yes Yes

Accessible within the subclass inside


Yes No Yes Yes
the same package

Accessible outside the package No No No Yes

Accessible within the subclass outside


No No No Yes
the package

.in
Operators and Expressions
An operator is a symbol that specifies the type of operation to be performed on
variables or values.

single constant value. ac


An expression is a sequence of operators & operands, which will be evaluated to

Precedence or priority: of an operator decides which terms should be evaluated


tu
first in any expression. For Example: c=a+b*20;
In the above expression b*20 will be evaluated first and then a+(result of b*20).
.v

Since * (multiplication) is having higher precedence over + (addition).


Associativity: When 2 or more operators have same priority, then associativity of
w

an operator tells the direction to evaluate terms i.e. either from left-to-right or
right-to-left. For Example: c=a*b-d/20;
Here * and / are equal priority, so operators are evaluated from left-to-right.
w

Java provides a rich set of operators to manipulate variables. We can divide all the
Java operators into the following groups:
w

Arithmetic Operators
 Arithmetic
 Relational Operators
 Bitwise Operators
 Logical Operators
 Assignment Operators
 Misc. Operators

Jagadeesh A Y, Dept. of CSE SPCE 18


Arithmetic Operator
 These operators are used to perform basic arithmetic operations such as
addition, subtraction, multiplication, division and remainder.
 Arithmetic operators operates on two operands, hence they are called as
binary operators.
 An expression which consists of only arithmetic operators & operands is
called as arithmetic expression.
 Ex: a+b, b-c, c/d, x%y, x*y
Operators, Precedence & Associativity

Operation Operator Precedence Associativity

.in
Multiplication * 1 L→R

Division / 1 L→R

Remainder

Addition
%

+
ac 1

2
L→R

L→R
tu
Subtraction - 2 L→R
.v

Modes of arithmetic expressions


w

The arithmetic operators can acts on integer and real number. So based on the type
of the operands arithmetic expressions are divided into 3 modes, namely
1. Integer mode arithmetic expression
w

2. Floating point arithmetic expression


w

3. Mixed mode arithmetic expression


Integer mode arithmetic expression
 All the operands in an expression must be of type integer.
 A result of integer expression must be an integer.
 Ex: 10/2=5, 9*2=18, 4/3=1 (not 1.33)
Floating point arithmetic expression
 All the operands in an expression must be of type floating point numbers or
double values.
 The result of floating point expression must be floating point number.

Jagadeesh A Y, Dept. of CSE SPCE 19


 Ex: 5.0/2.0=2.0, 4.0/3.0=1.333, 4.0/2.0=2.0 (floating)
Mixed mode arithmetic expression
 An expression that has operands of different data types.
 Always the data of lower rank will be converted to higher rank.(refer type
conversion)
 Example
int a = 4, b = 2;
float x = 2, y;
y = (a * b) / x;
= (4.0 * 2.0) / 2.0;
= 4.0;

.in
Program 5: To perform arithmetic operations.
public class Addition {
public static void main(String args[]) {
int a = 10;
ac
tu
int b = 20;
int c = 25;
.v

int d = 25;
System.out.println("a + b = " + (a + b) );
w

System.out.println("a - b = " + (a - b) );
System.out.println("a * b = " + (a * b) );
w

System.out.println("b / a = " + (b / a) );
System.out.println("b % a = " + (b % a) );
w

System.out.println("c % a = " + (c % a) );
System.out.println("a++ = " + (a++) );
System.out.println("b-- = " + (a--) );
System.out.println("d++ = " + (d++) );
System.out.println("++d = " + (++d) );
}
}
Output:

Jagadeesh A Y, Dept. of CSE SPCE 20


Relational operators
 Used to compare the relationship between two operands
 Result of relational operator is either TRUE or FALSE.
 Two operands may be constants, variable or an expression.
Operators, Precedence & Associativity

Operation Operator Precedence Associativity

Lesser than < 1 L→R

Greater than > 1 L→R

.in
Lesser than or equal to <= 1 L→R

Greater than or equal to >= 1 L→R

Equal to

Not equal to
==

!=
ac 2

2
L→R

L→R
tu
.v

Program 6: To perform relational operations.


public class RelationalOperators {
w

public static void main(String args[]) {


int a = 10;
w

int b = 20;
System.out.println("a == b = " + (a == b) );
w

System.out.println("a != b = " + (a != b) );
System.out.println("a > b = " + (a > b) );
System.out.println("a < b = " + (a < b) );
System.out.println("b >= a = " + (b >= a) );
System.out.println("b <= a = " + (b <= a) );
}
}
Output:

Jagadeesh A Y, Dept. of CSE SPCE 21


Bitwise Operators
 The bitwise operator manipulates the data using bits.
 Manipulation of individual bit is carried out in a machine language.
 Java provides six bitwise operators.
 Bitwise operator works on int, short, long, byte, char type data.
Operators, Precedence & Associativity

Operation Operator Precedence Associativity

NOT ~ 1 L→R

Left Shift << 2 L→R

.in
Right Shift >> 2 L→R

Right Shift Zero

And
>>>

&
ac 2

3
L→R

L→R
tu
XOR ^ 4 L→R
.v

OR | 5 L→R

The result of bitwise AND is 1, when both bits are 1 otherwise result is 0.
w

 The result of bitwise OR is 0, when both bits are 0 otherwise result is 1.


w

 The result of bitwise exclusive OR is 1, when both bits are different.


 The result of bitwise exclusive OR is 0, when both bits are different.
w

The bitwise complement operator reverses the state of each bit


 If bit is ”1”, then complement operator reverses to ”0”.
 If bit is ”0”, then complement operator reverses to ”1”.
Truth Table
A B A&B A|B A^B ~A
0 0 0 0 1 1
0 1 0 1 0 1
1 0 0 1 0 0
1 1 1 1 1 0

Jagadeesh A Y, Dept. of CSE SPCE 22


Bitwise operator works on bits and performs bit-by-bit operation.
Assume if a = 60; and b = 13; now in binary format they will be as follows:
a = 0011 1100 a = 0011 1100 a = 0011 1100
b = 0000 1101 b = 0000 1101 b = 0000 1101 b = 0000 1101
----------------- ----------------- ----------------- -----------------
a&b = 0000 1100 a|b = 0011 1101 a^b = 0011 0001 ~b = 1111 0010
Left shift operator (<<)
 The left shift operator shifts data by a specified number of bit positions
towards left.
 Syntax: <variable><shift operator><nob>;
Where

.in
variable → int or char data type variable
shift operator → <<
nob → number of bits to be shifted
Example: int a = 64, b;
b = a << 1; Answer?
ac
tu
Right shift operator (>>)
 The right shift operator shifts data by a specified number of bit positions
.v

towards right.
 The shifted bits are filled by MSB.
w

 Syntax <variable><shift operator><nob>;


Where
w

variable → int or char data type variable


shift operator → >>
w

nob → number of bits to be shifted


Example: int a = 64, b;
b = a >> 1; Answer?
Unsigned Right shift operator (>>>)
 The right shift operator shifts data by a specified number of bit positions
towards right.
 The shifted bits are filled by Zero.
 Syntax: (variable) >>>(nob);

Jagadeesh A Y, Dept. of CSE SPCE 23


Where
variable → int or char data type variable
shift operator → >> >
nob → number of bits to be shifted
Example: int a = 64, b;
b = a << 1;
Program 7: To perform bitwise operations.
public class Bitwise {
public static void main(String args[]) {
int a = 60; /* 60 = 0011 1100 */
int b = 13; /* 13 = 0000 1101 */

.in
int c = 0;
c = a & b; /* 12 = 0000 1100 */

c = a | b; ac
System.out.println("a & b = " + c );
/* 61 = 0011 1101 */
System.out.println("a | b = " + c );
tu
c = a ^ b; /* 49 = 0011 0001 */
System.out.println("a ^ b = " + c );
.v

c = ~a; /*-61 = 1100 0011 */


System.out.println("~a = " + c );
w

c = a << 2; /* 240 = 1111 0000 */


System.out.println("a << 2 = " + c );
w

c = a >> 2; /* 215 = 1111 */


System.out.println("a >> 2 = " + c );
w

c = a >>> 2; /* 215 = 0000 1111 */


System.out.println("a >>> 2 = " + c );
}
}
Output:

Jagadeesh A Y, Dept. of CSE SPCE 24


Logical Operators
 Logical operators are used to combine two or more relational expressions.
 The result of logical operator should be either TRUE or FALSE.

A B A&&B A||B !A

FALSE FALSE FALSE FALSE TRUE

FALSE TRUE FALSE TRUE FALSE

TRUE FALSE FALSE TRUE FALSE

TRUE TRUE TRUE TRUE FALSE

.in
Program 8: To perform logical operations.
public class Logical_Operators {

ac
public static void main(String args[]) {
boolean a = true;
tu
boolean b = false;
System.out.println("a && b = " + (a&&b));
.v

System.out.println("a || b = " + (a||b) );


System.out.println("!(a && b) = " + !(a && b));
w

}
}
w

Output:
w

Logical Expressions
 An expression involving operands which are bind together with suitable
logical operators is called as logical operators.
 Example: (a > b && a > c), (a > b || a > c)
Assignment Operator
 The operator which is used to assign the data or result of an expression in to
a variable is called assignment operator.

Jagadeesh A Y, Dept. of CSE SPCE 25


 The assignment operator is =.
Example
1. x = 10; the value 10 is assigned to the variable x.
2. x = y+z; the value (y+z) is stored in the variable x.
Types of assignment expression
1. Simple assignment statement
Syntax: variable = expression;
where
expression → may be a constant or variable or expression.
= → assignment operator.

.in
Example: a = 40;
a = b + c;
2. Shorthand assignment operator


ac
It is a compact way of writing expressions in an assignment statement.
Syntax: <variable> <operator>= <expression>;
tu
where
variable → is a valid C identifier.
.v

operator → arithmetic or bitwise operator.


expression → constant or variable or expression
w

Example: a += 10; (which is nothing but a = a+10;)


x -= 2; (which is nothing but x = x-2;)
w

3. Multiple assignment statement


 Assigns same value to two or more variables in one statement.
w

 The multiple assignment operators are right associative.


 Example: i = j = k = 20;
The ? Operator
 It is called as conditional or ternary operator.
 It operates on three operands.
 The objective of conditional operator is to decide which value should be
assigned to variable.
 Syntax: variable = (expression) ? Value if true : Value if false;

Jagadeesh A Y, Dept. of CSE SPCE 26


Program 9: To evaluate ternary operator.
public class Ternary {
public static void main(String args[]){
int a , b;
a = 10;
b = (a == 1) ? 20: 30;
System.out.println( "Value of b is : " + b );
b = (a == 10) ? 20: 30;
System.out.println( "Value of b is : " + b );
}

.in
}
Operators Precedence

Operators

[]
Operation

Array Index
ac Priority Associativity
tu
() Method Call 1 L→R
.v

. Member Access

a++ Postfix Increment


w

a-- Prefix Decrement 2 R→L


w

~ Bitwise Negation
w

++a

--a

+ Unary Plus
3 R→L
- Unary Minus

! Logical NOT

new

Jagadeesh A Y, Dept. of CSE SPCE 27


() typecasting

* Multiplication

/ Division 4 L→R

% Remainder

Addition or String
+
Concatenation
5 L→R

- Subtraction

<< Left Shift

.in
>> Right Shift 6 L→R

>>>

<
Unsigned Right Shift

Lesser than ac
tu
<= Lesser than or equal to

> Greater than


7 L→R
.v

>= Greater than or equal


to
w

instance of Type comparison


w

== Is equal to
8 L→R
w

!= Not equal to

& Bitwise AND 9 L→R

^ Bitwise Exclusive OR 10 L→R

| Bitwise OR 11 L→R

&& Logical AND 12 L→R

|| Logical OR 13 L→R

Jagadeesh A Y, Dept. of CSE SPCE 28


?: Ternary or Conditional 14 R→L

== Assignment

15 R→L
*=, /=, %=, +=, -=, &=,
Short Assignment
^=, |=, <<=, >>=, >>>=

Type Casting
 The process of conversion of data type of an operand is called as type
conversion.
 For example, if operands in an expression are of different data types, then all
operands must be converted into single data type before evaluating an

.in
expression.
 There are two types of type conversion, namely
1. Implicit Conversion (Promotion or Widening)
2. Explicit Conversion (Narrowing)
Implicit Type Conversion

ac
The process of conversion of data from lower rank to higher rank
tu
automatically.
 Here, Automatic Type casting takes place when,
.v

 the two types are compatible


 the target type is larger than the source type
w

Program 10: To perform Implicit type conversion.


public class Explicit
w

{
public static void main(String[] args)
w

{
int i = 100;
long l = i; //no explicit type casting required
float f = l; //no explicit type casting required
System.out.println("Int value "+i);
System.out.println("Long value "+l);
System.out.println("Float value "+f);
}

Jagadeesh A Y, Dept. of CSE SPCE 29


}
Output:

Explicit type conversion


• The forcible conversion of data from one data type to another data type is known
as explicit conversion.
• Syntax: (data type)expression;
where
data type → required data type
expression → can be operand or variable or constant

.in
Program 11: To perform Explicit type conversion.
public class Implicit
{

ac
public static void main(String[] args)
{
tu
double d = 100.04;
long l = (long)d; //explicit type casting required
.v

int i = (int)l; //explicit type casting required


System.out.println("Double value "+d);
w

System.out.println("Long value "+l);


System.out.println("Int value "+i);
w

}
}
w

Control Statements
These statements control the flow of execution of the program based upon
conditions. Java supports two control statements, namely
1. if
2. switch
if statement
It is a conditional statement, which executes or skips set of instructions based upon
result of the evaluated condition.

Jagadeesh A Y, Dept. of CSE SPCE 30


Variants of if statement
1. Simple-if
2. if-else
3. nested if
4. else-if ladder
Simple if
 If condition evaluates to true, then simple or block statements are executed.
 If condition evaluates to false, then simple or block statements are skipped.
 It is also called as one way decision or selection statement.
Syntax:

.in
if( condition )
{
statement1;

}
statement2;
ac
tu
where
if -> is a keyword, must be written in lower case
condition -> logical expression results in either TRUE or FALSE
.v

statement -> simple or compound statement


w

Program 13: To implement simple if statement.


public class SimpleIf {
w

public static void main(String[] args) {


int a = 10, b=20;
w

if( a == 10 )
System.out.println("a equal to 10");
if( b == 20 )
System.out.println("b is equal to 20");
}
}
if-else
 It is called as two way selection.
 If condition evaluates to true, then statements belongs to if part are executed.

Jagadeesh A Y, Dept. of CSE SPCE 31


 If condition evaluates to false, then statements belongs to else part are
executed.
Syntax
if ( condition )
{
statement 1;
statement 2;
}
else
{
statement 3;

.in
statement 4;
}
Where

ac
if & else -> are keywords, must be written in lower case
condition -> a logical expression evaluates to either TRUE or FALSE
tu
statement 1 & 2 -> may be simple or compound statement, executed when
condition is TRUE
statement 3 & 4 -> may be simple or compound statement, executed when
.v

condition is FALSE
Program 14: To find smallest of two numbers.
w

public class SimpleIf {


public static void main(String[] args) {
w

int a = 10, b=20;


if( a < b )
w

System.out.println("a is lesser than b");


else
System.out.println("b is lesser than a");
}
}

Jagadeesh A Y, Dept. of CSE SPCE 32


Nested If
 Enclosing an if or if-else statement within another if or if-else statement is
called nested if statement.
 It is also called as multi-way decision or selection statement.
 In this case, nesting will takes place only in if part.
Syntax
if(condition1)
{
if(condition2)
{
statement1;

.in
}
else
{

}
ac
statement2;
tu
}
else
.v

{
statement3;
w

}
Program 15: To find largest of three numbers.
w

public class Nested_If {


public static void main(String[] args) {
w

int a = 10, b = 20, c = 30;


if( a > b )
{
if( a > c )
{
System.out.println("A is largest among B &
C\n");
}
}

Jagadeesh A Y, Dept. of CSE SPCE 33


if( b > a )
{
if( b > c )
{
System.out.println("B is largest among A &
C\n");
}
}
if( c > a )
{
if( c > b )

.in
{
System.out.println("C is largest among A &
B\n");

}
}
}
ac
tu
}
Output:
.v
w
w

else-if ladder
 Checks condition in else part.
w

 Nesting will takes place only in else part.


 It is also called as multi-way decision or selection statements.

Jagadeesh A Y, Dept. of CSE SPCE 34


Syntax
if( condition1 )
{
statement1;
}
else if( condition2 )
{
staement2;
}
else if( condition3 )
{

.in
staement3;
}
else
{
statement4;
ac
tu
}
where
.v

if & else -> are keywords, must be written in lower case


else if -> else and if are separate keywords, must provide space between
them.
w

statement -> may be a simple or compound statements executed depending


on the result of conditions.
w

Working of else-if ladder


w

 If the result of logical expression given in if is FALSE, control will enters into
else part.
 Checks one more conditions given in else if, if the result is TRUE then
executes immediately following simple or compound statements, then comes
out of entire else- if ladder.
 If none of the condition is TRUE, then statements in else part will be
executed.

Jagadeesh A Y, Dept. of CSE SPCE 35


Program 16: To classify people based on height.
import java.util.Scanner;
public class Else_If {
public static void main(String[] args) {
int ht;
Scanner in = new Scanner(System.in);
System.out.println("Enter height in cms:\n");
ht = in.nextInt();
if(ht < 165)
System.out.println("Dwarf\n");
else if(ht>165 && ht <175)

.in
System.out.println("Average\n");
else if(ht>175 && ht <180)

else if(ht>180 && ht <185)


ac
System.out.println("Normal\n");

System.out.println("Tall\n");
tu
else
System.out.println("Abnormal\n");
.v

}
}
w

Output:
w
w

Switch statement
 It is a conditional statement used to select one case depending upon the value
of expression.
 It is also called as multi-way decision or selection.

Jagadeesh A Y, Dept. of CSE SPCE 36


Syntax
switch(choice/expression)
{
case label1: block1;
break;
case label2: block2;
break;
-----------
-----------
default: default block;
break;

.in
}
where

ac
switch, case, break, default -> are keywords must be written in lower case
choice/expression -> must be integer or character, we can also give expression
and it should produce valid integer result.
tu
block-> may be simple or compound statements belongs to particular case.
In the above syntax,
.v

 Give integer or character or valid expression which yields integer result


within the parenthesis.
 Depending on the value of choice or expression a particular case label among
w

many alternatives will be selected.


 A simple or compound statement of selected case label will be executed.
w

 Each case must end with break statement.


w

 If break statement is not used, then subsequent cases will be executed till it
encounters break statement.
 After executing the break statement of particular case label, then control
comes out of the switch body.
 If the value of the choice or expression do not matches to any of the case
label, then the statements given in default will be executed.

Program 17: To simulate simple calculator using switch.


import java.util.Scanner;
public class Swithc_Calulator {

Jagadeesh A Y, Dept. of CSE SPCE 37


public static void main(String[] args) {
int choice = 0, a, b, res = 0;
Scanner in = new Scanner(System.in);
System.out.println("Enter Two Numbers\n");
a = in.nextInt();
b = in.nextInt();
System.out.println("1. Addition\n");
System.out.println("2. Subtraction\n");
System.out.println("3. Mulitplication\n");
System.out.println("4. Division\n");
System.out.println("5. Quit\n");

.in
System.out.println("Enter your choice\n");
choice = in.nextInt();
switch(choice)
{
ac
case 1: res = a + b;
tu
System.out.println("Addition of two numbers
is" +res +"\n");
break;
.v

case 2: res = a - b;
System.out.println("Subtraction of two
w

numbers is" +res +"\n");


break;
w

case 3: res = a * b;
System.out.println("Subtraction of two
w

numbers is" +res +"\n");


break;
case 4: if ( b == 0)
{
System.out.println("Run Time
Error:\nDivision Not Possible\n");
}
else
{

Jagadeesh A Y, Dept. of CSE SPCE 38


res = a * b;
System.out.println("Subtraction of two
numbers is" +res +"\n");
break;
}
default: System.out.println("Invalid Choice\n");
}
}
}
Iteration statements
These statements execute set of statements repeatedly until condition is met.

.in
Java's iterative statements are
1. for
2. while
3. do-while
while
ac
tu
 It repeatedly executes simple or block statement until condition is true.
Syntax
.v

while( expression )
{
w

statements;
}
w

where
while -> is a keyword must be written in lower case
w

statements -> may be simple or compound statement


expression -> is a logical expression that results in either TRUE or
FALSE
Program 18: To print numbers from 1 to 10.
public class While_Print_Numbers {
public static void main(String[] args) {
int n = 1;
while( n <= 10)
{

Jagadeesh A Y, Dept. of CSE SPCE 39


System.out.println(n);
n++;
}
}
}
do-while
 A do-while loop is similar to a while loop, but do-while loop is guaranteed to
execute at least one time.
Syntax
do
{

.in
statements;
}while( expression );
where

ac
do & while -> is a keyword must be written in lower case
statements -> may be simple or compound statement
tu
expression -> is a logical expression that results in either TRUE or FALSE
Program 19: To print numbers from 10 to 20 using do-while
.v

public class DoWhile {


public static void main(String args[]){
w

int x = 10;
do{
w

System.out.print("value of x : " + x );
x++;
w

System.out.print("\n");
}while( x < 20 );
}
}
for
 it is also called as counter-controlled loop / pre-test loop.
 It is a conditional control statement, executes a set of statement repeatedly
for known number of times.

Jagadeesh A Y, Dept. of CSE SPCE 40


Syntax
for( exp1(initialization); exp2(Boolean_Expression); exp3(Update) )
{
statements;
}

where
for -> is a keyword must be written in lower case
exp1 -> initializes the loop index before the loop begins
exp2 -> is a conditional expression that tests whether the loop index reached
the fixed value
exp3 -> modifies the loop index after every iteration or post condition

.in
statements -> may be a simple or a compound statement
Working of for loop
 First expression exp1 is evaluated. It is executed at the beginning of the for

 ac
loop, exp1 is evaluated only once in the for loop.
Then, exp2 is evaluated to TRUE or FALSE. If the result of exp2 is FALSE,
then control comes out of for loop.
tu
 If the result of exp2 is TRUE, then the body of the loop will be executed. After
executing the body of the loop control goes back to the exp3 is evaluated
followed by exp2.
.v

 Again exp2 is evaluated to TRUE or FALSE, and loop repeats till result of
exp2 becomes FALSE.
w

Program 20: To print numbers from 1 to 20 using for loop.


public class ForLoop {
w

public static void main(String args[]) {


for(int x = 1; x <= 20; x = x+1) {
w

System.out.print("value of x : " + x );
System.out.print("\n");
}
}
}
Output:

Jagadeesh A Y, Dept. of CSE SPCE 41


Enhanced for loop
 It is an enhanced for loop introduced in JAVA 5.5 version.
 In each iteration the element in the collection is retrieved & stored in the
iteration variable. Then loop is executed with that value.
 The loop repeats for all elements in the collection.
 Data type of loop variable must be same as data type of elements in
collection.
 Elements in an array are read in sequential order from beginning to ending.
Program 21: To print elements of array using enhanced for loop.
public class ForEach {
public static void main(String[] args) {

.in
int[] array1 = new int[] {5, 6, 7, 8, 9};

for(int x: array1)
{
ac
System.out.println(x);
tu
}
}
}
.v

Program 22: To print elements of two dimensional array using enhanced


for loop.
w

public class ForEachTwoDimensional {


public static void main(String[] args) {
w

int a[][] = new int[][] {


{1,2,3},
w

{4,5,6}
};
/* Printing Array Elements using nested for loop
for(int i = 0; i<2; i++)
for(int j = 0; j<3; j++)
System.out.println(a[i][j]);*/

/* Printing Array Element Using For Each*/

Jagadeesh A Y, Dept. of CSE SPCE 42


for(int x[]: a)
for(int y: x)
System.out.println(y);
}
}
Jump Statements
Jump statements are used to transfer control to other parts of the program.
Java supports three jump statements, namely
1. break
2. continue

.in
3. return
Break
 It can be used to terminate statements in switch.

 It can be used as a form of goto.
Program 23: To use break in for loop.
ac
It can be used to exit from loops like for, while, do-while.
tu
public class Break {
public static void main(String[] args) {
.v

for(int i = 1; ; i++)
{
w

if(i == 11)
break;
w

System.out.println(i);
w

}
}
}
Output:

Jagadeesh A Y, Dept. of CSE SPCE 43


Program 24: To use break in while loop.
public class BreakWhile {
public static void main(String[] args) {

int i = 1;
while(true)
{
if (i == 11)
break;
System.out.println(i);
i++;

.in
}
}
}
Output:
ac
tu
.v

Program 25: To use break as goto.


class BreakGoto
w

{
public static void main(String args[])
w

{
int i=10;
w

one:
{
two:
{
System.out.println("Statement before
break");
if(i==10)
{
break two;

Jagadeesh A Y, Dept. of CSE SPCE 44


}
System.out.println("This will not get
executed");
}
System.out.println("This is statement block of
label one");
}
}
}
Output:

.in
Continue
 It skips statements in an iteration and continues with the next iteration.

ac
It transfers control to the conditional statement.
Program 26: To print odd numbers from 1 to 10 using continue statement.
public class Continue {
tu
public static void main(String[] args) {
for(int i=1; i<=10; i++)
.v

{
if(i%2 == 0)
w

continue;
System.out.println(i);
w

}
}
w

Return statement
 It is used to transfer control from called function to calling function.
 It also terminates execution of program.
Program 27: To print numbers from 1 to 10 using return statement.
public class Return {
public static void main(String[] args) {

Jagadeesh A Y, Dept. of CSE SPCE 45


for(int i = 1; ; i++ )
{
if(i == 10)
return;
System.out.println(i);
}
}
}
Output:

.in
ac
tu
.v
w
w
w

Jagadeesh A Y, Dept. of CSE SPCE 46

Вам также может понравиться