0% found this document useful (0 votes)
43 views

2 Java

This document provides an overview of the history and key features of the Java programming language. It discusses the origins of Java as a project at Sun Microsystems in the early 1990s to develop software for consumer electronics. While the original project failed, Java was adapted for use on the internet. The document then outlines Java's main buzzwords and features, including being simple, secure, portable, object-oriented, robust, multithreaded, architecture-neutral, interpreted, high-performance, distributed, and dynamic. It provides definitions and examples for each of these features.

Uploaded by

saumya patel
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
43 views

2 Java

This document provides an overview of the history and key features of the Java programming language. It discusses the origins of Java as a project at Sun Microsystems in the early 1990s to develop software for consumer electronics. While the original project failed, Java was adapted for use on the internet. The document then outlines Java's main buzzwords and features, including being simple, secure, portable, object-oriented, robust, multithreaded, architecture-neutral, interpreted, high-performance, distributed, and dynamic. It provides definitions and examples for each of these features.

Uploaded by

saumya patel
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 135

Java Basics

Books

Books:
1. Naughton, Schildt, “The Complete Reference JAVA2”, TMH

2. Balagurusamy E, “Programming in JAVA”, TMH

Reference Books:
3. Brett Spell, Professional Java Programming, WROX Publication

4. H.M.Dietal, Advanced Java 2 Platform : How to program, PHI,2nd


Ed

5. Steven Holzner, “Java2 Black book”, dreamtech


1.1 Java History
• Computer language innovation and development occurs
for two fundamental reasons:
1) to adapt to changing environments and uses
2) to implement improvements in the art of
programming
• The development of Java was driven by both in equal
measures.
• Many Java features are inherited from the earlier
languages:
B  C  C++  Java
Before Java: C

• Designed by Dennis Ritchie in 1970s.

• Before C: BASIC, COBOL, FORTRAN, PASCAL

• C :Structured, efficient, high-level language that could


replace assembly code when creating systems programs.

• Designed, implemented and tested by programmers.


Before Java: C++
• Designed by Bjarne Stroustrup in 1979.
• Response to the increased complexity of programs and respective
improvements in the programming paradigms and methods:
1) assembly language
2) high-level languages
3) structured programming
(Structured programming is a programming paradigm aimed on
improving the clarity, quality, and development time of a 
computer program by making extensive use ofsubroutines, 
block structures and for and while loops – in contrast to using jumps
such as the goto statement which could lead to "spaghetti code"
which is harmful.
4) object-oriented programming (OOP)
• OOP – methodology that helps organize complex programs through the use
of inheritance, encapsulation and polymorphism.
• C++ extends C by adding object-oriented features.
Java: History
• In 1990, Sun Microsystems started a project called Green.
• Objective: to develop software for consumer electronics.
• Project was assigned to James Gosling, a veteran of classic
network software design. Others included Patrick Naughton,
ChrisWarth, Ed Frank, and Mike Sheridan.
• The team started writing programs in C++ for embedding into
– toasters
– washing machines
– VCR’s
• Aim was to make these appliances more “intelligent”.
Java: History (contd.)
• C++ is powerful, but also dangerous. The power and popularity of C
derived from the extensive use of pointers. However, any incorrect
use of pointers can cause memory leaks, leading the program to
crash.
• In a complex program, such memory leaks are often hard to detect.
• Users do not expect toasters to crash, or washing machines to crash
just like in case of operating system.
• A design for consumer electronics has to be robust.
• Replacing pointers by references, and automating memory
management was the proposed solution.
Complete History
• In 1991 researcher at sun microsystem started thinking that consumer electronics will capture the market in future.

Sun Microsystem secretly started a project "Project Green" for creating a simple device that can control a variety of day to
day electronics devices. This project was secret and the team member cut off from the company to complete the project.

Team of "project green" had 13 members group, leading by Dr. arthur james gosling.

After 18 months, the Green project team emerged with a device that they called Star7. Essentially, it worked like today's
PDA and had a animated color touchscreen. This device ran a application which react to user on touch.

Star7 was meant as demonstration platform. Green project team expected that software running on device could be
deployed on various platform i.e. television, home appliance.

