SlideShare a Scribd company logo
DEFINATION :
●Java is an object-oriented
multithreaded programming language
developed by Sun Microsystems.
●Write Once Run Anywhere
●Java is a general-purpose, high-level
programming language.
Java Applications
●Stand-alone Applications
◦ Just like any programming language
●Applet
◦ Run under a Java-Enabled Browser
●Midlet
◦ Run in a Java-Enabled Mobile Phone
●Servlet
◦ Run on a Java-Enabled Web Server
Versions of Java
● Java Language vs Java Platform
◦ Current version of the language is 1.7
◦ Core language plus additional APIs is called the Java 2 platform
● Java 2 Micro Edition (J2ME)
◦ Very small Java environment for smart cards, pages, phones,
and set-top boxes
◦ Subset of the standard Java libraries aimed at limited size and
processing power
● Java 2 Standard Edition (J2SE)
◦ The basic platform, which this course will cover
● Java 2 Enterprise Edition (J2EE)
◦ For business applications, web services, mission-critical
systems
◦ Transaction processing, databases, distribution, replication
Use of JAVA Technology ….
●The Java technology is:
◦ A programming language
Java can create all kinds of applications
that you could create using any
conventional programming language.
◦ A development environment
As a development environment, Java
technology provides you with a large
suite of tools.
●An application environment
●Java technology applications are typically general-
purpose programs that run on any machine where
the Java runtime environment (JRE) is installed.
●A deployment environment
●The JRE supplied by the Java 2 Software
Development Kit (SDK) contains the complete set
of class files for all the Java technology packages,
which includes basic language classes, GUI
component classes, and so on.
●The other main deployment environment is on
your web browser. Most commercial browsers
supply a Java technology interpreter and runtime
environment.
Compiled & Interpreted
“Java Bytecode &
Java Virtual Machine (JVM)”
JAVA …Program … Run….
Java is Compiled and Interpreted
Text Editor Compiler Interpreter
Programmer
Source Code
.java file
Byte Code
.class file
Hardware and
Operating System
Notepad
javac
java
appletviewer
Java works in two stage
• Java compiler translate the
source code into byte code.
• Java interpreter converts the
byte code into machine level
representation.
Compiler
●Definition:- Acompiler is a program that reads a
program in one language, the source language and
translates into an equivalent program in another
language, the target language.
●The translation process should also report the
presence of errors in the source program
Source Program→ Compiler→Target Program
↓
Error Messages
●A compiler is a program that translates a source
program written in some high-level programming
language (such as Java) into machine code for some
computer architecture (such as the Intel Pentium
architecture).
Compiler
➢All language compilers translate source
code into machine code for a specific
computer.
➢Java compiler also does the same thing, but
it produces intermediate code, known as
bytecode.
➢Sun's Java compiler called javac.
Bytecode:
●Java byte code is a from of instruction that the java
special machine execute language ------that can be
understood by the Java Virtual Machine (JVM) .
●Each byte code instruction is one byte length &
hence there instruction are called as byte code. Java
support 256 byte code.
●Byte code are always platform independent .
●independent of any particular computer hardware, so
any computer with a Java interpreter can execute the
compiled Java program, no matter what type of
computer the program was compiled on
Java Virtual Machine (JVM)
Java program
(Source code)
Java compiler
(javac )
Java Virtual
machine
Java interpreter
(java)
Real machine
(machine code)
Java works in two stage
• Java compiler translate the
source code into byte code.
• Java interpreter converts the
byte code into machine level
representation.
Java Virtual Machine (JVM)
●A JVM is a set of computer programs that implement a
specific virtual machine model.
●A JVM accept byetcodes & converts it in the format which
is understood by the system.(which it is executed).
● JVM is exist only inside the computer memory.
●(A software "execution engine" that safely and compatibly
executes the byte codes in Java class files on a
microprocessor (whether in a computer or in another
electronic device)
●
Java Program Virtual Machine
Java Compiler
Bytecode
Fig. 1 : Process of Compilation
➢The output produce by the Java compiler is not executable code.
➢It is Bytecode, highly optimized set of instructions executed by java run
time system or JVM.
➢JVM is the interpreter for the bytecode.
➢The virtual machine code generated by the Java interpreter is not machine
specific code, but it is acts as an intermediate between the virtual machine and real
machine.
Machine code
Java Interpreter
Bytecode
Virtual machine Real machine
Fig. 2 : Process of converting bytecode into machine code
Java interpreter
●A module that alternately decodes and
executes every statement in some body of
code.
●The Java interpreter decodes and executes
bytecode for the Java virtual machine.
●The Java interpreter is actually a part of JVM.
Virtual machine is not just executing the
bytecodes, it has lot of tasks to do. That full-
fledged environment is referred to as a JVM.
Java Runtime Environment (JRE)
Definition: The Java Runtime Environment
(JRE) is a set of software tools for development of
Java applications. It combines the Java Virtual
Machine (JVM), platform core classes and supporting
libraries.
●JRE is part of the Java Development Kit (JDK), but
can be downloaded separately. JRE was originally
developed by Sun Microsystems. Also known as Java
runtime.
●JDK = JRE + development tools
Java Runtime Environment
IfJREis not installed on a computer, Java
programs may not be recognized by the
operating system and will not run.
●The JRE software provides runtime
environment in which Java programs can
be executed
●JRE software is available as both a
standalone environment and a Web
browser plug-in, which allows Java
applets to be run within a Web browser
JRE components:
The JRE is developed by Sun Microsystems (the
creator of Java) and includes the Java Virtual
Machine(JVM), code libraries, and components,
which are necessary to run programs written in
Java.
The JRE is available for multiple computer
platforms, including Mac, Windows, and Unix
Java Virtual Machine
●To execute a Java program, you run a program called a
bytecode interpreter, which in turn reads the bytecodes and
executes your Java program. The Java bytecode interpreter is
often also called the Java virtual machine or the Java runtime.
●The java bytecodes are a special set of machine
instructions that are not specific to any one processor or
computer system. A platform-specific bytecode interpreter
executes the Java bytecodes. The bytecode interpreter is also
called the Java virtual machine or the Java runtime
Interpreter.
Java Development Kit
●javac - The Java Compiler
●java -
●jdb-
The Java Interpreter
The Java Debugger
●appletviewer -Tool to run the applets
●javap - to print the Java bytecodes
●javaprof - Java profiler
●javadoc - documentation generator
●javah - creates C header files
Main API Packages
■java.lang COLUMN
■java.util
■java.io
■java.awt
■java.awt.image
■java.applet
■java.net
STRUCTURE OF JAVA
DOCUMENTATION SECTION
• The documentation section is an important section but
optional for a Java program. It includes basic information
about a Java program.
• The information includes the author's name, date of
creation, version, program name, company name, and
description of the program. It improves the readability of the
program.
The comments may be single-line, multi-line, and
documentation comments.
• Single-line Comment: It starts with a pair of forwarding slash
(//). For example:
//First Java Program
• Multi-line Comment: It starts with a /* and ends with */. We
write between these two symbols.
For example:
• /*It is an example of
multiline comment*/
• Documentation Comment: It starts with the delimiter (/**)
and ends with */.
For example:
• /**It is an example of documentation comment*/
PACKAGE DECLARATION
• The package declaration is optional. It is placed just after the
documentation section. In this section, we declare the
package name in which the class is placed.
• Note that there can be only one package statement in a Java
program.
• It must be defined before any class and interface declaration.
• Eg:package javatpoint; //where javatpoint is the package name
IMPORT STATEMENTS
• The package contains the many predefined classes and
interfaces. If we want to use any class of a particular
package, we need to import that class.
• The import statement represents the class stored in the
other package. We use the import keyword to import the
class.
• It is written before the class declaration and after the
package statement.
• Eg:import java.util.Scanner; // it imports the scanner class only
• import java.util.*; // it imports all class of java.util package
INTERFACE SECTION
• It is an optional section. We can create an interface in this section if
required.
• We use the interface keyword to create an interface. An interface is a
slightly different from the class.
• It contains only constants and method declarations.
• Eg: interface car
{
void start();
void stop();
}
CLASS DEFINITION
• In this section, we define the class.
• It is vital part of a Java program. Without the class, we cannot create
any Java program.
• A Java program may conation more than one class definition. We use
the class keyword to define the class.
• It contains information about user-defined methods, variables, and
constants. Every Java program has at least one class that contains the
main() method.
• Eg: class Student // class definition
{
}
Main Method Class
• We define the main() method. It is essential for all Java programs. Because
the execution of all Java programs starts from the main() method.
• In other words, it is an entry point of the class. It must be inside the class.
Inside the main method, we create objects and call the methods.
• Eg:
public class Student //class definition
{
public static void main(String args[])
{
//statements
}
}
First JAVA Program….
public class Hello
{
public static void main( String args[ ] )
{
//prints the string Welcome To JAVAProgramming! on
screen
System.out.println(“Welcome To JAVA
Programming!”);
}
}
Steps In Running JAVA Program
● Write the previous slide’s source code as your Java
program in the Text Editor or IDE.
◦ Save your Java Program with Filename:
Hello.java
● Compiling your program
◦ in your commandTerminal window we type in
the command:
javac [filename]
◦ So in this case, type in:
javac Hello.java
◦ During compilation, javac adds a file to the
disk called [filename].class, or in this case,
Hello.class, which is the actual bytecode.
Steps In Running JAVA Program
● Running the Program
◦ To run your Java program, type in the command:
java [filename without the extension]
◦ so in the case of our example, type in:
java Hello
◦ You can see on the screen after running the
program:
◦ " Welcome To JAV
AProgramming!"
Explanation ….
public class Hello
{
/*
My first Java program
*/
●indicates the name of the class which is Hello
●In Java, all code should be placed inside a class
declaration
●The class uses an access specifies public, which
indicates that our class in accessible to other classes
from other packages (packages are a collection of
classes).
●The next line which contains a curly brace { indicates
the start of a block.
Explanation …..
public class Hello
{
public static void main( String args[ ])
{
●indicates the name of one method in Hello
which is the main method.
●The main method is the starting point of a
Java program.
●All programs except Applets written in
Java start with the main method.
●Make sure to follow the exact signature.
Explanation …..
public class Hello
{
public static void main( String[] args )
{
//prints the string “Hello world” on screen
System.out.println(“Hello world”);
}
}
●The command System.out.println(), prints the text
enclosed by quotation on the screen.
●The last two lines which contains the two curly braces is
used to close the main method and class respectively.
Fundamental Programming structures in java
JAVA TOKENS
• In Java, the program contains classes and methods. Further, the
methods contain the expressions and statements required to perform
a specific operation.
• These statements and expressions are made up of tokens. In other
words, we can say that the expression and statement is a set of
tokens.
TYPES OF TOKENS
JAVA Keywords ….(50)
●Keywords are predefined identifiers reserved by
Java for a specific purpose.
●You cannot use keywords as names for your
variables, classes, methods ... etc.
IDENTIFIER
• Identifiers are used to name a variable, constant, function, class, and
array. It usually defined by the user.
• It uses letters, underscores, or a dollar sign as the first character.
• There are some rules to declare identifiers are:
• The first letter of an identifier must be a letter, underscore or a dollar
sign. It cannot start with digits but may contain digits.
• The whitespace cannot be included in the identifier.
• Identifiers are case sensitive.
Eg: int a;
int A; // it has different meaning
JAVALiterals …..
●Literals are tokens that do not change -
they are constant.
●The different types of literals in Java are:
◦ Integer Literals
◦ Floating-Point Literals
◦ Boolean Literals
◦ Character Literals
◦ String Literals
Integer Literals ….
●Integer literals come in different formats
●Special Notations in using integer literals
◦ decimal (base 10)
No special notation
Example : 12
◦ hexadecimal (base 16)
Precede by 0x or 0X
example: 0xC
◦ octal (base 8)
Precede by 0
Example : 014
Floating point and Boolean Literals
●Represents decimals with fractional parts
◦ Example: 3.1416
●Can be expressed in standard or scientific
notation
◦ Example: 583.45 (standard), 5.8345e2 (scientific)
●Boolean literals have only two values, true or
false.
Character and String Literals ….
● Character Literals represent single Unicode characters.
● Unicode character
●a 16-bit character set that replaces the 8-bitASCII character set.
●Unicode allows the inclusion of symbols and special characters from other
languages
● To use a character literal, enclose the character in single quote delimiter. For
example
●the letter a, is represented as ‘a’.
●special characters such as a newline character, a backslash is used followed
by the character code. For example, ‘n’for the newline
character, ‘r’for the carriage return, ‘b’for backspace.
● String literals represent multiple characters and are enclosed by double quotes.
●An example of a string literal is, “Hello JAVA”.
CONSTANTS
• Constants in java are fixed values those are not changed during the
Execution of program java supports several types of Constants those
are :
Integer Constants
• Integer Constants refers to a Sequence of digits which Includes only
negative or positive Values and many other things those are as
follows
• Example: Decimal Integer Constants
• Ocatal Integer Constants
• Hexadecimal Integer Constants
• Real Constants
• Integer numbers are unable to represent distance, height,
temperature, price, and so on. These informations are contaning
fractional parts or real parts like 56.890. Such numbers are called Real
or Floating Point Contants
• Example A Real Constant must have at Least one Digit
• it must have a Decimal value
• Single Character Constants
• A Character is Single Alphabet a single digit or a Single Symbol that is
enclosed within Single inverted commas.
• Character Constant Can hold Single character at a time.
• String Constants
• String is a Sequence of Characters Enclosed between double Quotes
These Characters may be digits, Alphabets Like "Hello", "1234" etc.
• The string is "Sequence of Characters".
• String Constant is written in Pair of Double Quotes.
• The string is declared as Array of Characters.
Variable ….
●Avariable has a:
●data type
●The data type indicates the type of value that the
variable can hold.
●name
●The variable name must follow rules for
identifiers.
●Declare a variable as follows:
●<data type> <name> [=initial value];
●●Note: Values enclosed in <> are required
values, while
●those values in [ ] are optional.
Variable Declaration ….
public class VariableSamples {
public static void main( String[] args ){
//declare a data type with variable name
// result and boolean data type
boolean result;
//declare a data type with variable name
// option and char data type
char option= 'C';
//assign 'C' to option
//declare a data type with variable name
//grade, double data type and initialized
//to 0.0
double grade = 0.0;
}
}
Variable Types ….
● Two types of variables in Java:
● – Primitive Variables
● – Reference Variables
● Primitive Variables
● – variables with primitive data types such as int,long,char,float,double.
● – A primitive data type is a built-in data type that is a basic building block
for all other types and DO NOT create objects.
–byte, short, int, long are all integer data types. float and double are floating-
point
(decimal) data types.
● Reference Variables
● – variables that stores the address in the memory location
● – points to another memory location where the actual data is
● – When you declare a variable of a certain class, you are actually
declaring a reference variable to the object with that certain class.
● Suppose we have two variables with data types int and String.
● int num = 10; // primitive type
● String name = "Hello"; // reference type
Data Types ….
●The Java programming language defines
eight primitive data types.
◦ boolean (for logical)
◦ char (for textual)
◦ byte
◦ short
◦ int
◦ long (integral)
◦ double
◦ float (floating point).
Integral Data Types ….
●Integral data types in Java uses three forms
– decimal, octal or hexadecimal.
◦ Examples are,
2 //The decimal value 2
077 //The leading 0 indicates an octal value
0xBACC //The leading 0x indicates a hex value
●Integral types has int as default data type.
●You can define its long value by appending
the letter l or L. For example:
◦ 10L
Intregal Data Types ….
●Integral data type have the following ranges:
Length Data Type Range
8 bits/
1 byte
byte -128 to +127
16 bits/ 2
byte
short -32768 to+32767
32 bits/
4 byte
int -2147483648 to +2147483647
64 bits/
8byte
long -9223372036854775808 to
+9223372036854775807
Floating point Types ….
●Floating point types has double as default data
type.
●Floating-point literal includes either a decimal
point or one of the following,
●E or e //(add exponential value)
●F or f //(float)
●D or d //(double)
●Examples are,
●3.14 //A simple floating-point value (a double)
●6.02E23 //A large floating-point value
●2.718F //A simple float size value
●123.4E+306D//A large double value with redundant
D
Floating point Data Types ….
●Floating-point data types have the following
ranges
Length Data Type Range
32 bits/
4byte
float -3.4e38 to
3.4e038
64 bits/
8byte
double -1.7e308 to
1.7e308
Boolean Data Type ….
●A boolean data type represents two states:
true and false.
●An example is,
◦ boolean result = true;
●The example shown above, declares a
variable named
◦ result as boolean type and assigns it a value of
true.
Character Data Type ….
●A character data type (char), represents a
single Unicode character.
●It must have its literal enclosed in single
quotes(’ ’). For example,
●‘a’ //The letter a
●‘t’ //A tab
●To represent special characters like ' (single
quotes) or " (double quotes), use the escape
character . For Example,
●''' //for single quotes
●'"' //for double quotes
String as Reference Type ….
●Although, String is not a primitive data type
(it is a Class)
●A String represents a data type that
contains multiple characters. It is not a
primitive data type, it is a class.
●It has its literal enclosed in double
quotes(“”). For example,
◦ String message =“Hello JAVA!”;
◦ String creator = new String(“James A. Gosline”);
Operators ….
●Different types of operators:
◦ Arithmetic operators
◦ Unary operators.
◦ Increment & decrement operators
◦ Relational operators
◦ Logical operators
◦ Assignment operators
◦ Ternary/conditional operators
◦ Bitwise operator
●These operators follow a certain kind of
precedence so that the compiler will know
which operator to evaluate first in case
multiple operators are used in one statement.
Ki
inds of
f Operator
Operator Description
+ Addition
- subtraction
* multiplication
/ division
% remainder after integer division
Arithmetic Operators ….
Operator Use Description
+ op1 + op2 Adds op1 with op2
- op1 - op2 Substract op1 with op2
* op1 * op2 Multiply op1 with op2
/ op1 / op2 Divide op1 with op2
% op1 % op2 Remainder of divide op1 by
op2
Types of Arithmetic Operator
●Integer type Arithmetic :
Both integer
●Real Arithmetic
Both float
●Mix mode Arithmetic
integer / float =float
25/10.0=2.5
/* Program to demonstrate the addition and subtraction
of double numbers*/
class AddSubDoubles
{ public static void main (String args[])
{
double x = 7.5;
double y = 5.4;
System.out.println("x is : " + x);
System.out.println("y is : " + y);
double z = x + y;
System.out.println("x + y is : " + z);
z = x - y;
System.out.println("x - y is : " + z);
}
}
Unary Operator …
●Example :
●-743 -0x7fff -0.2
-E-8
-(x + y)
●-root 1
-3*(x + y)
Unary Operator …
●Unary numeric promotion is applied to the single
operand of the unary arithmetic operators - and +.
◦ When a unary arithmetic operator is applied to an
operand whose type is narrower than int, the operandis
promoted to a value of type int, with the operation
resulting in an int value.
●Binary numeric promotion for operands of binary
operators implies that each operand of a binary
operator is promoted to type int or a broader
numeric type
Increment & Decrement
Opeartor
Operator Use Description
++ ++op Increment op by 1 evaluates to the value of
op after it was incremented
++ op++ Increment op by 1 evaluates to the value of
op before it was incremented
-- --op Decrement op by 1 evaluates to the value of
op after it was decremented
-- op-- Decrement op by 1 evaluates to the value of
op before it was decremented
Prof.Deepak Gaikar
Operator Representation
Pre-increment + + i
Post increment i + +
Pre decrement -- i
Post decrement i - -
The SYNTAX of these operators is given
below:
++<variable name >
<variable name>++
--<variable name>
<variable name>--
syntax:
variable = expression
example: a =3 , x=y
also java contains the following 5 additional assignment operator
(+ =, - =,* =, % =)
syntax:
expression1+= expression2
is equivalent to:
expression1=expression1+expression2
simllarly, the assignment expression
expression 1 -= expression2
is equivalent to:
expression1=expression1-expression
Assignment operator
Operator Expression Result
i + = 3 i = i + 3 i = 18
i - = 2 i = i – 2 i = 13
i * = 4 i = i * 4 i = 60
i / = 3 i = i / 3 i = 5
i % = 4 i = i % 4 i = 3
Precedence Associativity of Increment/Decrement Operators:
Prof.Deepak Gaikar
Operator Associativity
Icrement/Decrements Right to Left
Arithmetic Left to right
ASSIGNMENT Right to Left
Precedence Associativity of Increment/Decrement Operators
Operator operations Associativity
- , + Unary minus Right to Left
++
--
Increment
Decrement Right to Left
*
/
%
Multiplication
Division
Modulus
Left to Right
+
-
Addition
Subtraction
Left to Right
= Assignment Right to Left
Relational Opeartor ….
● Relational operators compare two values and determines the
relationship between those values.
● The output of evaluation are the Boolean values true or false.
Operator Use Description
> op1 > op2 op1 is greater than op2
>= op1 >= op2 op1 is greater than or equals to op2
< op1 < op2 op1 is less than op2
<= op1 <= op2 op1 is less than or equals to op2
== op1 == op2 op1 is equals to op2
!= op1 != op2 op1 is not equals to op2
Compare two value Result : true or false
relational operator …use for, while, ...Operator
∈, ∈=, >, >=, ==, !=
Higher precedence lower precedence
/* Program to demonstrate Relational Operators */
class RelationalOp
{
public static void main(String args[])
{
float x = 15.0F, y = 10.65F, z = 25.0F;
System.out.println("x = "+x);
System.out.println("y = "+y);
System.out.println("z = "+z);
System.out.println("x < y is : "+(x<y));
System.out.println("x > y is : "+(x>y));
System.out.println("x == z is : "+(x==z));
System.out.println("x <= z is : "+(x<=z));
System.out.println("x >= y is : "+(x>=y));
System.out.println("y != z is : "+(y!=z));
System.out.println("y == x+z is : "+(y==x+z));
} }
Logical Operator ….
●Logical operators have one or two boolean
operands that yield a boolean result. There
are six logical operators:
◦ && (logical AND)
◦ & (boolean logical AND)
◦ || (logical OR)
◦ | (boolean logical inclusive OR)
◦ ^ (boolean logical exclusive OR)
◦ ! (logical NOT)
Operand Usage
&& Logical AND. Returns 1 if both the expressions are non-zero.
|| Logical OR. Returns 1 if either of the expression is non-zero.
! Unary negation. It converts a non-zero operand into 0 and a zero operand
into 1.
Expr1 Expr2 Expr1 && Expr2 Expr1 || Expr2
0 0 0 0
0 non-zero 0 1
non-zero 0 0 1
non-zero non-zero 1 1
&& (short-circuit AND)and &
Operator
●Here is the truth table for && and &,
Prof.Deepak Gaikar
X1 X2 Result
TRUE TRUE TRUE
TRUE FALSE FALSE
FALSE FALSE FALSE
FALSE TRUE FALSE
●The basic difference between && and & operators :
● && supports short-circuit evaluations (or partial evaluations), while &
doesn't.
● Given an
expression: exp1
&& exp2
● && will evaluate the expression exp1, and immediately return a false
value is exp1 is false.
● If exp1 is false, the operator never evaluates exp2 because the result of
the operator will be false regardless of the value of exp2.
● In contrast, the & operator always evaluates both exp1 and exp2 before
returning an answer.
|| OR Operators
●Here is the truth table for || and |,
Prof.Deepak Gaikar
●The basic difference between || and | operators :
● || supports short-circuit evaluations (or partial evaluations), while |
doesn't.
● Given an expression:
● exp1 || exp2
● || will evaluate the expression exp1, and immediately return a true value
is exp1 is true
● If exp1 is true, the operator never evaluates exp2 because the result of
the operator will be true regardless of the value of exp2.
● In contrast, the | operator always evaluates both exp1 and exp2 before
returning an answer.
X1 X2 Result
TRUE TRUE TRUE
TRUE FALSE TRUE
FALSE FALSE FALSE
FALSE TRUE TRUE
^ Logical XOR(Exclusive) Operator
….
●Here is the truth table for ^,
●The result of exclusive or operation is TRUE, if and
only if one operand is true and the other is false.
X1 X2 Result
TRUE TRUE FALSE
TRUE FALSE TRUE
FALSE FALSE FALSE
FALSE TRUE TRUE
! Operator ….
●The logical NOT takes in one argument,
wherein that argument can be an
expression, variable or constant.
●Here is the truth table for !,
X Result
TRUE FALSE
FALSE TRUE
/* Program to demonstrate the boolean logical operators */
class BoolLogic
{
public static void main(String args[])
{ boolean a = true;
boolean b = false;
boolean c = a|b;
boolean d = a&b;
boolean e = a^b;
boolean f = (!a & b)|(a & !b);
boolean g = !a;
System.out.println("
System.out.println("
System.out.println("
System.out.println("
System.out.println("
a = "+a);
b = "+b);
a|b = "+c);
a&b = "+d);
a^b = "+e);
}
System.out.println(" !a&b|a&!b = "+f);
System.out.println(" !a = "+g);
}
Conditional Opeartor ….
●The conditional operator ?:
◦ is a ternary operator.
●This means that it takes in three arguments
that together form a conditional expression.
◦ The structure of an expression using a
conditional operator is
exp1?exp2:exp3
◦ exp1 - is a boolean expression whose result
must either be true or false
◦ Result:
If exp1 is true, exp2 is the value returned.
If it is false, then exp3 is returned.
BITWISE Operator
Operator Meaning
& BITWISE AND
| BITWISE OR
^ BITWISE XOR(EXCLUSIVE OR)
~ One’s complement
>> Right SHIFT
<< LEFT SHIFT
>>> SHIFT righit zero fill assiggnment
Operator Precedence ….
Prof.Deepak Gaikar
Operator operations Associatively
.
( )
[ ]
Access object member
Function call
Access Array element
Left to Right
- Unary minus
++ Increment
-- Decrement
! Logical negation
~ Ones complement (bitwise
Not )
Right to Left
(data type)
new
Casting
Object creation Right to Left
* Multiplication
/ Division
% Modulus
+ Addition
- Subtraction
Left to Right
+ String concatenation Left to Right
>> Right SHIFT
<< LEFT SHIFT Left to Right
>>> SHIFT righit zero fill
assiggnment
<
<=
>
>=
Instanceof
Less than
Less than or equals to Left to Right
Greater than
Greater than or equals to
= =
!=
Equality
Not equal
Left to Right
&
^
|
&&
||
?:
BITWISE AND
BITWISE XOR(EXCLUSIVE OR)
BITWISE OR
Logical AND
Logical OR.
Conditional Operator
Left to Right
Left to Right
Left to Right
Left to Right
= , +=,-=, *= ,
/=, %= , &= ,
^= ,|= , <<= ,
Assignment &
Compound assignment operator
Right to Left
>>= , >>>
Objectives ….
●Use decision control structures (if, else,
switch) which allows selection of specific
sections of code to be executed
●Use repetition control structures (while,
do-while, for) which allow executing
specific sections of code a number of
times
●Use branching statements (break,
continue, return) which allows redirection
of program flow
●Control structures
◦ allows us to change the ordering of how the
statements in our programs are executed
●Two types of Control Structures
◦ decision control structures
allows us to select specific sections of code to be
executed
◦ repetition control structures
allows us to execute specific sections of the code
a number of times
if Statement ….
●if-statement
◦ specifies that a statement (or block of code) will be
executed if and only if a certain boolean statement is
true.
◦ if-statement has the form:
if( boolean_expression )
statement;
◦ or if-statement with block
if( boolean_expression )
{
statement1;
statement2;
}
◦ where, boolean_expression is either a boolean
expression or boolean variable.
Boolean Expression ….
●The boolean_expression part of a
statement should
◦ evaluate to a boolean value. That means that
the execution of the condition should either
result to a value of true or a false.
●Indent the statements inside the if-block.
For example,
if( boolean_expression ){
//statement1;
//statement2;
}
● if-else statement
◦ used when we want to execute a certain statement if a
condition is true, and a different statement if the condition is
false.
● if-else statement has the form:
if( boolean_expression )
{
statement1;
statement2; }
else
{
statement3;
statement4; }
●Nested if-else statement
●if-else Ladder
Switch Statement ….
◦ allows branching on multiple outcomes.
◦ switch statement has the form:
switch( switch_expression )
{
case case_selector1:
statement1;//
statement2;//block 1
break;
case case_selector2:
statement1;//
statement2;//block 2
break;
default:
statement1;//
statement2;//block n
} Prof.Deepak Gaikar
Switch Case Expression ….
● where,
◦ switch_expression
is an integer or character expression
◦ case_selector1, case_selector2 and so on,
are unique integer or character constants.
● When a switch is encountered,
◦ Java first evaluates the switch_expression, and jumps to the case
whose selector matches the value of the expression.
◦ The program executes the statements in order from that point on
until a break statement is encountered, skipping then to the first
statement after the end of the switch structure.
◦ If none of the cases are satisfied, the default block is executed.
Take note however, that the default part is optional.
Repeatation Control Structures
….
●Repetation control structures
◦ are Java statements that allows us to
execute specific blocks of code a number
of times.
●Types:
◦ while-loop
◦ do-while loop
◦ for-loop
While Loop Statement ….
● while loop
◦ is a statement or block of statements that is
repeated as long as some condition is satisfied.
● while loop has the form:
while( boolean_expression )
{
statement1;
statement2;
}
◦ The statements inside the while loop are executed
as long as the boolean_expression evaluates to
true.
Do While Loop Statement ….
● do-while loop
◦ is similar to the while-loop
◦ statements inside a do-while loop are executed several
times as long as the condition is satisfied
◦ The main difference between a while and do-while loop:
the statements inside a do-while loop are executed at
least once.
● do-while loop has the form:
Do
{
statement1;
statement2;
}while( boolean_expression ); Prof.Deepak Gaikar
For Loop Statement ….
● for loop
◦ allows execution of the same code a number of times.
◦ for loop has the form:
for(InitializationExpression;LoopCondition;StepExpression)
{
statement1;
statement2;
. . .
}
◦ where,
InitializationExpression -initializes the loop variable.
LoopCondition - compares the loop variable to some limit
value.
StepExpression - updates the loop variable.22
Branching Statement ….
● Branching statements allows us to redirect the flow of program
execution.
● Java offers three branching statements:
◦ break
◦ continue
◦ return.
● unlabeled break
◦ terminates the enclosing switch statement, and flow of
control transfers to the statement immediately following the
switch.
◦ This can also be used to terminate a for, while, or do-while
loop
Labeled Break Statement ….
●labeled break statement
◦ terminates an outer statement, which is
identified by the label specified in the break
statement.
◦ the flow of control transfers to the
statement immediately following the
labeled (terminated) statement.
◦ The sample program in the next slide
searches for a value in a two dimensional
array. Two nested for loops traverse the
array. When the value is found, a labeled
break terminates the statement labeled
search, which is the outer forPlro
o
f.D
o
ee
p
pa
.k Gaikar
Example ….
int[][] numbers = {{1, 2, 3}, {4, 5, 6},{7, 8, 9}};
int searchNum = 5;
boolean foundNum = false;
searchLabel:
for( int i=0; i<numbers.length; i++ ){
for( int j=0; j<numbers[i].length; j++ ){
if( searchNum == numbers[i][j] ){
foundNum = true;
break searchLabel;
}
}
}
if( foundNum )
System.out.println(searchNum + " found!" );
else
System.out.println(searchNum + " not found!");Prof.Deepak Gaikar
Continue Statement ….
●unlabeled continue statement
◦ skips to the end of the innermost loop's body
and evaluates the boolean expression that
controls the loop, basically skipping the
remainder of this iteration of the loop.
●labeled continue statement
◦ skips the current iteration of an outer loop
marked with the given label.
Return Statement ….
● return statement
◦ used to exit from the current method.
◦ flow of control returns to the statement that follows the
original method call.
● To return a value
◦ simply put the value (or an expression that calculates the
value) after the return keyword. For example,
return ++count;
◦ or
return "Hello";
◦ The data type of the value returned by return must match
the type of the method's declared return value.
◦ When a method is declared void, use the form of return
that doesn't return a value. – For example,
return;
//Write a program to display the following pattern
1
01
101
0101
10101
import java.io.*;
class Pattern
{
public static void main(String args[])
{
int i,j,n,k;
Scanner br=new
System.out.print("Enter number of lines:");
n=br.nextInt());
for(i=1;i<=n;i++)
{
for(j=0;j<=i-1;j++)
{
System.out.print((i+j)%2 + " ");
}
System.out.println();
} }}
//Write a program to determine the sum of the series
1-1/2+1/3+1/4+…….+1/n
import java.util.*;
class Sum{
public static void main(String args[])
{
int i,n,sign=1;
float sum=0;
Scanner br=new Scanner(System.in));
System.out.print("Enter value of n:");
n=br.nextInt();
for(i=1;i<=n;i++)
{
sum=sum+1.0f/i*sign;
sign=sign*-1;
}
System.out.println("Sum=" + sum);
}
}
//Write a program to determine the sum of the series
1+1/2!+1/3!+1/4!+…….+1/n!
import java.util.*;
class Sum
{
public static void main(String args[])
{
int i,n,fact=1;
float sum=0;
Scanner br=new Scanner(System.in);
System.out.print("Enter the value of n:");
n=br.nextInt();
for(i=1;i<=n;i++)
{
fact=fact*i;
sum=sum+1.0f/fact;
}
System.out.println("Sum=" + sum);
}}
/*output*******
Enter the value of n:3
sum=1.66666666 */

More Related Content

Similar to java intro.pptx

What is-java
What is-javaWhat is-java
What is-java
Shahid Rasheed
 
Java & J2EE Struts with Hibernate Framework
Java & J2EE Struts with Hibernate FrameworkJava & J2EE Struts with Hibernate Framework
Java & J2EE Struts with Hibernate Framework
Mohit Belwal
 
J2ee strutswithhibernate-140121221332-phpapp01
J2ee strutswithhibernate-140121221332-phpapp01J2ee strutswithhibernate-140121221332-phpapp01
J2ee strutswithhibernate-140121221332-phpapp01
Jay Palit
 
JAVA ALL 5 MODULE NOTES.pptx
JAVA ALL 5 MODULE NOTES.pptxJAVA ALL 5 MODULE NOTES.pptx
JAVA ALL 5 MODULE NOTES.pptx
DrPreethiD1
 
JAVA PROGRAM CONSTRUCTS OR LANGUAGE BASICS.pptx
JAVA PROGRAM CONSTRUCTS OR LANGUAGE BASICS.pptxJAVA PROGRAM CONSTRUCTS OR LANGUAGE BASICS.pptx
JAVA PROGRAM CONSTRUCTS OR LANGUAGE BASICS.pptx
AALIM MUHAMMED SALEGH COLLEGE OF ENGINEERING
 
Java chapter 1 basic introduction Unit-1.pptx
Java chapter  1 basic introduction Unit-1.pptxJava chapter  1 basic introduction Unit-1.pptx
Java chapter 1 basic introduction Unit-1.pptx
noosdysharma
 
Java unit 1
Java unit 1Java unit 1
Java unit 1
Shipra Swati
 
Java introduction
Java introductionJava introduction
Java introduction
logeswarisaravanan
 
Notes of java first unit
Notes of java first unitNotes of java first unit
Notes of java first unit
gowher172236
 
Java ms harsha
Java ms harshaJava ms harsha
Java ms harsha
Harsha Batra
 
Java chapter 1
Java   chapter 1Java   chapter 1
Java chapter 1
Mukesh Tekwani
 
unit1.pptx
unit1.pptxunit1.pptx
unit1.pptx
PrasadKalal4
 
Core Java Programming Language (JSE) : Chapter I - Getting Started
Core Java Programming Language (JSE) : Chapter I - Getting StartedCore Java Programming Language (JSE) : Chapter I - Getting Started
Core Java Programming Language (JSE) : Chapter I - Getting Started
WebStackAcademy
 
JAVA Program Examples
JAVA Program ExamplesJAVA Program Examples
JAVA Program Examples
Prof Chethan Raj C
 
JAVAPart1_BasicIntroduction.pptx
JAVAPart1_BasicIntroduction.pptxJAVAPart1_BasicIntroduction.pptx
JAVAPart1_BasicIntroduction.pptx
Murugesh33
 
JAVA_Day1_BasicIntroduction.pptx
JAVA_Day1_BasicIntroduction.pptxJAVA_Day1_BasicIntroduction.pptx
JAVA_Day1_BasicIntroduction.pptx
Murugesh33
 
Introduction to java programming tutorial
Introduction to java programming   tutorialIntroduction to java programming   tutorial
Introduction to java programming tutorial
jackschitze
 
1 java introduction
1 java introduction1 java introduction
1 java introduction
abdullah al mahamud rosi
 
1 java intro
1 java intro1 java intro

Similar to java intro.pptx (20)

What is-java
What is-javaWhat is-java
What is-java
 
Java & J2EE Struts with Hibernate Framework
Java & J2EE Struts with Hibernate FrameworkJava & J2EE Struts with Hibernate Framework
Java & J2EE Struts with Hibernate Framework
 
J2ee strutswithhibernate-140121221332-phpapp01
J2ee strutswithhibernate-140121221332-phpapp01J2ee strutswithhibernate-140121221332-phpapp01
J2ee strutswithhibernate-140121221332-phpapp01
 
JAVA ALL 5 MODULE NOTES.pptx
JAVA ALL 5 MODULE NOTES.pptxJAVA ALL 5 MODULE NOTES.pptx
JAVA ALL 5 MODULE NOTES.pptx
 
JAVA PROGRAM CONSTRUCTS OR LANGUAGE BASICS.pptx
JAVA PROGRAM CONSTRUCTS OR LANGUAGE BASICS.pptxJAVA PROGRAM CONSTRUCTS OR LANGUAGE BASICS.pptx
JAVA PROGRAM CONSTRUCTS OR LANGUAGE BASICS.pptx
 
Java chapter 1 basic introduction Unit-1.pptx
Java chapter  1 basic introduction Unit-1.pptxJava chapter  1 basic introduction Unit-1.pptx
Java chapter 1 basic introduction Unit-1.pptx
 
Java unit 1
Java unit 1Java unit 1
Java unit 1
 
Java introduction
Java introductionJava introduction
Java introduction
 
Notes of java first unit
Notes of java first unitNotes of java first unit
Notes of java first unit
 
Java ms harsha
Java ms harshaJava ms harsha
Java ms harsha
 
Java chapter 1
Java   chapter 1Java   chapter 1
Java chapter 1
 
unit1.pptx
unit1.pptxunit1.pptx
unit1.pptx
 
Core Java Programming Language (JSE) : Chapter I - Getting Started
Core Java Programming Language (JSE) : Chapter I - Getting StartedCore Java Programming Language (JSE) : Chapter I - Getting Started
Core Java Programming Language (JSE) : Chapter I - Getting Started
 
OOPS JAVA.pdf
OOPS JAVA.pdfOOPS JAVA.pdf
OOPS JAVA.pdf
 
JAVA Program Examples
JAVA Program ExamplesJAVA Program Examples
JAVA Program Examples
 
JAVAPart1_BasicIntroduction.pptx
JAVAPart1_BasicIntroduction.pptxJAVAPart1_BasicIntroduction.pptx
JAVAPart1_BasicIntroduction.pptx
 
JAVA_Day1_BasicIntroduction.pptx
JAVA_Day1_BasicIntroduction.pptxJAVA_Day1_BasicIntroduction.pptx
JAVA_Day1_BasicIntroduction.pptx
 
Introduction to java programming tutorial
Introduction to java programming   tutorialIntroduction to java programming   tutorial
Introduction to java programming tutorial
 
1 java introduction
1 java introduction1 java introduction
1 java introduction
 
1 java intro
1 java intro1 java intro
1 java intro
 

Recently uploaded

RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
thanhdowork
 
Water Industry Process Automation and Control Monthly - May 2024.pdf
Water Industry Process Automation and Control Monthly - May 2024.pdfWater Industry Process Automation and Control Monthly - May 2024.pdf
Water Industry Process Automation and Control Monthly - May 2024.pdf
Water Industry Process Automation & Control
 
Standard Reomte Control Interface - Neometrix
Standard Reomte Control Interface - NeometrixStandard Reomte Control Interface - Neometrix
Standard Reomte Control Interface - Neometrix
Neometrix_Engineering_Pvt_Ltd
 
WATER CRISIS and its solutions-pptx 1234
WATER CRISIS and its solutions-pptx 1234WATER CRISIS and its solutions-pptx 1234
WATER CRISIS and its solutions-pptx 1234
AafreenAbuthahir2
 
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
AJAYKUMARPUND1
 
space technology lecture notes on satellite
space technology lecture notes on satellitespace technology lecture notes on satellite
space technology lecture notes on satellite
ongomchris
 
MCQ Soil mechanics questions (Soil shear strength).pdf
MCQ Soil mechanics questions (Soil shear strength).pdfMCQ Soil mechanics questions (Soil shear strength).pdf
MCQ Soil mechanics questions (Soil shear strength).pdf
Osamah Alsalih
 
Nuclear Power Economics and Structuring 2024
Nuclear Power Economics and Structuring 2024Nuclear Power Economics and Structuring 2024
Nuclear Power Economics and Structuring 2024
Massimo Talia
 
一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理
一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理
一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理
zwunae
 
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdfTop 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
Teleport Manpower Consultant
 
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&BDesign and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Sreedhar Chowdam
 
Fundamentals of Electric Drives and its applications.pptx
Fundamentals of Electric Drives and its applications.pptxFundamentals of Electric Drives and its applications.pptx
Fundamentals of Electric Drives and its applications.pptx
manasideore6
 
Student information management system project report ii.pdf
Student information management system project report ii.pdfStudent information management system project report ii.pdf
Student information management system project report ii.pdf
Kamal Acharya
 
Cosmetic shop management system project report.pdf
Cosmetic shop management system project report.pdfCosmetic shop management system project report.pdf
Cosmetic shop management system project report.pdf
Kamal Acharya
 
HYDROPOWER - Hydroelectric power generation
HYDROPOWER - Hydroelectric power generationHYDROPOWER - Hydroelectric power generation
HYDROPOWER - Hydroelectric power generation
Robbie Edward Sayers
 
power quality voltage fluctuation UNIT - I.pptx
power quality voltage fluctuation UNIT - I.pptxpower quality voltage fluctuation UNIT - I.pptx
power quality voltage fluctuation UNIT - I.pptx
ViniHema
 
CFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptx
CFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptxCFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptx
CFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptx
R&R Consult
 
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdfAKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
SamSarthak3
 
The role of big data in decision making.
The role of big data in decision making.The role of big data in decision making.
The role of big data in decision making.
ankuprajapati0525
 
Final project report on grocery store management system..pdf
Final project report on grocery store management system..pdfFinal project report on grocery store management system..pdf
Final project report on grocery store management system..pdf
Kamal Acharya
 

Recently uploaded (20)

RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
 
Water Industry Process Automation and Control Monthly - May 2024.pdf
Water Industry Process Automation and Control Monthly - May 2024.pdfWater Industry Process Automation and Control Monthly - May 2024.pdf
Water Industry Process Automation and Control Monthly - May 2024.pdf
 
Standard Reomte Control Interface - Neometrix
Standard Reomte Control Interface - NeometrixStandard Reomte Control Interface - Neometrix
Standard Reomte Control Interface - Neometrix
 
WATER CRISIS and its solutions-pptx 1234
WATER CRISIS and its solutions-pptx 1234WATER CRISIS and its solutions-pptx 1234
WATER CRISIS and its solutions-pptx 1234
 
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
 
space technology lecture notes on satellite
space technology lecture notes on satellitespace technology lecture notes on satellite
space technology lecture notes on satellite
 
MCQ Soil mechanics questions (Soil shear strength).pdf
MCQ Soil mechanics questions (Soil shear strength).pdfMCQ Soil mechanics questions (Soil shear strength).pdf
MCQ Soil mechanics questions (Soil shear strength).pdf
 
Nuclear Power Economics and Structuring 2024
Nuclear Power Economics and Structuring 2024Nuclear Power Economics and Structuring 2024
Nuclear Power Economics and Structuring 2024
 
一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理
一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理
一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理
 
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdfTop 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
 
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&BDesign and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
 
Fundamentals of Electric Drives and its applications.pptx
Fundamentals of Electric Drives and its applications.pptxFundamentals of Electric Drives and its applications.pptx
Fundamentals of Electric Drives and its applications.pptx
 
Student information management system project report ii.pdf
Student information management system project report ii.pdfStudent information management system project report ii.pdf
Student information management system project report ii.pdf
 
Cosmetic shop management system project report.pdf
Cosmetic shop management system project report.pdfCosmetic shop management system project report.pdf
Cosmetic shop management system project report.pdf
 
HYDROPOWER - Hydroelectric power generation
HYDROPOWER - Hydroelectric power generationHYDROPOWER - Hydroelectric power generation
HYDROPOWER - Hydroelectric power generation
 
power quality voltage fluctuation UNIT - I.pptx
power quality voltage fluctuation UNIT - I.pptxpower quality voltage fluctuation UNIT - I.pptx
power quality voltage fluctuation UNIT - I.pptx
 
CFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptx
CFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptxCFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptx
CFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptx
 
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdfAKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
 
The role of big data in decision making.
The role of big data in decision making.The role of big data in decision making.
The role of big data in decision making.
 
Final project report on grocery store management system..pdf
Final project report on grocery store management system..pdfFinal project report on grocery store management system..pdf
Final project report on grocery store management system..pdf
 

java intro.pptx

  • 1. DEFINATION : ●Java is an object-oriented multithreaded programming language developed by Sun Microsystems. ●Write Once Run Anywhere ●Java is a general-purpose, high-level programming language.
  • 2. Java Applications ●Stand-alone Applications ◦ Just like any programming language ●Applet ◦ Run under a Java-Enabled Browser ●Midlet ◦ Run in a Java-Enabled Mobile Phone ●Servlet ◦ Run on a Java-Enabled Web Server
  • 3. Versions of Java ● Java Language vs Java Platform ◦ Current version of the language is 1.7 ◦ Core language plus additional APIs is called the Java 2 platform ● Java 2 Micro Edition (J2ME) ◦ Very small Java environment for smart cards, pages, phones, and set-top boxes ◦ Subset of the standard Java libraries aimed at limited size and processing power ● Java 2 Standard Edition (J2SE) ◦ The basic platform, which this course will cover ● Java 2 Enterprise Edition (J2EE) ◦ For business applications, web services, mission-critical systems ◦ Transaction processing, databases, distribution, replication
  • 4. Use of JAVA Technology …. ●The Java technology is: ◦ A programming language Java can create all kinds of applications that you could create using any conventional programming language. ◦ A development environment As a development environment, Java technology provides you with a large suite of tools.
  • 5. ●An application environment ●Java technology applications are typically general- purpose programs that run on any machine where the Java runtime environment (JRE) is installed. ●A deployment environment ●The JRE supplied by the Java 2 Software Development Kit (SDK) contains the complete set of class files for all the Java technology packages, which includes basic language classes, GUI component classes, and so on. ●The other main deployment environment is on your web browser. Most commercial browsers supply a Java technology interpreter and runtime environment.
  • 6. Compiled & Interpreted “Java Bytecode & Java Virtual Machine (JVM)” JAVA …Program … Run….
  • 7. Java is Compiled and Interpreted Text Editor Compiler Interpreter Programmer Source Code .java file Byte Code .class file Hardware and Operating System Notepad javac java appletviewer Java works in two stage • Java compiler translate the source code into byte code. • Java interpreter converts the byte code into machine level representation.
  • 8. Compiler ●Definition:- Acompiler is a program that reads a program in one language, the source language and translates into an equivalent program in another language, the target language. ●The translation process should also report the presence of errors in the source program Source Program→ Compiler→Target Program ↓ Error Messages ●A compiler is a program that translates a source program written in some high-level programming language (such as Java) into machine code for some computer architecture (such as the Intel Pentium architecture).
  • 9. Compiler ➢All language compilers translate source code into machine code for a specific computer. ➢Java compiler also does the same thing, but it produces intermediate code, known as bytecode. ➢Sun's Java compiler called javac.
  • 10. Bytecode: ●Java byte code is a from of instruction that the java special machine execute language ------that can be understood by the Java Virtual Machine (JVM) . ●Each byte code instruction is one byte length & hence there instruction are called as byte code. Java support 256 byte code. ●Byte code are always platform independent . ●independent of any particular computer hardware, so any computer with a Java interpreter can execute the compiled Java program, no matter what type of computer the program was compiled on
  • 11. Java Virtual Machine (JVM) Java program (Source code) Java compiler (javac ) Java Virtual machine Java interpreter (java) Real machine (machine code) Java works in two stage • Java compiler translate the source code into byte code. • Java interpreter converts the byte code into machine level representation.
  • 12. Java Virtual Machine (JVM) ●A JVM is a set of computer programs that implement a specific virtual machine model. ●A JVM accept byetcodes & converts it in the format which is understood by the system.(which it is executed). ● JVM is exist only inside the computer memory. ●(A software "execution engine" that safely and compatibly executes the byte codes in Java class files on a microprocessor (whether in a computer or in another electronic device) ●
  • 13.
  • 14. Java Program Virtual Machine Java Compiler Bytecode Fig. 1 : Process of Compilation ➢The output produce by the Java compiler is not executable code. ➢It is Bytecode, highly optimized set of instructions executed by java run time system or JVM. ➢JVM is the interpreter for the bytecode. ➢The virtual machine code generated by the Java interpreter is not machine specific code, but it is acts as an intermediate between the virtual machine and real machine. Machine code Java Interpreter Bytecode Virtual machine Real machine Fig. 2 : Process of converting bytecode into machine code
  • 15. Java interpreter ●A module that alternately decodes and executes every statement in some body of code. ●The Java interpreter decodes and executes bytecode for the Java virtual machine. ●The Java interpreter is actually a part of JVM. Virtual machine is not just executing the bytecodes, it has lot of tasks to do. That full- fledged environment is referred to as a JVM.
  • 16. Java Runtime Environment (JRE) Definition: The Java Runtime Environment (JRE) is a set of software tools for development of Java applications. It combines the Java Virtual Machine (JVM), platform core classes and supporting libraries. ●JRE is part of the Java Development Kit (JDK), but can be downloaded separately. JRE was originally developed by Sun Microsystems. Also known as Java runtime. ●JDK = JRE + development tools
  • 17. Java Runtime Environment IfJREis not installed on a computer, Java programs may not be recognized by the operating system and will not run. ●The JRE software provides runtime environment in which Java programs can be executed ●JRE software is available as both a standalone environment and a Web browser plug-in, which allows Java applets to be run within a Web browser
  • 18. JRE components: The JRE is developed by Sun Microsystems (the creator of Java) and includes the Java Virtual Machine(JVM), code libraries, and components, which are necessary to run programs written in Java. The JRE is available for multiple computer platforms, including Mac, Windows, and Unix
  • 19.
  • 20. Java Virtual Machine ●To execute a Java program, you run a program called a bytecode interpreter, which in turn reads the bytecodes and executes your Java program. The Java bytecode interpreter is often also called the Java virtual machine or the Java runtime. ●The java bytecodes are a special set of machine instructions that are not specific to any one processor or computer system. A platform-specific bytecode interpreter executes the Java bytecodes. The bytecode interpreter is also called the Java virtual machine or the Java runtime Interpreter.
  • 21. Java Development Kit ●javac - The Java Compiler ●java - ●jdb- The Java Interpreter The Java Debugger ●appletviewer -Tool to run the applets ●javap - to print the Java bytecodes ●javaprof - Java profiler ●javadoc - documentation generator ●javah - creates C header files
  • 22. Main API Packages ■java.lang COLUMN ■java.util ■java.io ■java.awt ■java.awt.image ■java.applet ■java.net
  • 24. DOCUMENTATION SECTION • The documentation section is an important section but optional for a Java program. It includes basic information about a Java program. • The information includes the author's name, date of creation, version, program name, company name, and description of the program. It improves the readability of the program.
  • 25. The comments may be single-line, multi-line, and documentation comments. • Single-line Comment: It starts with a pair of forwarding slash (//). For example: //First Java Program • Multi-line Comment: It starts with a /* and ends with */. We write between these two symbols. For example: • /*It is an example of multiline comment*/ • Documentation Comment: It starts with the delimiter (/**) and ends with */. For example: • /**It is an example of documentation comment*/
  • 26. PACKAGE DECLARATION • The package declaration is optional. It is placed just after the documentation section. In this section, we declare the package name in which the class is placed. • Note that there can be only one package statement in a Java program. • It must be defined before any class and interface declaration. • Eg:package javatpoint; //where javatpoint is the package name
  • 27. IMPORT STATEMENTS • The package contains the many predefined classes and interfaces. If we want to use any class of a particular package, we need to import that class. • The import statement represents the class stored in the other package. We use the import keyword to import the class. • It is written before the class declaration and after the package statement. • Eg:import java.util.Scanner; // it imports the scanner class only • import java.util.*; // it imports all class of java.util package
  • 28. INTERFACE SECTION • It is an optional section. We can create an interface in this section if required. • We use the interface keyword to create an interface. An interface is a slightly different from the class. • It contains only constants and method declarations. • Eg: interface car { void start(); void stop(); }
  • 29. CLASS DEFINITION • In this section, we define the class. • It is vital part of a Java program. Without the class, we cannot create any Java program. • A Java program may conation more than one class definition. We use the class keyword to define the class. • It contains information about user-defined methods, variables, and constants. Every Java program has at least one class that contains the main() method. • Eg: class Student // class definition { }
  • 30. Main Method Class • We define the main() method. It is essential for all Java programs. Because the execution of all Java programs starts from the main() method. • In other words, it is an entry point of the class. It must be inside the class. Inside the main method, we create objects and call the methods. • Eg: public class Student //class definition { public static void main(String args[]) { //statements } }
  • 31. First JAVA Program…. public class Hello { public static void main( String args[ ] ) { //prints the string Welcome To JAVAProgramming! on screen System.out.println(“Welcome To JAVA Programming!”); } }
  • 32. Steps In Running JAVA Program ● Write the previous slide’s source code as your Java program in the Text Editor or IDE. ◦ Save your Java Program with Filename: Hello.java ● Compiling your program ◦ in your commandTerminal window we type in the command: javac [filename] ◦ So in this case, type in: javac Hello.java ◦ During compilation, javac adds a file to the disk called [filename].class, or in this case, Hello.class, which is the actual bytecode.
  • 33. Steps In Running JAVA Program ● Running the Program ◦ To run your Java program, type in the command: java [filename without the extension] ◦ so in the case of our example, type in: java Hello ◦ You can see on the screen after running the program: ◦ " Welcome To JAV AProgramming!"
  • 34. Explanation …. public class Hello { /* My first Java program */ ●indicates the name of the class which is Hello ●In Java, all code should be placed inside a class declaration ●The class uses an access specifies public, which indicates that our class in accessible to other classes from other packages (packages are a collection of classes). ●The next line which contains a curly brace { indicates the start of a block.
  • 35. Explanation ….. public class Hello { public static void main( String args[ ]) { ●indicates the name of one method in Hello which is the main method. ●The main method is the starting point of a Java program. ●All programs except Applets written in Java start with the main method. ●Make sure to follow the exact signature.
  • 36. Explanation ….. public class Hello { public static void main( String[] args ) { //prints the string “Hello world” on screen System.out.println(“Hello world”); } } ●The command System.out.println(), prints the text enclosed by quotation on the screen. ●The last two lines which contains the two curly braces is used to close the main method and class respectively.
  • 37. Fundamental Programming structures in java JAVA TOKENS • In Java, the program contains classes and methods. Further, the methods contain the expressions and statements required to perform a specific operation. • These statements and expressions are made up of tokens. In other words, we can say that the expression and statement is a set of tokens.
  • 39. JAVA Keywords ….(50) ●Keywords are predefined identifiers reserved by Java for a specific purpose. ●You cannot use keywords as names for your variables, classes, methods ... etc.
  • 40. IDENTIFIER • Identifiers are used to name a variable, constant, function, class, and array. It usually defined by the user. • It uses letters, underscores, or a dollar sign as the first character. • There are some rules to declare identifiers are: • The first letter of an identifier must be a letter, underscore or a dollar sign. It cannot start with digits but may contain digits. • The whitespace cannot be included in the identifier. • Identifiers are case sensitive. Eg: int a; int A; // it has different meaning
  • 41. JAVALiterals ….. ●Literals are tokens that do not change - they are constant. ●The different types of literals in Java are: ◦ Integer Literals ◦ Floating-Point Literals ◦ Boolean Literals ◦ Character Literals ◦ String Literals
  • 42. Integer Literals …. ●Integer literals come in different formats ●Special Notations in using integer literals ◦ decimal (base 10) No special notation Example : 12 ◦ hexadecimal (base 16) Precede by 0x or 0X example: 0xC ◦ octal (base 8) Precede by 0 Example : 014
  • 43. Floating point and Boolean Literals ●Represents decimals with fractional parts ◦ Example: 3.1416 ●Can be expressed in standard or scientific notation ◦ Example: 583.45 (standard), 5.8345e2 (scientific) ●Boolean literals have only two values, true or false.
  • 44. Character and String Literals …. ● Character Literals represent single Unicode characters. ● Unicode character ●a 16-bit character set that replaces the 8-bitASCII character set. ●Unicode allows the inclusion of symbols and special characters from other languages ● To use a character literal, enclose the character in single quote delimiter. For example ●the letter a, is represented as ‘a’. ●special characters such as a newline character, a backslash is used followed by the character code. For example, ‘n’for the newline character, ‘r’for the carriage return, ‘b’for backspace. ● String literals represent multiple characters and are enclosed by double quotes. ●An example of a string literal is, “Hello JAVA”.
  • 45. CONSTANTS • Constants in java are fixed values those are not changed during the Execution of program java supports several types of Constants those are :
  • 46. Integer Constants • Integer Constants refers to a Sequence of digits which Includes only negative or positive Values and many other things those are as follows • Example: Decimal Integer Constants • Ocatal Integer Constants • Hexadecimal Integer Constants
  • 47. • Real Constants • Integer numbers are unable to represent distance, height, temperature, price, and so on. These informations are contaning fractional parts or real parts like 56.890. Such numbers are called Real or Floating Point Contants • Example A Real Constant must have at Least one Digit • it must have a Decimal value • Single Character Constants • A Character is Single Alphabet a single digit or a Single Symbol that is enclosed within Single inverted commas. • Character Constant Can hold Single character at a time.
  • 48. • String Constants • String is a Sequence of Characters Enclosed between double Quotes These Characters may be digits, Alphabets Like "Hello", "1234" etc. • The string is "Sequence of Characters". • String Constant is written in Pair of Double Quotes. • The string is declared as Array of Characters.
  • 49. Variable …. ●Avariable has a: ●data type ●The data type indicates the type of value that the variable can hold. ●name ●The variable name must follow rules for identifiers. ●Declare a variable as follows: ●<data type> <name> [=initial value]; ●●Note: Values enclosed in <> are required values, while ●those values in [ ] are optional.
  • 50. Variable Declaration …. public class VariableSamples { public static void main( String[] args ){ //declare a data type with variable name // result and boolean data type boolean result; //declare a data type with variable name // option and char data type char option= 'C'; //assign 'C' to option //declare a data type with variable name //grade, double data type and initialized //to 0.0 double grade = 0.0; } }
  • 51. Variable Types …. ● Two types of variables in Java: ● – Primitive Variables ● – Reference Variables ● Primitive Variables ● – variables with primitive data types such as int,long,char,float,double. ● – A primitive data type is a built-in data type that is a basic building block for all other types and DO NOT create objects. –byte, short, int, long are all integer data types. float and double are floating- point (decimal) data types. ● Reference Variables ● – variables that stores the address in the memory location ● – points to another memory location where the actual data is ● – When you declare a variable of a certain class, you are actually declaring a reference variable to the object with that certain class. ● Suppose we have two variables with data types int and String. ● int num = 10; // primitive type ● String name = "Hello"; // reference type
  • 52. Data Types …. ●The Java programming language defines eight primitive data types. ◦ boolean (for logical) ◦ char (for textual) ◦ byte ◦ short ◦ int ◦ long (integral) ◦ double ◦ float (floating point).
  • 53. Integral Data Types …. ●Integral data types in Java uses three forms – decimal, octal or hexadecimal. ◦ Examples are, 2 //The decimal value 2 077 //The leading 0 indicates an octal value 0xBACC //The leading 0x indicates a hex value ●Integral types has int as default data type. ●You can define its long value by appending the letter l or L. For example: ◦ 10L
  • 54. Intregal Data Types …. ●Integral data type have the following ranges: Length Data Type Range 8 bits/ 1 byte byte -128 to +127 16 bits/ 2 byte short -32768 to+32767 32 bits/ 4 byte int -2147483648 to +2147483647 64 bits/ 8byte long -9223372036854775808 to +9223372036854775807
  • 55. Floating point Types …. ●Floating point types has double as default data type. ●Floating-point literal includes either a decimal point or one of the following, ●E or e //(add exponential value) ●F or f //(float) ●D or d //(double) ●Examples are, ●3.14 //A simple floating-point value (a double) ●6.02E23 //A large floating-point value ●2.718F //A simple float size value ●123.4E+306D//A large double value with redundant D
  • 56. Floating point Data Types …. ●Floating-point data types have the following ranges Length Data Type Range 32 bits/ 4byte float -3.4e38 to 3.4e038 64 bits/ 8byte double -1.7e308 to 1.7e308
  • 57. Boolean Data Type …. ●A boolean data type represents two states: true and false. ●An example is, ◦ boolean result = true; ●The example shown above, declares a variable named ◦ result as boolean type and assigns it a value of true.
  • 58. Character Data Type …. ●A character data type (char), represents a single Unicode character. ●It must have its literal enclosed in single quotes(’ ’). For example, ●‘a’ //The letter a ●‘t’ //A tab ●To represent special characters like ' (single quotes) or " (double quotes), use the escape character . For Example, ●''' //for single quotes ●'"' //for double quotes
  • 59. String as Reference Type …. ●Although, String is not a primitive data type (it is a Class) ●A String represents a data type that contains multiple characters. It is not a primitive data type, it is a class. ●It has its literal enclosed in double quotes(“”). For example, ◦ String message =“Hello JAVA!”; ◦ String creator = new String(“James A. Gosline”);
  • 60.
  • 61. Operators …. ●Different types of operators: ◦ Arithmetic operators ◦ Unary operators. ◦ Increment & decrement operators ◦ Relational operators ◦ Logical operators ◦ Assignment operators ◦ Ternary/conditional operators ◦ Bitwise operator ●These operators follow a certain kind of precedence so that the compiler will know which operator to evaluate first in case multiple operators are used in one statement.
  • 63. Operator Description + Addition - subtraction * multiplication / division % remainder after integer division Arithmetic Operators …. Operator Use Description + op1 + op2 Adds op1 with op2 - op1 - op2 Substract op1 with op2 * op1 * op2 Multiply op1 with op2 / op1 / op2 Divide op1 with op2 % op1 % op2 Remainder of divide op1 by op2
  • 64. Types of Arithmetic Operator ●Integer type Arithmetic : Both integer ●Real Arithmetic Both float ●Mix mode Arithmetic integer / float =float 25/10.0=2.5
  • 65. /* Program to demonstrate the addition and subtraction of double numbers*/ class AddSubDoubles { public static void main (String args[]) { double x = 7.5; double y = 5.4; System.out.println("x is : " + x); System.out.println("y is : " + y); double z = x + y; System.out.println("x + y is : " + z); z = x - y; System.out.println("x - y is : " + z); } }
  • 66. Unary Operator … ●Example : ●-743 -0x7fff -0.2 -E-8 -(x + y) ●-root 1 -3*(x + y)
  • 67. Unary Operator … ●Unary numeric promotion is applied to the single operand of the unary arithmetic operators - and +. ◦ When a unary arithmetic operator is applied to an operand whose type is narrower than int, the operandis promoted to a value of type int, with the operation resulting in an int value. ●Binary numeric promotion for operands of binary operators implies that each operand of a binary operator is promoted to type int or a broader numeric type
  • 68. Increment & Decrement Opeartor Operator Use Description ++ ++op Increment op by 1 evaluates to the value of op after it was incremented ++ op++ Increment op by 1 evaluates to the value of op before it was incremented -- --op Decrement op by 1 evaluates to the value of op after it was decremented -- op-- Decrement op by 1 evaluates to the value of op before it was decremented Prof.Deepak Gaikar Operator Representation Pre-increment + + i Post increment i + + Pre decrement -- i Post decrement i - -
  • 69. The SYNTAX of these operators is given below: ++<variable name > <variable name>++ --<variable name> <variable name>--
  • 70. syntax: variable = expression example: a =3 , x=y also java contains the following 5 additional assignment operator (+ =, - =,* =, % =) syntax: expression1+= expression2 is equivalent to: expression1=expression1+expression2 simllarly, the assignment expression expression 1 -= expression2 is equivalent to: expression1=expression1-expression Assignment operator
  • 71. Operator Expression Result i + = 3 i = i + 3 i = 18 i - = 2 i = i – 2 i = 13 i * = 4 i = i * 4 i = 60 i / = 3 i = i / 3 i = 5 i % = 4 i = i % 4 i = 3
  • 72. Precedence Associativity of Increment/Decrement Operators: Prof.Deepak Gaikar Operator Associativity Icrement/Decrements Right to Left Arithmetic Left to right ASSIGNMENT Right to Left Precedence Associativity of Increment/Decrement Operators Operator operations Associativity - , + Unary minus Right to Left ++ -- Increment Decrement Right to Left * / % Multiplication Division Modulus Left to Right + - Addition Subtraction Left to Right = Assignment Right to Left
  • 73. Relational Opeartor …. ● Relational operators compare two values and determines the relationship between those values. ● The output of evaluation are the Boolean values true or false. Operator Use Description > op1 > op2 op1 is greater than op2 >= op1 >= op2 op1 is greater than or equals to op2 < op1 < op2 op1 is less than op2 <= op1 <= op2 op1 is less than or equals to op2 == op1 == op2 op1 is equals to op2 != op1 != op2 op1 is not equals to op2 Compare two value Result : true or false relational operator …use for, while, ...Operator ∈, ∈=, >, >=, ==, != Higher precedence lower precedence
  • 74. /* Program to demonstrate Relational Operators */ class RelationalOp { public static void main(String args[]) { float x = 15.0F, y = 10.65F, z = 25.0F; System.out.println("x = "+x); System.out.println("y = "+y); System.out.println("z = "+z); System.out.println("x < y is : "+(x<y)); System.out.println("x > y is : "+(x>y)); System.out.println("x == z is : "+(x==z)); System.out.println("x <= z is : "+(x<=z)); System.out.println("x >= y is : "+(x>=y)); System.out.println("y != z is : "+(y!=z)); System.out.println("y == x+z is : "+(y==x+z)); } }
  • 75. Logical Operator …. ●Logical operators have one or two boolean operands that yield a boolean result. There are six logical operators: ◦ && (logical AND) ◦ & (boolean logical AND) ◦ || (logical OR) ◦ | (boolean logical inclusive OR) ◦ ^ (boolean logical exclusive OR) ◦ ! (logical NOT)
  • 76. Operand Usage && Logical AND. Returns 1 if both the expressions are non-zero. || Logical OR. Returns 1 if either of the expression is non-zero. ! Unary negation. It converts a non-zero operand into 0 and a zero operand into 1. Expr1 Expr2 Expr1 && Expr2 Expr1 || Expr2 0 0 0 0 0 non-zero 0 1 non-zero 0 0 1 non-zero non-zero 1 1
  • 77. && (short-circuit AND)and & Operator ●Here is the truth table for && and &, Prof.Deepak Gaikar X1 X2 Result TRUE TRUE TRUE TRUE FALSE FALSE FALSE FALSE FALSE FALSE TRUE FALSE ●The basic difference between && and & operators : ● && supports short-circuit evaluations (or partial evaluations), while & doesn't. ● Given an expression: exp1 && exp2 ● && will evaluate the expression exp1, and immediately return a false value is exp1 is false. ● If exp1 is false, the operator never evaluates exp2 because the result of the operator will be false regardless of the value of exp2. ● In contrast, the & operator always evaluates both exp1 and exp2 before returning an answer.
  • 78. || OR Operators ●Here is the truth table for || and |, Prof.Deepak Gaikar ●The basic difference between || and | operators : ● || supports short-circuit evaluations (or partial evaluations), while | doesn't. ● Given an expression: ● exp1 || exp2 ● || will evaluate the expression exp1, and immediately return a true value is exp1 is true ● If exp1 is true, the operator never evaluates exp2 because the result of the operator will be true regardless of the value of exp2. ● In contrast, the | operator always evaluates both exp1 and exp2 before returning an answer. X1 X2 Result TRUE TRUE TRUE TRUE FALSE TRUE FALSE FALSE FALSE FALSE TRUE TRUE
  • 79. ^ Logical XOR(Exclusive) Operator …. ●Here is the truth table for ^, ●The result of exclusive or operation is TRUE, if and only if one operand is true and the other is false. X1 X2 Result TRUE TRUE FALSE TRUE FALSE TRUE FALSE FALSE FALSE FALSE TRUE TRUE
  • 80. ! Operator …. ●The logical NOT takes in one argument, wherein that argument can be an expression, variable or constant. ●Here is the truth table for !, X Result TRUE FALSE FALSE TRUE
  • 81. /* Program to demonstrate the boolean logical operators */ class BoolLogic { public static void main(String args[]) { boolean a = true; boolean b = false; boolean c = a|b; boolean d = a&b; boolean e = a^b; boolean f = (!a & b)|(a & !b); boolean g = !a; System.out.println(" System.out.println(" System.out.println(" System.out.println(" System.out.println(" a = "+a); b = "+b); a|b = "+c); a&b = "+d); a^b = "+e); } System.out.println(" !a&b|a&!b = "+f); System.out.println(" !a = "+g); }
  • 82. Conditional Opeartor …. ●The conditional operator ?: ◦ is a ternary operator. ●This means that it takes in three arguments that together form a conditional expression. ◦ The structure of an expression using a conditional operator is exp1?exp2:exp3 ◦ exp1 - is a boolean expression whose result must either be true or false ◦ Result: If exp1 is true, exp2 is the value returned. If it is false, then exp3 is returned.
  • 83. BITWISE Operator Operator Meaning & BITWISE AND | BITWISE OR ^ BITWISE XOR(EXCLUSIVE OR) ~ One’s complement >> Right SHIFT << LEFT SHIFT >>> SHIFT righit zero fill assiggnment
  • 84. Operator Precedence …. Prof.Deepak Gaikar Operator operations Associatively . ( ) [ ] Access object member Function call Access Array element Left to Right - Unary minus ++ Increment -- Decrement ! Logical negation ~ Ones complement (bitwise Not ) Right to Left (data type) new Casting Object creation Right to Left * Multiplication / Division % Modulus + Addition - Subtraction Left to Right + String concatenation Left to Right >> Right SHIFT << LEFT SHIFT Left to Right >>> SHIFT righit zero fill assiggnment
  • 85. < <= > >= Instanceof Less than Less than or equals to Left to Right Greater than Greater than or equals to = = != Equality Not equal Left to Right & ^ | && || ?: BITWISE AND BITWISE XOR(EXCLUSIVE OR) BITWISE OR Logical AND Logical OR. Conditional Operator Left to Right Left to Right Left to Right Left to Right = , +=,-=, *= , /=, %= , &= , ^= ,|= , <<= , Assignment & Compound assignment operator Right to Left >>= , >>>
  • 86.
  • 87. Objectives …. ●Use decision control structures (if, else, switch) which allows selection of specific sections of code to be executed ●Use repetition control structures (while, do-while, for) which allow executing specific sections of code a number of times ●Use branching statements (break, continue, return) which allows redirection of program flow
  • 88. ●Control structures ◦ allows us to change the ordering of how the statements in our programs are executed ●Two types of Control Structures ◦ decision control structures allows us to select specific sections of code to be executed ◦ repetition control structures allows us to execute specific sections of the code a number of times
  • 89. if Statement …. ●if-statement ◦ specifies that a statement (or block of code) will be executed if and only if a certain boolean statement is true. ◦ if-statement has the form: if( boolean_expression ) statement; ◦ or if-statement with block if( boolean_expression ) { statement1; statement2; } ◦ where, boolean_expression is either a boolean expression or boolean variable.
  • 90. Boolean Expression …. ●The boolean_expression part of a statement should ◦ evaluate to a boolean value. That means that the execution of the condition should either result to a value of true or a false. ●Indent the statements inside the if-block. For example, if( boolean_expression ){ //statement1; //statement2; }
  • 91. ● if-else statement ◦ used when we want to execute a certain statement if a condition is true, and a different statement if the condition is false. ● if-else statement has the form: if( boolean_expression ) { statement1; statement2; } else { statement3; statement4; }
  • 93. Switch Statement …. ◦ allows branching on multiple outcomes. ◦ switch statement has the form: switch( switch_expression ) { case case_selector1: statement1;// statement2;//block 1 break; case case_selector2: statement1;// statement2;//block 2 break; default: statement1;// statement2;//block n } Prof.Deepak Gaikar
  • 94. Switch Case Expression …. ● where, ◦ switch_expression is an integer or character expression ◦ case_selector1, case_selector2 and so on, are unique integer or character constants. ● When a switch is encountered, ◦ Java first evaluates the switch_expression, and jumps to the case whose selector matches the value of the expression. ◦ The program executes the statements in order from that point on until a break statement is encountered, skipping then to the first statement after the end of the switch structure. ◦ If none of the cases are satisfied, the default block is executed. Take note however, that the default part is optional.
  • 95. Repeatation Control Structures …. ●Repetation control structures ◦ are Java statements that allows us to execute specific blocks of code a number of times. ●Types: ◦ while-loop ◦ do-while loop ◦ for-loop
  • 96. While Loop Statement …. ● while loop ◦ is a statement or block of statements that is repeated as long as some condition is satisfied. ● while loop has the form: while( boolean_expression ) { statement1; statement2; } ◦ The statements inside the while loop are executed as long as the boolean_expression evaluates to true.
  • 97. Do While Loop Statement …. ● do-while loop ◦ is similar to the while-loop ◦ statements inside a do-while loop are executed several times as long as the condition is satisfied ◦ The main difference between a while and do-while loop: the statements inside a do-while loop are executed at least once. ● do-while loop has the form: Do { statement1; statement2; }while( boolean_expression ); Prof.Deepak Gaikar
  • 98. For Loop Statement …. ● for loop ◦ allows execution of the same code a number of times. ◦ for loop has the form: for(InitializationExpression;LoopCondition;StepExpression) { statement1; statement2; . . . } ◦ where, InitializationExpression -initializes the loop variable. LoopCondition - compares the loop variable to some limit value. StepExpression - updates the loop variable.22
  • 99. Branching Statement …. ● Branching statements allows us to redirect the flow of program execution. ● Java offers three branching statements: ◦ break ◦ continue ◦ return. ● unlabeled break ◦ terminates the enclosing switch statement, and flow of control transfers to the statement immediately following the switch. ◦ This can also be used to terminate a for, while, or do-while loop
  • 100. Labeled Break Statement …. ●labeled break statement ◦ terminates an outer statement, which is identified by the label specified in the break statement. ◦ the flow of control transfers to the statement immediately following the labeled (terminated) statement. ◦ The sample program in the next slide searches for a value in a two dimensional array. Two nested for loops traverse the array. When the value is found, a labeled break terminates the statement labeled search, which is the outer forPlro o f.D o ee p pa .k Gaikar
  • 101. Example …. int[][] numbers = {{1, 2, 3}, {4, 5, 6},{7, 8, 9}}; int searchNum = 5; boolean foundNum = false; searchLabel: for( int i=0; i<numbers.length; i++ ){ for( int j=0; j<numbers[i].length; j++ ){ if( searchNum == numbers[i][j] ){ foundNum = true; break searchLabel; } } } if( foundNum ) System.out.println(searchNum + " found!" ); else System.out.println(searchNum + " not found!");Prof.Deepak Gaikar
  • 102. Continue Statement …. ●unlabeled continue statement ◦ skips to the end of the innermost loop's body and evaluates the boolean expression that controls the loop, basically skipping the remainder of this iteration of the loop. ●labeled continue statement ◦ skips the current iteration of an outer loop marked with the given label.
  • 103. Return Statement …. ● return statement ◦ used to exit from the current method. ◦ flow of control returns to the statement that follows the original method call. ● To return a value ◦ simply put the value (or an expression that calculates the value) after the return keyword. For example, return ++count; ◦ or return "Hello"; ◦ The data type of the value returned by return must match the type of the method's declared return value. ◦ When a method is declared void, use the form of return that doesn't return a value. – For example, return;
  • 104. //Write a program to display the following pattern 1 01 101 0101 10101 import java.io.*; class Pattern { public static void main(String args[]) { int i,j,n,k; Scanner br=new System.out.print("Enter number of lines:"); n=br.nextInt()); for(i=1;i<=n;i++) { for(j=0;j<=i-1;j++) { System.out.print((i+j)%2 + " "); } System.out.println(); } }}
  • 105. //Write a program to determine the sum of the series 1-1/2+1/3+1/4+…….+1/n import java.util.*; class Sum{ public static void main(String args[]) { int i,n,sign=1; float sum=0; Scanner br=new Scanner(System.in)); System.out.print("Enter value of n:"); n=br.nextInt(); for(i=1;i<=n;i++) { sum=sum+1.0f/i*sign; sign=sign*-1; } System.out.println("Sum=" + sum); } }
  • 106. //Write a program to determine the sum of the series 1+1/2!+1/3!+1/4!+…….+1/n! import java.util.*; class Sum { public static void main(String args[]) { int i,n,fact=1; float sum=0; Scanner br=new Scanner(System.in); System.out.print("Enter the value of n:"); n=br.nextInt(); for(i=1;i<=n;i++) { fact=fact*i; sum=sum+1.0f/fact; } System.out.println("Sum=" + sum); }} /*output******* Enter the value of n:3 sum=1.66666666 */