How an application could work on various platform? this was the problem before "Green" team.

james gosling created the language that fulfill required functionality. He called this language Oak after a large oak tree
outside his office

Oak was processor independent so it could easily be used on all consumer devices.

The Green project tream tried to convince some industries that their creation was ideal. But unfortunately it didn't take
off. Project Green was failure.

In 1993, WWW exploded. Soon sun microsystem realised that language they have created could work better that
consumer market.

Green Project team discovered that language named oak already existing, so they had to change the name.

Before java became official name for language other name Neon, pepper, silk names were suggested
The Java Buzzwords
• The key considerations were summed up by the Java team
in the following list of buzzwords:

 Simple
 Secure
 Portable
 Object-oriented
 Robust (Doesn’t do memory crashing)
 Multithreaded
 Architecture-neutral
 Interpreted
 High performance
 Distributed
 Dynamic
Java Features
• Simple

Object oriented

Polymorphism

Inheritance

. multithreading
.

C++
Java
The Java Buzzwords (Definition)

• simple – Java is designed to be easy for the professional programmer to learn


and use. Java omits many rarely used, poorly understood, confusing
features of C++. Say : No Pointer! No dynamic delete.

• object-oriented: a clean, usable, pragmatic approach to objects, not restricted


by the need for compatibility with other languages.
Object –oriented design is a technology that focuses design on the data
(object) and on the interfaces to it.
Let’s say, everything is an object, everything will become a class in
Java. Every java program, in top- level view, is classes.

• Secure: restricts the programmer to find the mistakes early, performs compile-
time (strong typing) and run-time (exception-handling) checks, manages
memory automatically.
• programs are confined to the Java execution environment and cannot access other
parts of the computer.
Java’s Features
• Secure

Internet

When java bytecode come from network or another machine, in that case before
executing that file verifier check first.
Java’s Features
• Pure Object Oriented

Class One
{
Public static void main(String arg[])
{
System.out.println(“Hello World”);
}
}

In java everything must be inside class .


The Java Buzzwords (Definition)

• Architecture-neutral: Java Virtual Machine provides a


platform independent environment for the execution of
Java byte code
• Interpreted and high-performance: Java programs are
compiled into an intermediate representation – byte code:
a) can be later interpreted by any JVM
b) can be also translated into the native machine code for
efficiency.
Multithreaded: supports multi-threaded programming for
writing program that perform concurrent computations
Java Features
• Multithreading

This is demo for checking This is demo for checking


multithreading concept of java . multithreading concept of java .

Spelling checking operation


running while used giving input

Developed in early c Developed in early java


The Java Buzzwords (Definition)

• Distributed: Java handles TCP/IP protocols, accessing a


resource through its URL much like accessing a local file.
Basically, Java is for Net-Work application, for WEB project.

Java can open and access “objects” across the Net via URLs
(Uniform Resource Locator)----eg.
“http//:gamut.neiu.edu/~ylei/home.html”,
with the same ease as when accessing a local file system

• Dynamic: substantial amounts of run-time type information


to verify and resolve access to objects at run-time.
The Java Buzzwords (Definition)

• Portability: Many types of computers and operating


systems are in use throughout the world—and many
are connected to the Internet.
• For programs to be dynamically downloaded to all
the various types of platforms connected to the
Internet, some means of generating portable
executable code is needed. The same mechanism
that helps ensure security also helps create
portability.
• Indeed, Java's solution to these two problems is both
elegant and efficient.
Java’s Features
• Platform Independent
Java’s Features
• Strongly typed

#include<stdio.h>
Void main()
{
printf(“Value of I”,&i);

Every variable used in program must be declared.


Garbage collection
One ob1=new One();
Two ob2=new Two();

Ob1=ob2;

one class two class


object object

Ob1 Ob2

Memory
Java’s Features(continue)
• Robust
The single biggest difference between Java
and C/C++ is that Java has “a inner safe pointer-
model”, therefore it eliminates the possibility of
overwriting memory and corrupting data, so
programmers feel very safe in coding.
Computing platform include hardware and software

Platform
framework, this combination allows software to run.
Platform problem
Source code

Compiler
(windows)

Object code
Platform problem
Source code Source code Source code

Compiler Compiler Compiler


(windows) (linux) (mac)

Object code Object code Object code


java
Java Intermediate
Source code code

Compiler
Interpreter

Intermediate Object code


code execution

Phase I Phase II
Byte code
Byte code

Interpreter Interpreter Interpreter


(windows) (linux) (mac)

Object code Object code Object code


Byte code

Byte Code Byte Code Byte Code

JVM JVM JVM

Windows Linux Mac


Operating system Operating system Operating system
Java Virtual Machine(JVM)
• JVM (Java Virtual Machine) is an abstract
machine. It is a specification that provides
runtime environment in which java bytecode
can be executed.
• JVMs are available for many hardware and
software platforms (i.e.JVM is plateform
dependent).
What it does?

The JVM performs following operation:


• Loads code
• Verifies code
• Executes code
• Provides runtime environment

JVM provides definitions for the:


• Memory area
• Class file format
• Register set
• Garbage-collected heap
• Fatal error reporting etc.
A=10

Byte code
B=20
C=A+B

0 iload_1
Java 1 iload_2 Intermediate
Source code 2 iadd code
3 istore_3

Compiler
Interpreter

Intermediate Object code


code execution

Phase I Phase II
mainly for c++ programmer
Why Java ?
• Portable
• Easy to learn

• [ Designed to be used on the Internet ]


Compilation process in ‘ C ’
Source code( .c file)

C Compilation process
Preprocessor

Compiler

Assembly code
Components of
Compiler
Assember

Libraries
Object code

Linker

Executable file
Preprocessor
/* this is demo */
#include<stdio.h>
void main()
{
printf (“hello”);
}
Preprocessor

code of stdio.h file


void main()
{
printf (“hello”);
}
Preprocessor remove comments and include header files in
source code, replace macro name with code.
Compiler
code of stdio.h file
void main()
{
printf (“hello”);
}
Compiler

push ebp
mov ebp, esp
and esp, -16
sub esp, 16
mov eax, OFFSET FLAT:.LC0
mov DWORD PTR [esp],
eax
Compiler generate assebmly code. call printf
leave
ret
Assembler
push ebp
mov ebp, esp
and esp, -16
sub esp, 16
mov eax, OFFSET FLAT:.LC0
mov DWORD PTR [esp],
eax
call printf
leave
ret Assembler
00101001100101001
10101111010100101
01010010101011010
01010101010010101
01001100111111100
10001010010101001
Assebler convert assemble code into object code. 01011111011111111
11111010000000011
10010010
Linker
001010011 001010011 001010011
001010011 001010011 001010011
010111101 010111101 010111101
010010101 Libraries
010010101 010010101
010010101 010010101 010010101
0110 0110 0110

Linker
Linker: Static linking one()

#include<stdio.h>
void main()
{ one(); } 01010
10000
Libraries 01010
01010
001010011001
010011010111
Call function
110
one()

Linker

Code of function one included in final 001010011001010


executable file.
011010111110
01010100000101001010
Linker: Static Linking
Code of file 1 calling 200 funtions.
Code of file 2 calling 100 functions.

Libraries
Object file1 Object file2

Linker

Size ?
JAVA Programming
Java Package
• Java package has two parts
– JDK( java development Kit)
– JRE(java runtime environment)

• Java version 1.7


Hello program in c++
1. For including header files.
#include<iostream.h>
void main() 2. main function start
{
Cout<<“hello world” ;
} 3. print on screen hello world

#include<iostream.h>
void main(int argc , char * argv[])
{
Cout<<“hello world “;
}
Java first program
• Java is pure object oriented programming
language.
Class demo
{

main funtion(arguments)
{
print statement for hello world
}

}
First Java Program
For including libraries in java(like include statement in c)

import java.lang.*;
Name of class
Class demo
{ Main method in java. With string type of argument

public static void main(String arg[])


{ To print message on screen(like printf function)
System.out.println(“Hello World”);
}
}
Importing library
• If you need any routines that defined by java
package
import java.util.*;
import java.io.*;
• Put at the very beginning of the java file
• java.lang.* already been imported.
• Check javadoc for the classes
A Closer Look at the First Sample Program
class demo {
• This line uses the keyword class to declare that a new class is
being defined.
• demo is an identifier that is the name of the class. The entire
class definition, including all of its members, will be between
the opening curly brace ({) and the closing curly brace (}).

public static void main(String args[]) {


• This line begins the main( ) method. As the comment
preceding it suggests, this is the line at which the program
will begin executing
A Closer Look at the First Sample Program
• The public keyword is an access specifier, which allows the
programmer to control the visibility of class members. When a
class member is preceded by public, then that member may be
accessed by code outside the class in which it is declared.

• The keyword static allows main( ) to be called without having to


instantiate a particular instance of the class. This is necessary since
main( ) is called by the Java interpreter before any objects are
made.

• The keyword void simply tells the compiler that main( ) does not
return a value. As you will see, methods may also return values.
A Closer Look at the First Sample Program
• Any information that you need to pass to a method is received by variables
specified within the set of parentheses that follow the name of the method.
These variables are called parameters. If there are no parameters required
for a given method, you still need to include the empty parentheses.

• String args[ ] declares a parameter named args, which is an array of


instances of the class String

• args receives any command-line arguments present when the program is


executed

• System is a predefined class that provides access to the system, and out is
the output stream that is connected to the console.
Commands to run
• Save file with name of class, which contains
main method
• javac demo.java

• java demo
Creating, Compiling And Running Java
Programs
Java program Type it in with the text editor of your choice

filename.java
(java file)

Java compiler
javac
Java byte code

filename.class
To compile the program at the
command line type "javac
filename.java"
Java Interpreter
java
To run the interpreter, at the
command line type "java
filename"
Compiling The Smallest Java Program

Smallest.java
public class Smallest
Type “javac
{ Smallest.java”
public static void main (String[] args)
{
}
}

javac
Smallest.class
(Java byte code)
10000100000001000
00100100000001001
: :
Running The Smallest Java Program
Smallest.class
(Java byte code)
10000100000001000
00100100000001001
: :

java

Type “java Smallest” (Platform/Operating specific binary


10100111000001000
00100111001111001
: :
JDK versions
Difference between JDK,JVM and JRE
A Java program
/*
Here you describe what your program does.

*/

public class CLASS-NAME {


public static void main (String args[]) {

// your program goes here

} // end of main
} // end of class
Compiling and Running
In order to run a Java program:
• First you compile it
– that is, you run a program called compiler that checks whether the
program follows the Java syntax
– if it finds errors, it lists them
– If there are no errors, it translates the program into Java bytecode
– Example: assume you created a program called Hello.java
prompt>javac Hello.java
– If successful, this creates a file Hello.class which contains the
translation (Java bytecode) of Hello.java

• Then you execute it


– That is, you call the Java Virtual Machine to interpret and execute the
Java bytecode of your program
– Example:
prompt>java Hello
Compile & Run
• Interpreted Execute: cross-platform
why: For cross-platform purpose. Once coding, run anywhere.
The Java interpreter ( java.exe and its javaVirtualMachine) can execute
compiled Java-byte-codes(Xyz.class) directly on any machine to which the
interpreter has been ported.
`
How:
- Edit source code “demo.java” , by notepad/or other IDE tools

- Compile ( javac.exe ) “demo.java” javac Demo.java


Java byte codes, namely, Demo.class

- Execute (Interpreted Execute) java Demo


Hello world program

When learning a new language, the first program people usually write is
one that salutes the world :). Here is the Hello world program in Java.
/*
This program prints out “hello world!” and terminates.
*/
public class Hello {
public static void main (String args[]) {

System.out.println(“Hello world!”);

} // end of main
} // end of class
Notes
• Comments
– what follows after // on the same line is considered comment
– Or, what is in between /* this is a comment */

• Indentation
– is for the convenience of the reader; compiler ignores all spaces and new lines ; the
delimiter for the compiler is the semicolon

• All instructions end by semicolon

• Lower vs. upper case matters!!


– Void is different than void
– Main is different that main
Writing to user
(output)

System.out.println(variable-name);
prints the value of variable <variable-name> to the user

System.out.println(“any message “);


prints the message within quotes to the user

System.out.println(“hello” + “world” + a + “plus“ + b);


assuming the value of a is 3 and of b is 7, it prints
helloworld3plus7

Note: System.out.println() always prints on a new line.


Example
/*
This program illustrates the System.out.println command.
*/
public class Hello {
public static void main (String args[]) {

System.out.println(“This is my first Java program!”);


System.out.print(“I like Java.”);
System.out.print(“I think Java is cool.”);

} // end of main
} // end of class

• Exercise: change the print to println above. What is the difference?


Variable declaration
type variable-name;
Meaning: variable <variable-name> will be a variable of type <type>

Where type can be:


– int //integer
– double //real number

Example:
int a, b, c;
double x;
int sum;
Example

/*
Printing ages.
*/
public class MyFirstJavaProgram {
public static void main (String args[]) {

int myAge, myFriendAge; /* declare two integer variables */

myAge = 20;
myFriendAge = myAge + 1; //one year older
System.out.println(“Hello, I am “ +myAge + “years old, and my friend is “ +
myFriendAge + “ years old”);
System.out.println(“Goodbye”);

} // end of main
} // end of class
Java Data Type
Type Description
byte 8 bit signed integer

short 16 but signed integer

int 32 bit signed integer

long 64 bit signed integer

float 32 bit signed real number

double 64 bit signed real number

char 16 bit Unicode character (ASCII and


beyond)
boolean 1 bit true or false value

String A sequence of characters between double


quotes ("")
Boolean data type
• This data type can store only two values; true and false.
Declaring a boolean variable is the same as declaring any
other primitive data type like int, float, char.
• boolean response = false; //Valid
• boolean answer = true; //Valid
• boolean answer = 9943; //Invalid,
• boolean response = “false”; // Invalid,

• This is return type for relational & conditional operators.


Comments
• // One line comment

• /* multiple line
Comment
*/

/*** These comment used in documentation


*This is comment.
*This is comment
*/
What should be in comment?
• Author name
• Purpose of function
Default values for primitive members

• When a primitive type Primitive type Default


data is a member of a boolean false
class, it’s guaranteed to char ‘\u0000’ (null)
get a default value even
if you don’t initialize it. byte (byte)0

• Not true for those local short (short)0


variables!! int 0
– There will be compile
long 0L
error if you use it without
initialization float 0.0f
double 0.0d
String (+) Operator
String Concatenation

"Now is " + "the time."

"Now is the time."


String (+) Operator
Automatic Conversion to a String

expression_1 + expression_2

If either expression_1 or expression_2 evaluates


to a string the other will be converted to a string
if needed. The result will be their concatenation.
String (+) Operator
Automatic Conversion with Primitives

"The number is " + 4

"The number is " + "4"

"The number is 4"


Increment Operator
• i + + first use the value of i and then increment it by 1.
– ‘i + +’ equivalent to ‘i = (i)+1’. // postfix increment
• + + i first increment the value of i by 1 and then use it.
– ‘+ + i’ equivalent to ‘i = (i+1)’. // prefix increment
– int i=2;
• System.out.print(“ i = ”+ i++);//print 2, then i becomes 3
• System.out.print(“ i = ”+ ++i);//add 1 to i, then print 4
Decrement Operator
• i - - first use the i ’s value and then decrement it by one
• i - - equivalent to (i)-1. // postfix decrement
• - - i first decrement i ’s value by one and then use it.
• - - i equivalent to (i-1). // prefix decrement

• int i=5;
• System.out.print(“i = ” + i--);//print 5, then i becomes 4
• System.out.print(“i = ” + --i);//subtract 1 from i, then print 3
Relational Operator
• a < b a less than b. (true/false)
• a <= b a less than or equal b. (true/false)
• a > b a greater than b. (true/false)
• a >= b a greater than or equal to b. (true/false)
• These operations always return a boolean value.
• System.out.println(“23 is less than 65 ” +23<65); // true
• System.out.println(“5 is greater than or equal to 25.00?” +
5>=25.00); // false
Equality Operator
• a==b a equal to b. (true/false)
• a!=b a not equal to b. (true/false)

• boolean equal = 12 = = 150; // false

• boolean again_equal = ‘r’= = ‘r’); // true


• boolean not_equal = 53!=90); // true
Logical (&&) Operator Examples

public class Example {


public static void main(String[] args) {
boolean t = true;
boolean f = false;

System.out.println("f && f " + (f && f));


System.out.println("f && t " + (f && t));
System.out.println("t && f " + (t && f));
System.out.println("t && t " + (t && t));

}
}
> java Example
f && f false
f && t false
t && f false
t && t true
>
Logical (||) Operator Examples

public class Example {


public static void main(String[] args) {

boolean t = true;
boolean f = false;

System.out.println("f || f " + (f || f));


System.out.println("f || t " + (f || t));
System.out.println("t || f " + (t || f));
System.out.println("t || t " + (t || t));

}
}
> java Example
f || f false
f || t true
t || f true
t || t true
>
Logical (!) Operator Examples

public class Example {


public static void main(String[] args) {
boolean t = true;
boolean f = false;

System.out.println("!f " + !f);


System.out.println("!t " + !t);

}
}

> java Example


!f true
!t false
>
Logical Operators (Bit Level)
& | ^ ~

int a = 10; // 00001010 = 10


int b = 12; // 00001100 = 12

a 00000000000000000000000000001010 10
& b 00000000000000000000000000001100 12
AND a & b 00000000000000000000000000001000 8

| a
b
00000000000000000000000000001010
00000000000000000000000000001100
10
12
OR a | b 00000000000000000000000000001110 14

^ a
b
00000000000000000000000000001010
00000000000000000000000000001100
10
12
XOR a ^ b 00000000000000000000000000000110 6

~ a
~a
00000000000000000000000000001010
11111111111111111111111111110101
10
-11
NOT
Shift Operators (Bit Level)
<< >> >>>

• Shift Left << Fill with Zeros

• Shift Right >> Based on Sign

• Shift Right >>> Fill with Zeros


Shift Operators << >>
int a = 3; // ...00000011 = 3
int b = -4; // ...11111100 = -4

a 00000000000000000000000000000011 3
a << 2 00000000000000000000000000001100 12
<<
Left b 11111111111111111111111111111100 -4
b << 2 11111111111111111111111111110000 -16

a 00000000000000000000000000000011 3
a >> 2 00000000000000000000000000000000 0
>>
Right b 11111111111111111111111111111100 -4
b >> 2 11111111111111111111111111111111 -1
Shift Operator >>>
int a = 3; // ...00000011 = 3
int b = -4; // ...11111100 = -4

a 00000000000000000000000000000011 3

>>> a >>> 2 00000000000000000000000000000000 0

Right 0 b 11111111111111111111111111111100 -4
b >>> 2 00111111111111111111111111111111 +big
Shift Operator Examples
public class Example {
public static void main(String[] args) {
int a = 3; // ...00000011 = 3
int b = -4; // ...11111100 = -4

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


System.out.println("b<<2 = " + (b<<2));
System.out.println("a>>2 = " + (a>>2));
System.out.println("b>>2 = " + (b>>2));
System.out.println("a>>>2 = " + (a>>>2));
System.out.println("b>>>2 = " + (b>>>2));
}
}

> java Example


a<<2 = 12
b<<2 = -16
a>>2 = 0
b>>2 = -1
a>>>2 = 0
b>>>2 = 1073741823
>
Shift Operator >>> and
Automatic Arithmetic Promotion
byte a = 3; // 00000011 = 3
byte b = -4; // 11111100 = -4
byte c;
c = (byte) a >>> 2
c = (byte) b >>> 2

a 00000011 3
a >>> 2 00000000000000000000000000000000 0
c = (byte) 00000000 0
>>>
Right b 11111100 -4
Fill 0 b >>> 2 00111111111111111111111111111111 1073741823
c = (byte) Much to big for byte 11111111 -1
Algorithm
• An algorithm is a set of steps (rules) for solving a problem
in terms of:
actions to be executed
the order of actions execution
• We are using programming languages to specify the steps in
an algorithm
actions are called statements
the order of statement execution is called program
control
Flow of Control
• The order of statement execution in a program or method is
called the flow of control
• Some programming statements modify that order, allowing
us to:
• decide whether or not to execute a particular statement, or
• repeat a statement execution over and over

• These decisions are based on conditions in the program that


evaluates to true or false
Algorithm Constructs

• Sequence - only one step exists after


• Decision – More than one step exists
• Iteration – Want to perform a number of
steps again and again.
Selection (Decision Statement)
• An algorithm which is solely a sequence of
steps is extremely inflexible
• A ‘What if …? Then’ Statement allows for
this flexibility.
What if the coffee jar is empty?
Then get a new jar.
Iteration (Repetition or Loop)
• Sometimes it is necessary for the computer
not just to make a decision, but a continuous
action.
• This processes is called iteration.
Example : With the robot making the coffee
Continue finding coffee jar until jar is found.
Representation of Constructs
• Sequence: a single branch exists.
Representation of Constructs
• Decision: More than one branch exists.

False True
Condition?
Representation of Constructs
• Iteration: Repeat some steps.

Step 1

Step2

False
Condition
True
Control Statements

• Used to cause the flow of execution.

Control Statements

Selection Iteration Jump

• Branching • Looping • Jumping


• Execute a part of • Execute a part of • Execute a program in a
program with some program repeatedly with non-linear fashion.
condition some condition • Break, return, and
• Create different paths • while, for, and do-while continue
• If and switch statements statements
Selection Statements

• Single Selection
the if statement
• Double Selection
the if/else statement
nested if
• Multiple Selection
if-else -if ladder
the switch statement
Single Selection Statement

if ( booleanExpr )
statement; condition

• Example
– It is raining outside. Take your umbrella.
• Flowchart

true Take your


Raining? umbrella

false
Single Selection Statement
if ( countNumbers == 10 ) System.out.println( );

if ( grade >= 90 )
System.out.println( “You are an excellent student!” );

if ( account <= creditLimit )


System.out.pritnln( “You have insufficient credit!” );

if ( dayOfTheWeeek > 5 )
{
System.out.println( “Time to relax…” );
compound statement
System.out.println( “Weekend.”);
}

CSC 2310 (JAVA)


Double Selection Statement
if( booleanExpr )
statement1; condition
else
statement2;
• Example
– If you are hungry - go for lunch, otherwise take a cup of coffee.
• Flowchart

false true
Have coffee Hungry? Have lunch
Double Selection Statement
if ( dayOfTheWeek > 5 )
{
System.out.println( “Weekend.”);
System.out.println( “Time to relax…” );
}
else
{
System.out.println( “Workday.”);
System.out.println( “Go to work!” );
}
SCHOOL OF ENGINEERING & TECHNOLOGY
D E PA R T M E N T O F C O M P U T E R S C I E N C E A N D E N G I N E E R I N G

Nested if/else Statement


int a=325, b=712, c=478;
if ( a > b)
{
if ( a > c )
{
System.out.println(a);
}
else
{
System.out.println(c);
}
}
else
{
if( c > b)
{
System.out.println(c);
}
else
{
System.out.println(b);
}
Multiple Selection Statement(if-else-if ladder)

if( booleanExpr1 )
statement1;
else if ( booleanExpr2 ) condition
statement2;
else if ( booleanExpr3 )
statement3;



else
statement;
Multiple Selection Statement

char grade = ‘A’;


if ( grade == ‘A’)
System.out.println( “Excellent student”);
else if ( grade == ‘B’ )
System.out.println( “Good student”);
else if ( grade == ‘C’ )
System.out.println( “Average student”);
else if ( grade == ‘D’ )
System.out.println( “Bad student”);
else
System.out.println(“Failed student”);
Multiple Selection Statement

false false false


Expression1 Expression2 Expression N

true true true

statement1 statement2 statementN statement


Multiple Selection Statement (switch)

switch( booleanExpr)
{ condition
case value1:
statement1;
break;
case value2:
statement2;
break;



case value N;
statementN;
break;
default:
statement;
}
Switch Statement Execution

• First the expression is evaluated.


• The value of the expression is compared with the value in
the first case (value1). If they are equal, the statement1 is
executed.
• If they are not equal than the value of the expression is
compared with the value in the second case (value2). If they
are equal, the statement2 is executed and so on.
• If the value of the expression is not equal to any of the
values (in cases) the statement (the default case) is
executed.
• The next statement after the switch is executed.
Switch Statement Execution

false false false


Expression1 Expression2 ExpressionN default

true true true true

statement1 statement2 statementN statement

break break break break


Switch Statement Example
switch ( grade )
{
case ‘A’ : System.out.println( “Excellent student”);
break;
case ‘B’ : System.out.println( “Good student”)
break;
case ‘C’ : System.out.println( “Average student”);
break;
case ‘D’ : System.out.println( “Bad student”);
break;
default : System.out.println(“Failed student”);
break;
}
Looping Statements
• Repeatedly executes the same set of instructions until a termination
condition is met.

 while statement

 for statement

 do-while statement
while statement
while (Boolean Expression)
{
//body of loop (sequence of statements)
}
// summation from 1 to N
 Order of Execution i=1; s=0;
(1) while (i <= N)
{
s = s + i;
while (< Cond. Expr. >) ++i;
}

(2) True (3)


(4)
< Statement >
False
do-while statement
After executing the repeating statements, then check the
conditional expression
do{
//body of loop (sequence of statements)
} while (Boolean Expression);
 Order of Execution
do (1) Although the conditional expression
is false, execute the statement
< Statement > one time above at least
(2)
True

while (< Cond. Expr. >)

False (4)
for Statement

for(initialization; condition; iteration)


{
// body of loop
}
1 2

for ( < expr 1> ; <Expr2> ; <expr3>)

3 True 4

6 < Statement
>
False
for Statement variations

• More than one variable can be initialized at a time in the for


statement.
• Like the initialization section, the increment section may
also have more than one part.
• Test condition may have any compound relation.
• Specifically, this expression does not need to test the loop
control variable against some target value.
Jumping Statement

• Jump statements are used to transfer the control to another


part of your program
• Java supports three types of jumping statements:

• break statement
• continue statement
• return statement
break Statement
• To exit a single loop
While (BooleanExpr)
{
If(condition)
Break;
}

• To exit from nested loop


outer: for ( ; ; )
{
for( ; ; )
{
if (Condition)
break;
else
break outer;
}
}
continue Statement

• Used to skip a part of a loop for a particular iteration.


• continue works for single and outer loop skipping same as
break statement.

While ( test condition)


{ --------------
if (condition)
continue;
--------------
--------------
}
return Statement

• Used to explicitly return from a method.

• Causes program control to transfer back to the caller of the


method.
Int addition(int a, int b)
{
------------------------------
---------------------------------
return expression;
}
Exercise- 1

• WAP in Java to find whether a number is even or odd.


• WAP in Java to find the largest number.
• WAP in Java to find whether a number is prime or not.
• WAP in Java that prints first n prime number.
• WAP in Java to print the Fibonacci series upto n.
• WAP in Java to find the root of quadratic equation.
• WAP in Java that implements the arithmetic operation
(Calculator) using switch statement.
Arrays in Java
• An ordered collection of something, addressed by
integer index
– Something can be primitive values, objects, or even other
arrays. But all the values in an array must be of the same
type.
– Only int or char as index
– long values not allowed as array index
• 0 based
– Value indexes for array “a” with length 10
– a[0] – a[9];
• a.length==10
– Note: length is an attribute, not method
Arrays in Java: declaration
• Declaration
– int[] arr;
– Person[] persons;
– Also support: int arr[]; Person persons[];
(confusing, should be avoided)
• Creation
– int[] arr = new int[1024];
– int [][] arr = { {1,2,3}, {4,5,6} };
– Person[] persons = new Person[50];
Arrays in Java:

• second kind of reference types in Java


int[] arr = new int [5];
arr

int[][] arr = new int [2][5]; arr

arr[0]

arr[1]

You might also like