SlideShare a Scribd company logo
CS8392 - Object Oriented
Programming
Unit I
Introduction to OOP and Java Fundamentals
• Java is an Object-oriented, class-based, concurrent,
secured and general-purpose programming language.
• It is a widely used robust technology.
• Java is a platform.
– Platform: Any hardware or software environment in which
a program runs, is known as a platform.
– Since Java has a runtime environment (JRE) and API, it
is called a platform.
2
JAVA: Introduction
• Java initial work started in 1990 by Sun Microsystems engineer Patrick
Naughton as a part of the Stealth Project.
• The Stealth Project soon changed to the Green Project, with Mike Sheridan
and James Gosling joining the ranks, and the group began developing new
technology for programming next-generation smart appliances.
• James Gosling, Mike Sheridan, and Patrick Naughton initiated the Java
language project in June 1991.
• Gosling attempted to modify and extend C++ (a development he refers to as
"C++ ++ --"), but quickly abandoned this approach in favour of creating an
entirely new language.
• Firstly, it was called "Greentalk" by James Gosling, and file extension
was .gt. After that, it was called Oak, named after the tree that stood outside
his office. 3
JAVA: History
• Originally designed for small, embedded systems in electronic
appliances like set-top boxes. Then incorporate some changes based on
emergence of World Wide Web, which demanded portable programs.
• In 1995, Oak was renamed as "Java" because it was already a trademark
by Oak Technologies.
• The first publicly available version of Java (Java 1.0) was released in
1995.
• In 2006 Sun started to make Java available under the GNU General
Public License (GPL). Sun Microsystems was acquired by the Oracle
Corporation in 2010. Oracle continues this project called OpenJDK.
4
JAVA: History
Programming Popularity Java by Industry
5
JAVA: Why Java?
• 850 million PCs as Java Runtime Environment
• More then 3 billion devices run java
– Desktop Applications such as acrobat reader, media player,
antivirus etc.
– Web Applications
– Enterprise Applications such as banking applications.
– Mobile
– Web services
– Cloud
– Embedded System
– Smart Card
– Robotics
– Games etc.
6
JAVA: Where it is used?
7
JAVA: Version
8
C Vs C++ Vs JAVA
9
Java Editions
10
Java Editions
11
Characteristics of JAVA
12
Characteristics of JAVA
Simple
• Java is very easy to learn, and its syntax is simple, clean and
easy to understand.
– Java syntax is based on C++ (so easier for programmers to
learn it after C++).
– Java has removed many complicated and rarely-used
features, for example, explicit pointers, operator overloading,
etc.
– There is no need to remove unreferenced objects because
there is an Automatic Garbage Collection in Java.
13
Characteristics of JAVA
Object Oriented
• Java is an fully object-oriented programming language.
Everything in Java is an object.
• Object-oriented means we organize our software as a combination
of different types of objects that incorporates both data and
behaviour.
• It supports all the OOPs concepts.
Platform independent
• Java code can be run on multiple platforms, for example,
Windows, Linux, Sun Solaris, Mac/OS, etc. Java code is compiled
by the compiler and converted into bytecode or class file.
• This bytecode is a platform-independent code because it can be
run on multiple platforms, i.e., Write Once and Run
Anywhere(WORA).
14
Characteristics of JAVA
Secure:
• Java is secured because:
– No explicit pointer
– Java Programs run inside a virtual machine sandbox
Classloader:
• Classloader in Java is a part of the Java Runtime
Environment(JRE) which is used to load Java classes into the
Java Virtual Machine dynamically.
• It adds security by separating the package for the classes of
the local file system from those that are imported from network
sources.
15
Characteristics of JAVA
Secure
• Bytecode Verifier: It checks the code fragments for illegal
code that can violate access right to objects.
• Security Manager: It determines what resources a class can
access such as reading and writing to the local disk.
• Java language provides these securities by default. Some
security can also be provided by an application developer
explicitly through SSL, JAAS, Cryptography, etc.
16
Characteristics of JAVA
Robust
• Robust simply means strong.
Java is robust because:
• It uses strong memory management.
• There is a lack of pointers that avoids security problems.
• There is automatic garbage collection in java which runs on
the Java Virtual Machine to get rid of objects which are not
being used by a Java application anymore.
• There are exception handling and the type checking
mechanism in Java. All these points make Java robust.
17
Characteristics of JAVA
Architecture Neutral
• Java is architecture neutral because there are no
implementation dependent features, for example, the size of
primitive types is fixed.
• In C programming, int data type occupies 2 bytes of memory
for 32-bit architecture and 4 bytes of memory for 64-bit
architecture.
• However, it occupies 4 bytes of memory for both 32 and 64-
bit architectures in Java.
18
Characteristics of JAVA
Portable
• Java is portable because it facilitates you to carry the Java
bytecode to any platform. It doesn't require any implementation.
High-Performance
• Java is a little bit slower than a compiled language (e.g., C++).
Java is an compiled and interpreted language that is why it is
slower than compiled languages, e.g., C, C++, etc.
• But with the use of Just-In-Time compilers, Java enables high
performance than C, C++, etc.
19
Characteristics of JAVA
Distributed
• Java is distributed because it facilitates users to create distributed
applications in Java.
• RMI and EJB are used for creating distributed applications.
• This feature of Java makes us able to access files by calling the
methods from any machine on the internet.
Dynamic
• Java is a dynamic language. It supports dynamic loading of classes.
• It means classes are loaded on demand. It also supports functions from
its native languages, i.e., C and C++.
• Java supports dynamic compilation and automatic memory
management (garbage collection).
20
Characteristics of JAVA
Multi-threaded
• A thread is like a separate program, executing concurrently.
• We can write Java programs that deal with many tasks at once
by defining multiple threads.
• The main advantage of multi-threading is that it doesn't occupy
memory for each thread.
• It shares a common memory area. Threads are important for
multi-media, Web applications, etc.
• For executing any java program, you need to Install the JDK if
you don't have installed it, download the JDK and install it.
– https://www.oracle.com/technetwork/java/javase/downloads/index.html
• Create the java program using any editor like notepad, notepad++
and save with file extension .java.
‑ Ex: Simple.java
21
First Java Program
/** First Java Program **/
import java.io.*;
public class Simple
{
public static void main (String args[])
{
System.out.println(“Hello Worldn”);
} //end main
}//end class
22
First Java Program
• The path is required to be set for using tools such as javac, java, etc.
• If you are saving the Java source file inside the JDK/bin directory, the
path is not required to be set because all the tools will be available in the
current directory.
• However, if you have your Java file outside the JDK/bin folder, it is
necessary to set the path of JDK.
• There are two ways to set the path in java:
• Temporary
• In Comment Prompt
• set path= C:Program FilesJavajdk1.8.0_191bin
• Permanent
• Set Path using Environmental Variables option
First Java Program
• To compile
– javac Simple.java
• To run
– java Simple
23
To compile and run a java program
24
First Java Program: Compilation & Execution
• JDK = Java Runtime Environment (JRE) + Development
Tools
• JRE = Java Virtual Machine (JVM) + Library Classes
• JVM=Java Interpreter + Just-In-Time Compiler
25
JDK vs JRE vs JVM
• JDK stands for “Java Development Kit”.
• It is a software development environment used for
developing Java applications and applets.
• It includes the Java Runtime Environment (JRE), an
interpreter/loader (Java), a compiler (javac), an archiver (jar),
a documentation generator (Javadoc) and other tools needed in
Java development.
26
JDK: Java Development Kit
• JRE stands for “Java Runtime Environment” and may also
be written as “Java RTE.”
• The Java Runtime Environment provides the minimum
requirements for executing a Java application;
• it consists of the Java Virtual Machine (JVM), core classes,
and supporting files.
27
JRE: Java Runtime Environment
• JVM
– Java Interpreter + Just-In-Time Compiler
– JVM (Java Virtual Machine) is an abstract machine. It is a
specification that provides runtime environment in which
java byte code can be executed.
– JVMs are available for many hardware and software
platforms. It is the code execution component of the Java
platform.
– It is a Runtime Instance Whenever you write java
command on the command prompt to run the java class, an
instance of JVM is created.
• Note:
– JVM, JRE and JDK are platform dependent because
configuration of each OS differs. But, Java is platform
independent.
28
JVM: Java Virtual Machine
29
Need for JVM
• The Java Virtual Machine is a program whose purpose is to execute
other programs.
• The JVM has two primary functions:
₋ to allow Java programs to run on any device or operating system
(known as the "Write once, run anywhere" principle)
₋ to manage and optimize program memory.
• Each operating system has different JVM, however the output they
produce after execution of byte code is same across all operating
systems.
• Bytecode: Byte code is the set of optimized instructions generated
during compilation phase and it is more powerful than ordinary pointer
code.
30
JDK vs JRE vs JVM
JVM JDK JRE
It stands for Java Virtual
machine.
It stands for Java
Development Kit
It stands for Java
Runtime Environment
It is an abstract machine.
It is a specification that
provides a run-time
environment in which
java byte code can be
executed.
It is the tool necessary to
compile, document and
package java programs.
JRE refers to a runtime
environment in which
java byte code can be
executed.
JVM follows three
notation: Specification,
Implementation and
Runtime instance
It contains JRE +
development tools.
It is an implementation
of the JVM which
physically exists.
31
JVM Architecture
32
JVM Architecture
• Class Loader: The class loader reads the .class file and save
the byte code in the method area.
• Method Area: There is only one method area in a JVM
which is shared among all the classes. This holds the class
level information of each .class file.
• Heap: Heap is a part of JVM memory where objects are
allocated. JVM creates a Class object for each .class file.
• Stack: Stack is a also a part of JVM memory but unlike
Heap, it is used for storing temporary variables.
33
JVM Architecture
• PC Registers: This keeps the track of which instruction has been
executed and which one is going to be executed. Since instructions
are executed by threads, each thread has a separate PC register.
• Native Method stack: A native method can access the runtime data
areas of the virtual machine.
• Native Method interface: It enables java code to call or be called
by native applications. Native applications are programs that are
specific to the hardware and OS of a system.
• Garbage collection: A class instance is explicitly created by the
java code and after use it is automatically destroyed by garbage
collection for memory management.
34
JIT: Just In Time Compiler
• The Just-In-Time compiler is one of the integral parts of the Java
Runtime Environment.
• It is mainly responsible for performance optimization of Java-based
applications at run time or execution time.
35
JIT: Just In Time Compiler
Step:1
• When you code the Java Program, JRE uses javac compiler to
compile the high-level Source code to byte code.
• After this, JVM loads the byte code at run time and converts
into machine level binary code for further execution using
Interpreter.
Step:2
• Interpretation of Java byte code reduces the performance
when compared to a native application i.e JIT Compiler aids to
boost up the performance by compiling the byte code into
native machine code “just-in-time” to run.
36
JIT: Just In Time Compiler
Step:3
• The JIT Compiler is activated and enabled by default when
a method is invoked in Java.
• When a method is compiled, Java Virtual Machine invokes the
compiled code of the method directly without interpreting it.
• Hence, it does not require much memory usage and
processor time. That basically speeds up the performance of
the Java Native Application.
37
First Java Program
/** First Java Program **/
import java.io.*;
public class Simple
{
public static void main (String args[])
{
System.out.println(“Hello Worldn”);
} //end main
}//end class
Question and Answer
38
Java: Data Types
Is necessary main class is public in java?
• To compile a program, you doesn’t really need a main method in your program.
But, while execution JVM searches for the main method. In the Java the main
method is the entry point Whenever you execute a program in Java JVM
searches for the main method and starts executing from it.
• The main method must be public, static, with return type void, and a String
array as argument.
public static void main(String[] args)
• You can write a program without defining a main it gets compiled without
compilation errors. But when you execute it a run time error is generated saying
“Main method not found”.
Question and Answer
39
Java: Data Types
Is necessary main class name should be same as filename?
• The filename must have the same name as the public class name in that file,
which is the way to tell the JVM that this is an entry point.
• Suppose when we create a program in which more than one class resides
and after compiling a java source file, it will generate the same number of
the .class file as classes reside in our program. In this condition, we will not
able to easily identify which class need to interpret by java interpreter and
which class containing Entry point for the program.
Question and Answer
40
Java: Data Types
Why java main method is static and public?
• Java program's main method has to be declared static because keyword
static allows main to be called without creating an object of the class in
which the main method is defined. If we omit static keyword before main
Java program will successfully compile but it won't execute.
41
First Java Program
• Access modifiers (or access specifiers) are keywords in
object oriented languages that
‑ set the accessibility of classes,
methods, and other members.
• Access modifiers are a specific part of programming language
syntax used to facilitate the encapsulation of components.
42
Java: Access Modifiers
43
Java: Access Modifiers
44
First Java Program
• public keyword is an access modifier which represents visibility. It means it is
visible to all.
• class keyword is used to declare a class in java. (Here, Simple is a class name)
• static is a keyword. If we declare any method as static, it is known as the static
method.
– The core advantage of static method is that there is no need to create object
to invoke the static method.
– The main method is executed by the JVM, so it doesn't require to create
object to invoke the main method. So it saves memory.
/** First Java Program **/
import java.io.*;
public class Simple
{
public static void main (String args[])
{
System.out.println(“Hello World
n”);
} //end main
45
First Java Program
• void is the return type of the method. It means it doesn't return any value.
• main represents the starting point of the program.
• String[] args is used for command line argument.
• System.out.println() is used to print statement.
/** First Java Program **/
import java.io.*;
public class Simple
{
public static void main (String args[])
{
System.out.println(“Hello World
n”);
} //end main
}//end class
• A token is the smallest element of a program that is
meaningful to the compiler.
• Tokens can be classified as follows:
‑ Keywords
‑ Identifiers
‑ Constants / Literals
‑ Special Symbols
‑ Operators
46
Java: Tokens
47
Java: Keywords
• Keywords are terms or phrases appropriated for special use that
may not be utilized in the creation of variable names.
₋ For example, “while" is a reserved word because it is a function in
many languages to show text on the screen.
• Keywords are also known as Reserved words
48
Java: Identifiers
• Identifiers are used for identification purposes.
• An identifier is the name given by the user for the various
programming elements like variables, functions, arrays,
structure, class and file.
Rules for defining an identifier
• The only allowed characters for identifiers are all alphanumeric
characters([A-Z],[a-z],[0-9]), ‘$‘(dollar) and ‘_‘ (underscore).
• Identifiers should not start with digits([0-9]).
– For example “123geeks” is a not a valid identifier.
• Java identifiers are case-sensitive.
• There is no limit on the length of the identifier but it is advisable
to use an optimum length of 4 – 15 letters only.
• Reserved Words can’t be used as an identifier.
– For example “int while = 20;” is an invalid statement as while is a
reserved word. There are 53 reserved words in Java.
49
Java: Data Types
• Data types define the type of data a variable can hold
• For example an integer variable can hold integer data, a
character type variable can hold character data etc.
50
Java: Data Types
Question and Answer
51
Java: Data Types
Why is the size of char is 2 byte in java..?
• In other languages like C/C++ uses only ASCII characters and to represent all
ASCII characters 8-bits is enough,
• But java uses Unicode system not ASCII code system and to represent
Unicode system 8 bit is not enough to represent all characters so java uses 2
byte for characters.
Why Java is a statically typed language?
• Java is statically typed and also a strongly typed language because in Java, each
type of data (such as integer, character, hexadecimal, packed decimal, and so
forth) is predefined as part of the programming language and all constants
or variables defined for a given program must be described with one of the
data types.
52
Java: Variables
Variable:
• A variable is a container which holds the value while the Java
program is executed.
• The variable's name represents what information
the variable contains.
• A variable is defined by the combination of an identifier, a type,
and an optional initializer.
Example:
int age=20;
string name=“hello”;
Java: Variables
Types of variables
– Local Variable
– Instance Variable or Non-static Variable
– Static Variable
Local Variable
• Local variables are declared within a method or within a block
of code in a method.
• In general, a local variable is accessible from its declaration to
the end of the code block in which it was declared.
• A local variable cannot be defined with "static" keyword.
53
Instance Variable or Non-static variable
• A variable declared inside the class but outside the body of the
method, is called instance variable. Instance variables are defined
without the STATIC keyword .
• Instance variables are created when the objects are instantiated and
therefore they are associated with the objects.
Static Variable
• A variable which is declared as static is called static variable. It
cannot be local.
• You can create a single copy of static variable and share among all
the instances of the class. Memory allocation for static variable
happens only once when the class is loaded in the memory. 54
Java: Variables
Example:
class A
{
int data=50;//instance variable
static int m=100;//static variable
void method()
{
int n=90;//local variable
}
}//end of class 55
Java: Variables
Literal :
• Any constant value which can be assigned to the variable is
called as literal/constant.
Example
• boolean result = true;
• char capitalC = 'C';
• byte b = 100;
• short s = 10000;
• int i = 100000; 56
Java: Literals
Using Underscore Characters in Numeric Literals
• In Java SE 7 and later, any number of underscore characters (_)
can appear anywhere between digits in a numerical literal.
• This feature enables you, for example. to separate groups of digits
in numeric literals, which can improve the readability of your
code.
• Example
• long creditCardNumber = 1234_5678_9012_3456L;
• long socialSecurityNumber = 999_99_9999L;
• float pi = 3.14_15F;
• long bytes = 0b11010010_01101001_10010100_10010010;
• You can place underscores only between digits; you cannot place
underscores in the following places:
• At the beginning or end of a number
• Adjacent to a decimal point in a floating point literal
• Prior to an F or L suffix
• In positions where a string of digits is expected 57
Java: Literals
What is the difference between character literals and string
literals in Java?
• Character literals represents alphabets (both cases), numbers (0
to 9), special characters (@, ?, & etc.) and escape sequences
like n, b etc.
• The String literal represents objects of String class.
58
Java: Literals
Question and Answer
• Special symbols in Java are a few characters which have
special meaning known to Java compiler and cannot be used
for any other purpose.
59
Java: Special Symbols
Symbol Description
Brackets []
These are used as an array element reference and also
indicates single and multidimensional subscripts
Parentheses()
These indicate a function call along with function
parameters
Braces{}
The opening and ending curly braces indicate the
beginning and end of a block of code having more than
one statement
Comma ( , )
This helps in separating more than one statement in an
expression
Semi-Colon (;) This is used to invoke an initialization list
Asterisk (*) This is used to create a pointer variable in Java
Write a Java program
5.1 To print an int, a double and a char variable on screen.
5.2 To print the area of a rectangle of sides 2 and 3 units
respectively.
5.3 To print the product of the numbers 8.2 and 6.
5.4 Print the ASCII value of the character 'h'.
60
Java: Datatypes
Exercise:5
• Operator in Java is a symbol which is used to perform
operations. For example: +, -, *, / etc. There are many types of
operators in Java which are given below:
₋ Unary Operator,
₋ Arithmetic Operator,
₋ Shift Operator,
₋ Relational Operator,
₋ Bitwise Operator,
₋ Logical Operator,
₋ Ternary Operator and
₋ Assignment Operator. 61
Java: Operators
62
Java: Operators
6.1 Length and breadth of a rectangle are 5 and 7 respectively. Write a
program to calculate the area and perimeter of the rectangle.
6.2 Write a program to calculate the perimeter of a triangle having sides of
length 2,3 and 5 units.
6.3 Write a program to add 8 to the number 2345 and then divide it by 3.
Now, the modulus of the quotient is taken with 5 and then multiply the
resultant value by 5. Display the final result.
1. Now, solve the above question using assignment operators (eg.
+=, -=, *=).
6.4 Write a program to print the power of 7 raised to 5. 63
Java: Operators
Exercise:6
• The Java comments are the statements that are not executed by
the compiler and interpreter.
• The comments can be used to provide information or
explanation about the variable, method, class or any
statement.
64
Java: Comments
Single line comment
• This type of comment is mainly used for describing the code
functionality. It is the easiest typed comments.
• Single-line comments start with two forward slashes (//). Any
text between // and the end of the line is ignored by Java implies
it will not be executed.
• The single line comment is used to comment only one line.
Syntax:
//Comments here(Text in this line will be considered as comment)
Example:
//my first comment 65
Basic Java: Comments
Java: Comments
Syntax:
/*Comment starts
Continues
…….
Comment ends*/
Example:
/* This is the beginning of a
multi-line comment
this is the end */
66
Multi line comment
• To describe a full method in a code or a complex snippet
single line comments can be tedious to write since we have to
give ‘//’ at every line.
• So to overcome this multi-line comments can be used. Multi-
line comments start with /* and end with */.
• Any text between /* and */ will be ignored by Java. It is used
to comment multiple lines of code.
Java: Comments
Syntax:
/**Comment start
*
*tags are used in order to specify
a parameter
*or method or heading
*HTML tags can also be used
*such as <h1>
*comment ends*/
Example:
67
Java Documentation Comment
• This type of comments is used generally when you are writing code for
a project/ software package.
• It helps you to generate a documentation page for reference, which
can be used for getting information about methods present, its
parameters, etc.
• The documentation comment is used to create documentation API. To
create documentation API, you need to use Javadoc tool.
Tag Author Descritpion
@author Adds the author of a class. @author name-text
@exception
Adds a Throws subheading
to the generated
documentation, with the
classname and description
text.
@exception class-
name description
@return
Adds a “Returns” section
with the description text.
@return
description
• Casting is a process of changing one type of value to another
type. In Java, we can cast one type of value to another type. It is
known as type casting.
• When you assign the value of one data type to another, you
should be aware of the compatibility of the data type.
• If they are compatible, then Java will perform the conversion
automatically known as Automatic Type Conversion and if not,
then they need to be casted or converted explicitly.
• Types of casting
– Automatic or Implicit or widening
– Explicit or Narrowing 68
Java: Type Casting
Automatic or Implicit or Widening:
Automatic Type casting take place when,
– the two types are compatible
– the target type is larger than the source type
Note:
• In java the numeric data types are compatible with each other
but no automatic conversion is supported from numeric type
to char or boolean. Also, char and boolean are not compatible
with each other.
Example: Auto_Conversion.java 69
Java: Type Casting
Explicit or Narrowing:
• When you are assigning a larger type value to a variable of
smaller type, then you need to perform explicit type casting.
• This is useful for incompatible data types where automatic
conversion cannot be done.
• Here, target-type specifies the desired type to convert the
specified value to.
Example: Demo_Narrow.java,Narrowing.java 70
Java: Type Casting
Write a Java program
7.1 To assign a value of 100.235 to a double variable and then convert
it to int.
7.2 To add 3 to the ASCII value of the character 'd' and print the
equivalent character.
7.3 To add an integer variable having value 5 and a double variable
having value 6.2.
71
Java: Type Casting
Exercise:7
72
Java: Read input from console
• Java Scanner class allows the user to take input from the
console. It belongs to java.util package.
• It is used to read the input of primitive types like int, double,
long, short, float, and byte.
• It is the easiest way to read input in Java program.
• To create an object of Scanner class, we usually pass the
predefined object System.in, which represents the standard input
stream. We may pass an object of class File if we want to read
input from a file.
73
Java: Read input from console
• To read numerical values of a certain data type XYZ, the function
to use is nextXYZ().
– For example, to read a value of type short, we can use nextShort()
• To read strings, we use nextLine() or next().
• To read a single character, we use next().charAt(0). next()
function returns the next token/word in the input as a string and
charAt(0) funtion returns the first character in that string.
Example: Getinputfromuser.java, Demochar.java 74
Java: Read input from console
75
Java: Read input from console
Example:
Write a Java program
8.1 That accepts two integer inputs from user and print sum and
product of them.
8.2 That takes name, roll number and field of interest from user and
print in the format below :
Output: Hey, my name is xyz and my roll number is xyz. My field of
interest are xyz.
8.3 To find square of a number.
Test Cases: Input : 2 Output : 4
Input : 5 Output : 25
76
Java: Read input from console
Exercise:8
• A programming language uses control statements to control the
flow of execution of program based on certain conditions.
77
Java: Control Statements
• In Java, if statement is used for testing the conditions.
• The condition matches the statement it returns true else it returns
false.
• There are four types of if statement they are:
₋ if statement
₋ if-else statement
₋ if-else-if ladder
₋ nested if statement
₋ Switch statement
78
Java: Selection Statements
• if statement tests the condition. It executes the if block if
condition is true.
• Syntax: Example: IfDemo1.java
if(condition)
{
//code to be executed
}
79
Selection Statements :Simple if
Practice:
Write Java program for the following
problem:
1. To check the entered mark is pass (if
it is greater than 40).
2. To check whether given number is
divisor of 7.
Flowchart
• if-else statement also tests the condition. It executes the if block
if condition is true else if it is false the else block is executed.
• Syntax: Example: IfElseDemo1.java
if(condition){
//code for true
}
else{
//code for false
}
80
Selection Statements :if-else
Practice:
Write Java program for the following problem:
1. To find the greatest of two numbers.
2. To check whether the given number is odd
or even.
3. To check whether the given year is leap year
or not.
4. To check whether the given age is valid for
vote or not.
Flowchart
• The if-else-if ladder statement is used for testing conditions. It is
used for testing one condition from multiple statements.
• Syntax: Example: IfElseIFDemo1.java
if(condition1)
{
//code for if condition1 is true
}
else if(condition2)
{
//code for if condition2 is true
}
...
else
{
//code for all the false conditions
}
81
Selection Statements :if-else-if
Flowchart
82
Selection Statements :if-else-if
Practice:
Write Java program for the following problem:
1. To find the largest of three numbers
2. To Check whether the given Character is a
Vowel /Consonant /Digit /Special Symbol.
3. To input basic salary of an employee and calculate
gross salary according to given conditions.
Basic Salary <= 10000 : HRA = 20%, DA = 80%
Basic Salary is between 10001 to 20000 : HRA =
25%, DA = 90%
Basic Salary >= 20001 : HRA = 30%, DA = 95%
Gross Salary=Basic Salary + HRA + DA
• Nested if-else statements, is that using one if or else if statement
inside another if or else if statement(s).
• Syntax: Example: NestedIfDemo1.java
if(condition)
{
if(condition)
{
//statement
}
else
{
//statement
}
…
}
else
{
//statement 83
Selection Statements : Nested if
Flowchart
84
Selection Statements : Nested if
Practice:
Write Java program for the following problem:
1. To Read a Coordinate Point in a XY Coordinate
System and Determine its Quadrant.
2. To find the greatest of three numbers.
• In Java, the if..else..if ladder executes a block of code among
many blocks.
• The switch statement can be a substitute for
long if..else..if ladders which generally makes your code more
readable.
• It's also important to note that switch statement in Java only works
with:
– Primitive data types: byte, short, char and int
– Enumerated types (Java enums)
– String class
– a few classes that wrap primitive types: Character, Byte, Short &
Integer
85
Selection Statements: Switch
Syntax: Flowchart
switch(expression)
{
case value1:
//code for execution;
break; //optional
case value2:
// code for execution
break; //optional
......
Case value n:
// code for execution
break; //optional
default:
//code for execution
when none of the case is true;
}
Example:SwitchDemo1.java
86
Selection Statements: Switch
Practice:
Write Java program for the following
problem:
1. To Check the given Character is a
Vowel.
2. Simple Calculator (Try both integer
(1,2,3) and character(+, -, *, /, %) as a
case in separate program)
Write a Java program
9.1Write a program to calculate the monthly telephone bills as per the
following rule:
Minimum Rs. 200 for up to 100 calls.
Plus Rs. 0.60 per call for next 50 calls.
Plus Rs. 0.50 per call for next 50 calls.
Plus Rs. 0.40 per call for any call beyond 200 calls.
9.2 Write a program that asks the user to enter a number and displays
the absolute value of that number. 87
Selection Statements
Exercise:9
9.3 A triangle is valid if the sum of all the three angles is equal to 180
degrees. Write a program that asks the user to enter three integers as
angles and check whether a triangle is valid or not.
9.4 Write a program that prompts the user to enter grade. Your program
should display the corresponding meaning of grade as per the
following table
88
Selection Statements
Exercise:9
Grade Meaning
A Excellent
B Good
C Average
D Deficient
F Failing
• In programming languages, loops are used to execute a set of
instructions/functions repeatedly when some conditions become
true.
• There are three types of loops in java.
89
Java: Iterative Statements
• In java, while loop is used for iterating a part of the program
several times. When the number of iteration is not fixed then
while loop is used.
• Syntax: Example:
WhileDemo1.java
while(condition)
{
//code for execution
}
90
Iterative Statements: while
Practice:
Write Java program for the following
problem:
1. Rectangle number pattern.
2. To check the number is palindrome.
Flowchart
• In java, do-while loop is used to execute a part of the program
again and again. If the number of iteration is not fixed then the
do-while loop is used. This loop executes at least once because
the loop is executed before the condition is checked.
• Syntax: Example:
WhileDemo1.java
do
{
//code for execution
}while(condition);
91
Iterative Statements: do-while
Practice:
Write Java program for the following
problem:
1. To print the numbers from 10 to 1.
2. Sum of ‘n’ natural numbers.
Flowchart
• In java, for loop is used for executing a part of the program
again and again. When the number of execution is fixed
then it is suggested to use for loop.
• In java there are 2 types of for loops, they are as follows:
₋ Simple for loop
₋ For-each loop
92
Iterative Statements: for
Syntax:
for(initialization;condition;increment/decrement)
{
//statement
}
Example: ForDemo1.java
93
Iterative Statements: for
Flowchart
Practice:
Write Java program for the following
problems:
1. To print numbers from 1 to 10.
2. To find the factorial
3. To calculate the sum of following
series where n is input by user.
1 + 1/2 + 1/3 + 1/4 + 1/5 +…………1/n
• Nested Loop: A loop inside another loop is called a nested loop.
The number of loops depend on the complexity of a problem.
• Suppose, a loop, outer loop, running n number of times consists
of another loop inside it, inner loop, running m number of times.
Then, for each execution of the outer loop from 1...n, the inner
loop runs maximum of m times.
• Syntax:
Example: PyramidExample.java, Pattern.java
94
Iterative Statements: Nested Loop
• In Java, a break statement is used inside a loop. The loop is
terminated immediately when a break statement is encountered
and resumes from the next statement.
Syntax: Flowchart:
break;
Example: BreakDemo1.java
95
Jump Statements: Break
Practice:
Write Java program for the
following problem:
The sum of numbers entered by
the user until user enters a
negative number.
• In Java, the Continue statement is used in loops. Continue
statement is used to jump to the next iteration of the loop
immediately. It is used with for loop, while loop and do-while
loop.
Syntax: Example:ContinueDemo1.java
continue; Flowchart:
96
Jump Statements: Continue
Practice:
Write Java program for the
following problem:
The sum of numbers entered by the
user until user enters a negative
number.
• In Labelled Break Statement, we give a label/name to a loop.
• When this break statement is encountered with the label/name of
the loop, it skips the execution any statement after it and takes the
control right out of this labelled loop.
• The control goes to the first statement right after the loop.
Example:LabelledBreak.java,LabelledBreak1.java
97
Jump Statements: labelled break
• In Labelled Continue Statement, we give a label/name to a
loop.
• When this continue statement is encountered with the label/name
of the loop, it skips the execution any statement within the loop
for the current iteration and continues with the next iteration and
condition checking in the labelled loop.
Example: LabelledContinue.java
98
Jump Statements: labelled Continue
Write a Java program
10.1 To check the number is prime or not.
10.2 Guess the integer.
10.3 To enter the numbers till the user wants and at the end it should
display the count of positive, negative and zeros entered.
99
Java: Control Statements
Exercise:10
Write a Java program
10.4 To print the right angular triangle pattern.
10.5 To write the even numbers from 10 to 20, both
included, except 16, in 3 different ways:
- Incrementing 2 in each step (use "continue" to skip 16)
- Incrementing 1 in each step (use "continue")
- With and endless loop (using "break" & "continue")
100
Java: Control Statements
Exercise:10
• Array is a collection of similar type of elements that have
contiguous memory location.
• In Java all arrays are dynamically allocated. Since arrays are
objects in Java, we can find their length using member length.
• A Java array variable can also be declared like other variables
with [] after the data type.
• The variables in the array are ordered and each have an index
beginning from 0.
• Java array can be also be used as a static field, a local variable or
a method parameter. 101
Java: Arrays
Advantages
• Code Optimization: It makes the code optimized, we can
retrieve or sort the data efficiently.
• Random access: We can get any data located at an index
position.
Disadvantages
• Size Limit: We can store only the fixed size of elements in the
array. It doesn't grow its size at runtime.
– To solve this problem, collection framework is used in Java
which grows automatically.
102
Java: Arrays
Types of Array
There are two types of array.
Single Dimensional Array: An array is a group of like-typed
variables that are referred to by a common name.
Syntax: datatype variable_name[]; or datatype[] variable_name;
Multidimensional Array: An array of more than one dimension is
known as a multi-dimensional array.
Syntax: datatype array_name[][]=new int [][];
datatype [][] array_name=new int[][];
Example:Testarray.java,Testarray1.java,Testarray3.java,Testarray5.java,
Testarray11.java,MatrixMultiplicationExample.java
103
Java: Arrays
• Arrays -> Specified in java.util.Arrays Package
• Arrays is a class which contain following methods
– Arrays.toString({ArrayVariable});
– Arrays.copyOf({Array Variable},Length to be copied);
– Arrays.copyOfRange({Array Variable}, int from, int to);
– Arrays.equals({Array Variable x}, {Array Variable y});
– Arrays.sort({ArrayVariable}); 104
Java: Arrays
How to access an array element in java?
• Each variable in an Java array is also called an "element". Each
element in the array has an index (a number). You can access each
element in the array via its index.
• Syntax: datatype arrayname[index_value];
What happens if we try to access element outside the array size?
• JVM throws ArrayIndexOutOfBoundsException to indicate that
array has been accessed with an illegal index. The index is either
negative or greater than or equal to size of array.
105
Java: Arrays
Question and Answer
Jagged Arrays:
• It is an array of arrays where each element is, in turn, an array. A special
feature of this type of array is that it is a Multidimensional array whose
each element can have different sizes.
Purpose of jagged arrays:
• Jagged arrays are a special type of arrays that can be used to store rows
of data of varying lengths to improve performance when working with
multi-dimensional arrays. An array may be defined as a sequential
collection of elements of the same data type.
Example:TestJaggedArray.java 106
Java: Arrays
Write a Java program
11.1 To sum values of an array.
11.2 To find the maximum and minimum value of an array
11.3 To remove a specific element from an array.
11.4 To find the sum of two matrices.
11.5 To print the following grid.
- - - - - - - - - -
- - - - - - - - - -
107
Java: Arrays
Exercise:11
108
Quiz
1) Which of the following option leads to the portability and
security of Java?
2) Which of the following is not a Java features?
d) Dynamic binding between
objects
c) Use of exception handling
a) Byte code is executed by
JVM
b) The applet makes the Java
code secure and portable
Answer : Option a)
QUIZ
a) Dynamic b) Architecture Neutral
c) Use of pointers d) Object-oriented
Answer : Option c)
109
Quiz
3) _____ is used to find and fix bugs in the Java programs.
4) What does the expression float a = 35 / 0 return?
d) JDB
c) JDK
a) JVM b) JRE
Answer : Option d)
QUIZ
d) Run time exception
c) Infinity
a) 0 b) Not a Number
Answer : Option c)
110
Quiz
5) Evaluate the following Java expression, if x=3, y=5, and z=10: +
+z + y - y + z + x++
6)Which of the following tool is used to generate API
documentation in HTML format from doc comments in source
code?
Answer : Option a)
d) 25
c) 20
a) 24 b) 23
QUIZ
d) javah command
c) Javadoc tool
a) javap tool b) javaw command
Answer : Option c)
111
Quiz
7) Which method of the Class.class is used to determine the
name of a class represented by the class object as a String?
8) Which keyword is used for accessing the features of a
package?
d) toString()
c) getName()
a) getClass() b) intern()
Answer : Option c)
QUIZ
d) Export
c) extends
a) package b) import
Answer : Option b)
112
Quiz
9) What will be the output of the following program?
public class Test
{
public static void main(String[] args)
{
int count = 1;
while (count <= 15)
{
System.out.println(count % 2 == 1 ? "***" : "+++++");
++count;
}
} }
d) Both will print only once
c) 8 times *** and 7 times +++++
a) 15 times *** b) 15 times +++++
Answer : Option c)
QUIZ
113
Quiz
10) Which of the following for loop declaration is not valid?
d) for ( int i = 2; i <= 20; i = 2*
i )
c) for ( int i = 20; i >= 2; - -i )
a) for ( int i = 99; i >= 0; i / 9 )
b) for ( int i = 7; i <= 77; i += 7 )
Answer : Option a)
QUIZ
Possible questions: 2 Marks
1. What is Java?
2. What are the differences between C++ and Java?
3. List the features of Java Programming language.
4. Compare JDK,JRE and JVM.
5. What is JIT compiler?
6. What gives Java its 'write once and run anywhere' nature?
7. Is Empty .java file name a valid source file name?
8. What is the difference between double and float variables in
Java?
9. What if I write static public void instead of public static void?
114
Introduction to Java
Possible questions:2 Marks
10. What is the purpose of identifier in programming language?
11. Define keyword.
12. List the rules for defining an identifier.
13. What is the advantage of Unicode in Java?
14. Define operator and its types.
15. Differentiate while and do..while loop.
16. What is the difference between continue and break statement?
17. Define array and its types.
18. What is the purpose of jagged array?
19. Define strings.
20. How can we create a string in java? 115
Introduction to Java
Possible questions:
16 Marks:
1. Discuss the characteristics of java in detail.
2. Explain different types of operators involved in Java.
3. Discuss control statements in detail with its types.
4. Explain the advantage of labeled break and labeled continue.
5. Explain Jagged array with example.
6. What is array? Discuss its types with example.
7. Explain at least 5 array related inbuilt methods with example.
116
Introduction to Java
Anna University Questions:
2 marks:
1. Can a Java source file be saved using a name other than the class
name? Justify.(Apr/May 2018)
16 marks:
Apr/May 2019
2. What are literals? Explain the types of literals supported by java.(6)
3. Explain the selection statements in java with suitable examples.(7)
4. Write a Java code using do-while loop that counts down to 1 from 10
printing exactly ten lines of “hello”.(6)
117
Introduction to Java

More Related Content

PPTX
JAVAPart1_BasicIntroduction.pptx
Murugesh33
 
PPTX
JAVA_Day1_BasicIntroduction.pptx
Murugesh33
 
PPTX
JAVA PROGRAM CONSTRUCTS OR LANGUAGE BASICS.pptx
AALIM MUHAMMED SALEGH COLLEGE OF ENGINEERING
 
PPTX
java basics concepts and the keywords needed
PriyadharshiniG41
 
PPTX
Java Introduction
sunmitraeducation
 
PPT
Introduction to Core Java feature and its characteristics
rashmishekhar81
 
PPTX
Introduction to java
Java Lover
 
PPTX
JAVA-History-buzzwords-JVM_architecture.pptx
20EUEE018DEEPAKM
 
JAVAPart1_BasicIntroduction.pptx
Murugesh33
 
JAVA_Day1_BasicIntroduction.pptx
Murugesh33
 
JAVA PROGRAM CONSTRUCTS OR LANGUAGE BASICS.pptx
AALIM MUHAMMED SALEGH COLLEGE OF ENGINEERING
 
java basics concepts and the keywords needed
PriyadharshiniG41
 
Java Introduction
sunmitraeducation
 
Introduction to Core Java feature and its characteristics
rashmishekhar81
 
Introduction to java
Java Lover
 
JAVA-History-buzzwords-JVM_architecture.pptx
20EUEE018DEEPAKM
 

Similar to Object Oriented Programming Part 1 of Unit 1 (20)

PPT
PPS Java Overview Unit I.ppt
CDSukte
 
PPT
PPS Java Overview Unit I.ppt
RajeshSukte1
 
PPTX
Java fundamentals
Om Ganesh
 
PPTX
Introduction to JAVA
Md. Tanvir Hossain
 
PPTX
Getting Started with JAVA
ShivamPathak318367
 
PPTX
Presentation on java
william john
 
PPTX
1 java introduction
abdullah al mahamud rosi
 
PPTX
1 java intro
abdullah al mahamud rosi
 
PPTX
1 Module 1 Introduction.pptx
BhargaviDalal3
 
PPTX
1.Intro--Why Java.pptx
YounasKhan542109
 
PPTX
Java Basics
Fahad Shahzad
 
PPTX
Chapter-1 Introduction.pptx
SumanBhandari40
 
PPTX
Introduction to java
Krunali Gandhi
 
PDF
1. JAVA_Module_1-edited - AJIN ABRAHAM.pptx.pdf
10322210023
 
PPTX
2 22CA026_Advance Java Programming_Data types and Operators.pptx
dolphiverma80
 
PDF
Lecture-01 _Java Introduction CS 441 Fast
UzairSaeed18
 
PPTX
1 java programming- introduction
jyoti_lakhani
 
PPTX
powerpoint presentation on Java characteristics
sahooarka582
 
PPTX
UNIT 1 Programming in java Bsc program.pptx
jijinamt
 
PPTX
JAVA INTRODUCTION - 1
Infoviaan Technologies
 
PPS Java Overview Unit I.ppt
CDSukte
 
PPS Java Overview Unit I.ppt
RajeshSukte1
 
Java fundamentals
Om Ganesh
 
Introduction to JAVA
Md. Tanvir Hossain
 
Getting Started with JAVA
ShivamPathak318367
 
Presentation on java
william john
 
1 java introduction
abdullah al mahamud rosi
 
1 Module 1 Introduction.pptx
BhargaviDalal3
 
1.Intro--Why Java.pptx
YounasKhan542109
 
Java Basics
Fahad Shahzad
 
Chapter-1 Introduction.pptx
SumanBhandari40
 
Introduction to java
Krunali Gandhi
 
1. JAVA_Module_1-edited - AJIN ABRAHAM.pptx.pdf
10322210023
 
2 22CA026_Advance Java Programming_Data types and Operators.pptx
dolphiverma80
 
Lecture-01 _Java Introduction CS 441 Fast
UzairSaeed18
 
1 java programming- introduction
jyoti_lakhani
 
powerpoint presentation on Java characteristics
sahooarka582
 
UNIT 1 Programming in java Bsc program.pptx
jijinamt
 
JAVA INTRODUCTION - 1
Infoviaan Technologies
 
Ad

Recently uploaded (20)

PPTX
22PCOAM21 Session 1 Data Management.pptx
Guru Nanak Technical Institutions
 
DOCX
SAR - EEEfdfdsdasdsdasdasdasdasdasdasdasda.docx
Kanimozhi676285
 
PPTX
22PCOAM21 Session 2 Understanding Data Source.pptx
Guru Nanak Technical Institutions
 
PPT
1. SYSTEMS, ROLES, AND DEVELOPMENT METHODOLOGIES.ppt
zilow058
 
PDF
Top 10 read articles In Managing Information Technology.pdf
IJMIT JOURNAL
 
PDF
settlement FOR FOUNDATION ENGINEERS.pdf
Endalkazene
 
PPTX
22PCOAM21 Data Quality Session 3 Data Quality.pptx
Guru Nanak Technical Institutions
 
PPT
Lecture in network security and mobile computing
AbdullahOmar704132
 
PPTX
Chapter_Seven_Construction_Reliability_Elective_III_Msc CM
SubashKumarBhattarai
 
PPTX
business incubation centre aaaaaaaaaaaaaa
hodeeesite4
 
PPTX
MSME 4.0 Template idea hackathon pdf to understand
alaudeenaarish
 
PPTX
database slide on modern techniques for optimizing database queries.pptx
aky52024
 
PDF
67243-Cooling and Heating & Calculation.pdf
DHAKA POLYTECHNIC
 
PDF
Principles of Food Science and Nutritions
Dr. Yogesh Kumar Kosariya
 
PPT
SCOPE_~1- technology of green house and poyhouse
bala464780
 
PDF
Activated Carbon for Water and Wastewater Treatment_ Integration of Adsorptio...
EmilianoRodriguezTll
 
PDF
2010_Book_EnvironmentalBioengineering (1).pdf
EmilianoRodriguezTll
 
PDF
Chad Ayach - A Versatile Aerospace Professional
Chad Ayach
 
PDF
Cryptography and Information :Security Fundamentals
Dr. Madhuri Jawale
 
PPTX
easa module 3 funtamental electronics.pptx
tryanothert7
 
22PCOAM21 Session 1 Data Management.pptx
Guru Nanak Technical Institutions
 
SAR - EEEfdfdsdasdsdasdasdasdasdasdasdasda.docx
Kanimozhi676285
 
22PCOAM21 Session 2 Understanding Data Source.pptx
Guru Nanak Technical Institutions
 
1. SYSTEMS, ROLES, AND DEVELOPMENT METHODOLOGIES.ppt
zilow058
 
Top 10 read articles In Managing Information Technology.pdf
IJMIT JOURNAL
 
settlement FOR FOUNDATION ENGINEERS.pdf
Endalkazene
 
22PCOAM21 Data Quality Session 3 Data Quality.pptx
Guru Nanak Technical Institutions
 
Lecture in network security and mobile computing
AbdullahOmar704132
 
Chapter_Seven_Construction_Reliability_Elective_III_Msc CM
SubashKumarBhattarai
 
business incubation centre aaaaaaaaaaaaaa
hodeeesite4
 
MSME 4.0 Template idea hackathon pdf to understand
alaudeenaarish
 
database slide on modern techniques for optimizing database queries.pptx
aky52024
 
67243-Cooling and Heating & Calculation.pdf
DHAKA POLYTECHNIC
 
Principles of Food Science and Nutritions
Dr. Yogesh Kumar Kosariya
 
SCOPE_~1- technology of green house and poyhouse
bala464780
 
Activated Carbon for Water and Wastewater Treatment_ Integration of Adsorptio...
EmilianoRodriguezTll
 
2010_Book_EnvironmentalBioengineering (1).pdf
EmilianoRodriguezTll
 
Chad Ayach - A Versatile Aerospace Professional
Chad Ayach
 
Cryptography and Information :Security Fundamentals
Dr. Madhuri Jawale
 
easa module 3 funtamental electronics.pptx
tryanothert7
 
Ad

Object Oriented Programming Part 1 of Unit 1

  • 1. CS8392 - Object Oriented Programming Unit I Introduction to OOP and Java Fundamentals
  • 2. • Java is an Object-oriented, class-based, concurrent, secured and general-purpose programming language. • It is a widely used robust technology. • Java is a platform. – Platform: Any hardware or software environment in which a program runs, is known as a platform. – Since Java has a runtime environment (JRE) and API, it is called a platform. 2 JAVA: Introduction
  • 3. • Java initial work started in 1990 by Sun Microsystems engineer Patrick Naughton as a part of the Stealth Project. • The Stealth Project soon changed to the Green Project, with Mike Sheridan and James Gosling joining the ranks, and the group began developing new technology for programming next-generation smart appliances. • James Gosling, Mike Sheridan, and Patrick Naughton initiated the Java language project in June 1991. • Gosling attempted to modify and extend C++ (a development he refers to as "C++ ++ --"), but quickly abandoned this approach in favour of creating an entirely new language. • Firstly, it was called "Greentalk" by James Gosling, and file extension was .gt. After that, it was called Oak, named after the tree that stood outside his office. 3 JAVA: History
  • 4. • Originally designed for small, embedded systems in electronic appliances like set-top boxes. Then incorporate some changes based on emergence of World Wide Web, which demanded portable programs. • In 1995, Oak was renamed as "Java" because it was already a trademark by Oak Technologies. • The first publicly available version of Java (Java 1.0) was released in 1995. • In 2006 Sun started to make Java available under the GNU General Public License (GPL). Sun Microsystems was acquired by the Oracle Corporation in 2010. Oracle continues this project called OpenJDK. 4 JAVA: History
  • 5. Programming Popularity Java by Industry 5 JAVA: Why Java?
  • 6. • 850 million PCs as Java Runtime Environment • More then 3 billion devices run java – Desktop Applications such as acrobat reader, media player, antivirus etc. – Web Applications – Enterprise Applications such as banking applications. – Mobile – Web services – Cloud – Embedded System – Smart Card – Robotics – Games etc. 6 JAVA: Where it is used?
  • 8. 8 C Vs C++ Vs JAVA
  • 12. 12 Characteristics of JAVA Simple • Java is very easy to learn, and its syntax is simple, clean and easy to understand. – Java syntax is based on C++ (so easier for programmers to learn it after C++). – Java has removed many complicated and rarely-used features, for example, explicit pointers, operator overloading, etc. – There is no need to remove unreferenced objects because there is an Automatic Garbage Collection in Java.
  • 13. 13 Characteristics of JAVA Object Oriented • Java is an fully object-oriented programming language. Everything in Java is an object. • Object-oriented means we organize our software as a combination of different types of objects that incorporates both data and behaviour. • It supports all the OOPs concepts. Platform independent • Java code can be run on multiple platforms, for example, Windows, Linux, Sun Solaris, Mac/OS, etc. Java code is compiled by the compiler and converted into bytecode or class file. • This bytecode is a platform-independent code because it can be run on multiple platforms, i.e., Write Once and Run Anywhere(WORA).
  • 14. 14 Characteristics of JAVA Secure: • Java is secured because: – No explicit pointer – Java Programs run inside a virtual machine sandbox Classloader: • Classloader in Java is a part of the Java Runtime Environment(JRE) which is used to load Java classes into the Java Virtual Machine dynamically. • It adds security by separating the package for the classes of the local file system from those that are imported from network sources.
  • 15. 15 Characteristics of JAVA Secure • Bytecode Verifier: It checks the code fragments for illegal code that can violate access right to objects. • Security Manager: It determines what resources a class can access such as reading and writing to the local disk. • Java language provides these securities by default. Some security can also be provided by an application developer explicitly through SSL, JAAS, Cryptography, etc.
  • 16. 16 Characteristics of JAVA Robust • Robust simply means strong. Java is robust because: • It uses strong memory management. • There is a lack of pointers that avoids security problems. • There is automatic garbage collection in java which runs on the Java Virtual Machine to get rid of objects which are not being used by a Java application anymore. • There are exception handling and the type checking mechanism in Java. All these points make Java robust.
  • 17. 17 Characteristics of JAVA Architecture Neutral • Java is architecture neutral because there are no implementation dependent features, for example, the size of primitive types is fixed. • In C programming, int data type occupies 2 bytes of memory for 32-bit architecture and 4 bytes of memory for 64-bit architecture. • However, it occupies 4 bytes of memory for both 32 and 64- bit architectures in Java.
  • 18. 18 Characteristics of JAVA Portable • Java is portable because it facilitates you to carry the Java bytecode to any platform. It doesn't require any implementation. High-Performance • Java is a little bit slower than a compiled language (e.g., C++). Java is an compiled and interpreted language that is why it is slower than compiled languages, e.g., C, C++, etc. • But with the use of Just-In-Time compilers, Java enables high performance than C, C++, etc.
  • 19. 19 Characteristics of JAVA Distributed • Java is distributed because it facilitates users to create distributed applications in Java. • RMI and EJB are used for creating distributed applications. • This feature of Java makes us able to access files by calling the methods from any machine on the internet. Dynamic • Java is a dynamic language. It supports dynamic loading of classes. • It means classes are loaded on demand. It also supports functions from its native languages, i.e., C and C++. • Java supports dynamic compilation and automatic memory management (garbage collection).
  • 20. 20 Characteristics of JAVA Multi-threaded • A thread is like a separate program, executing concurrently. • We can write Java programs that deal with many tasks at once by defining multiple threads. • The main advantage of multi-threading is that it doesn't occupy memory for each thread. • It shares a common memory area. Threads are important for multi-media, Web applications, etc.
  • 21. • For executing any java program, you need to Install the JDK if you don't have installed it, download the JDK and install it. – https://www.oracle.com/technetwork/java/javase/downloads/index.html • Create the java program using any editor like notepad, notepad++ and save with file extension .java. ‑ Ex: Simple.java 21 First Java Program /** First Java Program **/ import java.io.*; public class Simple { public static void main (String args[]) { System.out.println(“Hello Worldn”); } //end main }//end class
  • 22. 22 First Java Program • The path is required to be set for using tools such as javac, java, etc. • If you are saving the Java source file inside the JDK/bin directory, the path is not required to be set because all the tools will be available in the current directory. • However, if you have your Java file outside the JDK/bin folder, it is necessary to set the path of JDK. • There are two ways to set the path in java: • Temporary • In Comment Prompt • set path= C:Program FilesJavajdk1.8.0_191bin • Permanent • Set Path using Environmental Variables option
  • 23. First Java Program • To compile – javac Simple.java • To run – java Simple 23 To compile and run a java program
  • 24. 24 First Java Program: Compilation & Execution
  • 25. • JDK = Java Runtime Environment (JRE) + Development Tools • JRE = Java Virtual Machine (JVM) + Library Classes • JVM=Java Interpreter + Just-In-Time Compiler 25 JDK vs JRE vs JVM
  • 26. • JDK stands for “Java Development Kit”. • It is a software development environment used for developing Java applications and applets. • It includes the Java Runtime Environment (JRE), an interpreter/loader (Java), a compiler (javac), an archiver (jar), a documentation generator (Javadoc) and other tools needed in Java development. 26 JDK: Java Development Kit
  • 27. • JRE stands for “Java Runtime Environment” and may also be written as “Java RTE.” • The Java Runtime Environment provides the minimum requirements for executing a Java application; • it consists of the Java Virtual Machine (JVM), core classes, and supporting files. 27 JRE: Java Runtime Environment
  • 28. • JVM – Java Interpreter + Just-In-Time Compiler – JVM (Java Virtual Machine) is an abstract machine. It is a specification that provides runtime environment in which java byte code can be executed. – JVMs are available for many hardware and software platforms. It is the code execution component of the Java platform. – It is a Runtime Instance Whenever you write java command on the command prompt to run the java class, an instance of JVM is created. • Note: – JVM, JRE and JDK are platform dependent because configuration of each OS differs. But, Java is platform independent. 28 JVM: Java Virtual Machine
  • 29. 29 Need for JVM • The Java Virtual Machine is a program whose purpose is to execute other programs. • The JVM has two primary functions: ₋ to allow Java programs to run on any device or operating system (known as the "Write once, run anywhere" principle) ₋ to manage and optimize program memory. • Each operating system has different JVM, however the output they produce after execution of byte code is same across all operating systems. • Bytecode: Byte code is the set of optimized instructions generated during compilation phase and it is more powerful than ordinary pointer code.
  • 30. 30 JDK vs JRE vs JVM JVM JDK JRE It stands for Java Virtual machine. It stands for Java Development Kit It stands for Java Runtime Environment It is an abstract machine. It is a specification that provides a run-time environment in which java byte code can be executed. It is the tool necessary to compile, document and package java programs. JRE refers to a runtime environment in which java byte code can be executed. JVM follows three notation: Specification, Implementation and Runtime instance It contains JRE + development tools. It is an implementation of the JVM which physically exists.
  • 32. 32 JVM Architecture • Class Loader: The class loader reads the .class file and save the byte code in the method area. • Method Area: There is only one method area in a JVM which is shared among all the classes. This holds the class level information of each .class file. • Heap: Heap is a part of JVM memory where objects are allocated. JVM creates a Class object for each .class file. • Stack: Stack is a also a part of JVM memory but unlike Heap, it is used for storing temporary variables.
  • 33. 33 JVM Architecture • PC Registers: This keeps the track of which instruction has been executed and which one is going to be executed. Since instructions are executed by threads, each thread has a separate PC register. • Native Method stack: A native method can access the runtime data areas of the virtual machine. • Native Method interface: It enables java code to call or be called by native applications. Native applications are programs that are specific to the hardware and OS of a system. • Garbage collection: A class instance is explicitly created by the java code and after use it is automatically destroyed by garbage collection for memory management.
  • 34. 34 JIT: Just In Time Compiler • The Just-In-Time compiler is one of the integral parts of the Java Runtime Environment. • It is mainly responsible for performance optimization of Java-based applications at run time or execution time.
  • 35. 35 JIT: Just In Time Compiler Step:1 • When you code the Java Program, JRE uses javac compiler to compile the high-level Source code to byte code. • After this, JVM loads the byte code at run time and converts into machine level binary code for further execution using Interpreter. Step:2 • Interpretation of Java byte code reduces the performance when compared to a native application i.e JIT Compiler aids to boost up the performance by compiling the byte code into native machine code “just-in-time” to run.
  • 36. 36 JIT: Just In Time Compiler Step:3 • The JIT Compiler is activated and enabled by default when a method is invoked in Java. • When a method is compiled, Java Virtual Machine invokes the compiled code of the method directly without interpreting it. • Hence, it does not require much memory usage and processor time. That basically speeds up the performance of the Java Native Application.
  • 37. 37 First Java Program /** First Java Program **/ import java.io.*; public class Simple { public static void main (String args[]) { System.out.println(“Hello Worldn”); } //end main }//end class
  • 38. Question and Answer 38 Java: Data Types Is necessary main class is public in java? • To compile a program, you doesn’t really need a main method in your program. But, while execution JVM searches for the main method. In the Java the main method is the entry point Whenever you execute a program in Java JVM searches for the main method and starts executing from it. • The main method must be public, static, with return type void, and a String array as argument. public static void main(String[] args) • You can write a program without defining a main it gets compiled without compilation errors. But when you execute it a run time error is generated saying “Main method not found”.
  • 39. Question and Answer 39 Java: Data Types Is necessary main class name should be same as filename? • The filename must have the same name as the public class name in that file, which is the way to tell the JVM that this is an entry point. • Suppose when we create a program in which more than one class resides and after compiling a java source file, it will generate the same number of the .class file as classes reside in our program. In this condition, we will not able to easily identify which class need to interpret by java interpreter and which class containing Entry point for the program.
  • 40. Question and Answer 40 Java: Data Types Why java main method is static and public? • Java program's main method has to be declared static because keyword static allows main to be called without creating an object of the class in which the main method is defined. If we omit static keyword before main Java program will successfully compile but it won't execute.
  • 42. • Access modifiers (or access specifiers) are keywords in object oriented languages that ‑ set the accessibility of classes, methods, and other members. • Access modifiers are a specific part of programming language syntax used to facilitate the encapsulation of components. 42 Java: Access Modifiers
  • 44. 44 First Java Program • public keyword is an access modifier which represents visibility. It means it is visible to all. • class keyword is used to declare a class in java. (Here, Simple is a class name) • static is a keyword. If we declare any method as static, it is known as the static method. – The core advantage of static method is that there is no need to create object to invoke the static method. – The main method is executed by the JVM, so it doesn't require to create object to invoke the main method. So it saves memory. /** First Java Program **/ import java.io.*; public class Simple { public static void main (String args[]) { System.out.println(“Hello World n”); } //end main
  • 45. 45 First Java Program • void is the return type of the method. It means it doesn't return any value. • main represents the starting point of the program. • String[] args is used for command line argument. • System.out.println() is used to print statement. /** First Java Program **/ import java.io.*; public class Simple { public static void main (String args[]) { System.out.println(“Hello World n”); } //end main }//end class
  • 46. • A token is the smallest element of a program that is meaningful to the compiler. • Tokens can be classified as follows: ‑ Keywords ‑ Identifiers ‑ Constants / Literals ‑ Special Symbols ‑ Operators 46 Java: Tokens
  • 47. 47 Java: Keywords • Keywords are terms or phrases appropriated for special use that may not be utilized in the creation of variable names. ₋ For example, “while" is a reserved word because it is a function in many languages to show text on the screen. • Keywords are also known as Reserved words
  • 48. 48 Java: Identifiers • Identifiers are used for identification purposes. • An identifier is the name given by the user for the various programming elements like variables, functions, arrays, structure, class and file. Rules for defining an identifier • The only allowed characters for identifiers are all alphanumeric characters([A-Z],[a-z],[0-9]), ‘$‘(dollar) and ‘_‘ (underscore). • Identifiers should not start with digits([0-9]). – For example “123geeks” is a not a valid identifier. • Java identifiers are case-sensitive. • There is no limit on the length of the identifier but it is advisable to use an optimum length of 4 – 15 letters only. • Reserved Words can’t be used as an identifier. – For example “int while = 20;” is an invalid statement as while is a reserved word. There are 53 reserved words in Java.
  • 49. 49 Java: Data Types • Data types define the type of data a variable can hold • For example an integer variable can hold integer data, a character type variable can hold character data etc.
  • 51. Question and Answer 51 Java: Data Types Why is the size of char is 2 byte in java..? • In other languages like C/C++ uses only ASCII characters and to represent all ASCII characters 8-bits is enough, • But java uses Unicode system not ASCII code system and to represent Unicode system 8 bit is not enough to represent all characters so java uses 2 byte for characters. Why Java is a statically typed language? • Java is statically typed and also a strongly typed language because in Java, each type of data (such as integer, character, hexadecimal, packed decimal, and so forth) is predefined as part of the programming language and all constants or variables defined for a given program must be described with one of the data types.
  • 52. 52 Java: Variables Variable: • A variable is a container which holds the value while the Java program is executed. • The variable's name represents what information the variable contains. • A variable is defined by the combination of an identifier, a type, and an optional initializer. Example: int age=20; string name=“hello”;
  • 53. Java: Variables Types of variables – Local Variable – Instance Variable or Non-static Variable – Static Variable Local Variable • Local variables are declared within a method or within a block of code in a method. • In general, a local variable is accessible from its declaration to the end of the code block in which it was declared. • A local variable cannot be defined with "static" keyword. 53
  • 54. Instance Variable or Non-static variable • A variable declared inside the class but outside the body of the method, is called instance variable. Instance variables are defined without the STATIC keyword . • Instance variables are created when the objects are instantiated and therefore they are associated with the objects. Static Variable • A variable which is declared as static is called static variable. It cannot be local. • You can create a single copy of static variable and share among all the instances of the class. Memory allocation for static variable happens only once when the class is loaded in the memory. 54 Java: Variables
  • 55. Example: class A { int data=50;//instance variable static int m=100;//static variable void method() { int n=90;//local variable } }//end of class 55 Java: Variables
  • 56. Literal : • Any constant value which can be assigned to the variable is called as literal/constant. Example • boolean result = true; • char capitalC = 'C'; • byte b = 100; • short s = 10000; • int i = 100000; 56 Java: Literals
  • 57. Using Underscore Characters in Numeric Literals • In Java SE 7 and later, any number of underscore characters (_) can appear anywhere between digits in a numerical literal. • This feature enables you, for example. to separate groups of digits in numeric literals, which can improve the readability of your code. • Example • long creditCardNumber = 1234_5678_9012_3456L; • long socialSecurityNumber = 999_99_9999L; • float pi = 3.14_15F; • long bytes = 0b11010010_01101001_10010100_10010010; • You can place underscores only between digits; you cannot place underscores in the following places: • At the beginning or end of a number • Adjacent to a decimal point in a floating point literal • Prior to an F or L suffix • In positions where a string of digits is expected 57 Java: Literals
  • 58. What is the difference between character literals and string literals in Java? • Character literals represents alphabets (both cases), numbers (0 to 9), special characters (@, ?, & etc.) and escape sequences like n, b etc. • The String literal represents objects of String class. 58 Java: Literals Question and Answer
  • 59. • Special symbols in Java are a few characters which have special meaning known to Java compiler and cannot be used for any other purpose. 59 Java: Special Symbols Symbol Description Brackets [] These are used as an array element reference and also indicates single and multidimensional subscripts Parentheses() These indicate a function call along with function parameters Braces{} The opening and ending curly braces indicate the beginning and end of a block of code having more than one statement Comma ( , ) This helps in separating more than one statement in an expression Semi-Colon (;) This is used to invoke an initialization list Asterisk (*) This is used to create a pointer variable in Java
  • 60. Write a Java program 5.1 To print an int, a double and a char variable on screen. 5.2 To print the area of a rectangle of sides 2 and 3 units respectively. 5.3 To print the product of the numbers 8.2 and 6. 5.4 Print the ASCII value of the character 'h'. 60 Java: Datatypes Exercise:5
  • 61. • Operator in Java is a symbol which is used to perform operations. For example: +, -, *, / etc. There are many types of operators in Java which are given below: ₋ Unary Operator, ₋ Arithmetic Operator, ₋ Shift Operator, ₋ Relational Operator, ₋ Bitwise Operator, ₋ Logical Operator, ₋ Ternary Operator and ₋ Assignment Operator. 61 Java: Operators
  • 63. 6.1 Length and breadth of a rectangle are 5 and 7 respectively. Write a program to calculate the area and perimeter of the rectangle. 6.2 Write a program to calculate the perimeter of a triangle having sides of length 2,3 and 5 units. 6.3 Write a program to add 8 to the number 2345 and then divide it by 3. Now, the modulus of the quotient is taken with 5 and then multiply the resultant value by 5. Display the final result. 1. Now, solve the above question using assignment operators (eg. +=, -=, *=). 6.4 Write a program to print the power of 7 raised to 5. 63 Java: Operators Exercise:6
  • 64. • The Java comments are the statements that are not executed by the compiler and interpreter. • The comments can be used to provide information or explanation about the variable, method, class or any statement. 64 Java: Comments
  • 65. Single line comment • This type of comment is mainly used for describing the code functionality. It is the easiest typed comments. • Single-line comments start with two forward slashes (//). Any text between // and the end of the line is ignored by Java implies it will not be executed. • The single line comment is used to comment only one line. Syntax: //Comments here(Text in this line will be considered as comment) Example: //my first comment 65 Basic Java: Comments
  • 66. Java: Comments Syntax: /*Comment starts Continues ……. Comment ends*/ Example: /* This is the beginning of a multi-line comment this is the end */ 66 Multi line comment • To describe a full method in a code or a complex snippet single line comments can be tedious to write since we have to give ‘//’ at every line. • So to overcome this multi-line comments can be used. Multi- line comments start with /* and end with */. • Any text between /* and */ will be ignored by Java. It is used to comment multiple lines of code.
  • 67. Java: Comments Syntax: /**Comment start * *tags are used in order to specify a parameter *or method or heading *HTML tags can also be used *such as <h1> *comment ends*/ Example: 67 Java Documentation Comment • This type of comments is used generally when you are writing code for a project/ software package. • It helps you to generate a documentation page for reference, which can be used for getting information about methods present, its parameters, etc. • The documentation comment is used to create documentation API. To create documentation API, you need to use Javadoc tool. Tag Author Descritpion @author Adds the author of a class. @author name-text @exception Adds a Throws subheading to the generated documentation, with the classname and description text. @exception class- name description @return Adds a “Returns” section with the description text. @return description
  • 68. • Casting is a process of changing one type of value to another type. In Java, we can cast one type of value to another type. It is known as type casting. • When you assign the value of one data type to another, you should be aware of the compatibility of the data type. • If they are compatible, then Java will perform the conversion automatically known as Automatic Type Conversion and if not, then they need to be casted or converted explicitly. • Types of casting – Automatic or Implicit or widening – Explicit or Narrowing 68 Java: Type Casting
  • 69. Automatic or Implicit or Widening: Automatic Type casting take place when, – the two types are compatible – the target type is larger than the source type Note: • In java the numeric data types are compatible with each other but no automatic conversion is supported from numeric type to char or boolean. Also, char and boolean are not compatible with each other. Example: Auto_Conversion.java 69 Java: Type Casting
  • 70. Explicit or Narrowing: • When you are assigning a larger type value to a variable of smaller type, then you need to perform explicit type casting. • This is useful for incompatible data types where automatic conversion cannot be done. • Here, target-type specifies the desired type to convert the specified value to. Example: Demo_Narrow.java,Narrowing.java 70 Java: Type Casting
  • 71. Write a Java program 7.1 To assign a value of 100.235 to a double variable and then convert it to int. 7.2 To add 3 to the ASCII value of the character 'd' and print the equivalent character. 7.3 To add an integer variable having value 5 and a double variable having value 6.2. 71 Java: Type Casting Exercise:7
  • 72. 72 Java: Read input from console
  • 73. • Java Scanner class allows the user to take input from the console. It belongs to java.util package. • It is used to read the input of primitive types like int, double, long, short, float, and byte. • It is the easiest way to read input in Java program. • To create an object of Scanner class, we usually pass the predefined object System.in, which represents the standard input stream. We may pass an object of class File if we want to read input from a file. 73 Java: Read input from console
  • 74. • To read numerical values of a certain data type XYZ, the function to use is nextXYZ(). – For example, to read a value of type short, we can use nextShort() • To read strings, we use nextLine() or next(). • To read a single character, we use next().charAt(0). next() function returns the next token/word in the input as a string and charAt(0) funtion returns the first character in that string. Example: Getinputfromuser.java, Demochar.java 74 Java: Read input from console
  • 75. 75 Java: Read input from console Example:
  • 76. Write a Java program 8.1 That accepts two integer inputs from user and print sum and product of them. 8.2 That takes name, roll number and field of interest from user and print in the format below : Output: Hey, my name is xyz and my roll number is xyz. My field of interest are xyz. 8.3 To find square of a number. Test Cases: Input : 2 Output : 4 Input : 5 Output : 25 76 Java: Read input from console Exercise:8
  • 77. • A programming language uses control statements to control the flow of execution of program based on certain conditions. 77 Java: Control Statements
  • 78. • In Java, if statement is used for testing the conditions. • The condition matches the statement it returns true else it returns false. • There are four types of if statement they are: ₋ if statement ₋ if-else statement ₋ if-else-if ladder ₋ nested if statement ₋ Switch statement 78 Java: Selection Statements
  • 79. • if statement tests the condition. It executes the if block if condition is true. • Syntax: Example: IfDemo1.java if(condition) { //code to be executed } 79 Selection Statements :Simple if Practice: Write Java program for the following problem: 1. To check the entered mark is pass (if it is greater than 40). 2. To check whether given number is divisor of 7. Flowchart
  • 80. • if-else statement also tests the condition. It executes the if block if condition is true else if it is false the else block is executed. • Syntax: Example: IfElseDemo1.java if(condition){ //code for true } else{ //code for false } 80 Selection Statements :if-else Practice: Write Java program for the following problem: 1. To find the greatest of two numbers. 2. To check whether the given number is odd or even. 3. To check whether the given year is leap year or not. 4. To check whether the given age is valid for vote or not. Flowchart
  • 81. • The if-else-if ladder statement is used for testing conditions. It is used for testing one condition from multiple statements. • Syntax: Example: IfElseIFDemo1.java if(condition1) { //code for if condition1 is true } else if(condition2) { //code for if condition2 is true } ... else { //code for all the false conditions } 81 Selection Statements :if-else-if Flowchart
  • 82. 82 Selection Statements :if-else-if Practice: Write Java program for the following problem: 1. To find the largest of three numbers 2. To Check whether the given Character is a Vowel /Consonant /Digit /Special Symbol. 3. To input basic salary of an employee and calculate gross salary according to given conditions. Basic Salary <= 10000 : HRA = 20%, DA = 80% Basic Salary is between 10001 to 20000 : HRA = 25%, DA = 90% Basic Salary >= 20001 : HRA = 30%, DA = 95% Gross Salary=Basic Salary + HRA + DA
  • 83. • Nested if-else statements, is that using one if or else if statement inside another if or else if statement(s). • Syntax: Example: NestedIfDemo1.java if(condition) { if(condition) { //statement } else { //statement } … } else { //statement 83 Selection Statements : Nested if Flowchart
  • 84. 84 Selection Statements : Nested if Practice: Write Java program for the following problem: 1. To Read a Coordinate Point in a XY Coordinate System and Determine its Quadrant. 2. To find the greatest of three numbers.
  • 85. • In Java, the if..else..if ladder executes a block of code among many blocks. • The switch statement can be a substitute for long if..else..if ladders which generally makes your code more readable. • It's also important to note that switch statement in Java only works with: – Primitive data types: byte, short, char and int – Enumerated types (Java enums) – String class – a few classes that wrap primitive types: Character, Byte, Short & Integer 85 Selection Statements: Switch
  • 86. Syntax: Flowchart switch(expression) { case value1: //code for execution; break; //optional case value2: // code for execution break; //optional ...... Case value n: // code for execution break; //optional default: //code for execution when none of the case is true; } Example:SwitchDemo1.java 86 Selection Statements: Switch Practice: Write Java program for the following problem: 1. To Check the given Character is a Vowel. 2. Simple Calculator (Try both integer (1,2,3) and character(+, -, *, /, %) as a case in separate program)
  • 87. Write a Java program 9.1Write a program to calculate the monthly telephone bills as per the following rule: Minimum Rs. 200 for up to 100 calls. Plus Rs. 0.60 per call for next 50 calls. Plus Rs. 0.50 per call for next 50 calls. Plus Rs. 0.40 per call for any call beyond 200 calls. 9.2 Write a program that asks the user to enter a number and displays the absolute value of that number. 87 Selection Statements Exercise:9
  • 88. 9.3 A triangle is valid if the sum of all the three angles is equal to 180 degrees. Write a program that asks the user to enter three integers as angles and check whether a triangle is valid or not. 9.4 Write a program that prompts the user to enter grade. Your program should display the corresponding meaning of grade as per the following table 88 Selection Statements Exercise:9 Grade Meaning A Excellent B Good C Average D Deficient F Failing
  • 89. • In programming languages, loops are used to execute a set of instructions/functions repeatedly when some conditions become true. • There are three types of loops in java. 89 Java: Iterative Statements
  • 90. • In java, while loop is used for iterating a part of the program several times. When the number of iteration is not fixed then while loop is used. • Syntax: Example: WhileDemo1.java while(condition) { //code for execution } 90 Iterative Statements: while Practice: Write Java program for the following problem: 1. Rectangle number pattern. 2. To check the number is palindrome. Flowchart
  • 91. • In java, do-while loop is used to execute a part of the program again and again. If the number of iteration is not fixed then the do-while loop is used. This loop executes at least once because the loop is executed before the condition is checked. • Syntax: Example: WhileDemo1.java do { //code for execution }while(condition); 91 Iterative Statements: do-while Practice: Write Java program for the following problem: 1. To print the numbers from 10 to 1. 2. Sum of ‘n’ natural numbers. Flowchart
  • 92. • In java, for loop is used for executing a part of the program again and again. When the number of execution is fixed then it is suggested to use for loop. • In java there are 2 types of for loops, they are as follows: ₋ Simple for loop ₋ For-each loop 92 Iterative Statements: for
  • 93. Syntax: for(initialization;condition;increment/decrement) { //statement } Example: ForDemo1.java 93 Iterative Statements: for Flowchart Practice: Write Java program for the following problems: 1. To print numbers from 1 to 10. 2. To find the factorial 3. To calculate the sum of following series where n is input by user. 1 + 1/2 + 1/3 + 1/4 + 1/5 +…………1/n
  • 94. • Nested Loop: A loop inside another loop is called a nested loop. The number of loops depend on the complexity of a problem. • Suppose, a loop, outer loop, running n number of times consists of another loop inside it, inner loop, running m number of times. Then, for each execution of the outer loop from 1...n, the inner loop runs maximum of m times. • Syntax: Example: PyramidExample.java, Pattern.java 94 Iterative Statements: Nested Loop
  • 95. • In Java, a break statement is used inside a loop. The loop is terminated immediately when a break statement is encountered and resumes from the next statement. Syntax: Flowchart: break; Example: BreakDemo1.java 95 Jump Statements: Break Practice: Write Java program for the following problem: The sum of numbers entered by the user until user enters a negative number.
  • 96. • In Java, the Continue statement is used in loops. Continue statement is used to jump to the next iteration of the loop immediately. It is used with for loop, while loop and do-while loop. Syntax: Example:ContinueDemo1.java continue; Flowchart: 96 Jump Statements: Continue Practice: Write Java program for the following problem: The sum of numbers entered by the user until user enters a negative number.
  • 97. • In Labelled Break Statement, we give a label/name to a loop. • When this break statement is encountered with the label/name of the loop, it skips the execution any statement after it and takes the control right out of this labelled loop. • The control goes to the first statement right after the loop. Example:LabelledBreak.java,LabelledBreak1.java 97 Jump Statements: labelled break
  • 98. • In Labelled Continue Statement, we give a label/name to a loop. • When this continue statement is encountered with the label/name of the loop, it skips the execution any statement within the loop for the current iteration and continues with the next iteration and condition checking in the labelled loop. Example: LabelledContinue.java 98 Jump Statements: labelled Continue
  • 99. Write a Java program 10.1 To check the number is prime or not. 10.2 Guess the integer. 10.3 To enter the numbers till the user wants and at the end it should display the count of positive, negative and zeros entered. 99 Java: Control Statements Exercise:10
  • 100. Write a Java program 10.4 To print the right angular triangle pattern. 10.5 To write the even numbers from 10 to 20, both included, except 16, in 3 different ways: - Incrementing 2 in each step (use "continue" to skip 16) - Incrementing 1 in each step (use "continue") - With and endless loop (using "break" & "continue") 100 Java: Control Statements Exercise:10
  • 101. • Array is a collection of similar type of elements that have contiguous memory location. • In Java all arrays are dynamically allocated. Since arrays are objects in Java, we can find their length using member length. • A Java array variable can also be declared like other variables with [] after the data type. • The variables in the array are ordered and each have an index beginning from 0. • Java array can be also be used as a static field, a local variable or a method parameter. 101 Java: Arrays
  • 102. Advantages • Code Optimization: It makes the code optimized, we can retrieve or sort the data efficiently. • Random access: We can get any data located at an index position. Disadvantages • Size Limit: We can store only the fixed size of elements in the array. It doesn't grow its size at runtime. – To solve this problem, collection framework is used in Java which grows automatically. 102 Java: Arrays
  • 103. Types of Array There are two types of array. Single Dimensional Array: An array is a group of like-typed variables that are referred to by a common name. Syntax: datatype variable_name[]; or datatype[] variable_name; Multidimensional Array: An array of more than one dimension is known as a multi-dimensional array. Syntax: datatype array_name[][]=new int [][]; datatype [][] array_name=new int[][]; Example:Testarray.java,Testarray1.java,Testarray3.java,Testarray5.java, Testarray11.java,MatrixMultiplicationExample.java 103 Java: Arrays
  • 104. • Arrays -> Specified in java.util.Arrays Package • Arrays is a class which contain following methods – Arrays.toString({ArrayVariable}); – Arrays.copyOf({Array Variable},Length to be copied); – Arrays.copyOfRange({Array Variable}, int from, int to); – Arrays.equals({Array Variable x}, {Array Variable y}); – Arrays.sort({ArrayVariable}); 104 Java: Arrays
  • 105. How to access an array element in java? • Each variable in an Java array is also called an "element". Each element in the array has an index (a number). You can access each element in the array via its index. • Syntax: datatype arrayname[index_value]; What happens if we try to access element outside the array size? • JVM throws ArrayIndexOutOfBoundsException to indicate that array has been accessed with an illegal index. The index is either negative or greater than or equal to size of array. 105 Java: Arrays Question and Answer
  • 106. Jagged Arrays: • It is an array of arrays where each element is, in turn, an array. A special feature of this type of array is that it is a Multidimensional array whose each element can have different sizes. Purpose of jagged arrays: • Jagged arrays are a special type of arrays that can be used to store rows of data of varying lengths to improve performance when working with multi-dimensional arrays. An array may be defined as a sequential collection of elements of the same data type. Example:TestJaggedArray.java 106 Java: Arrays
  • 107. Write a Java program 11.1 To sum values of an array. 11.2 To find the maximum and minimum value of an array 11.3 To remove a specific element from an array. 11.4 To find the sum of two matrices. 11.5 To print the following grid. - - - - - - - - - - - - - - - - - - - - 107 Java: Arrays Exercise:11
  • 108. 108 Quiz 1) Which of the following option leads to the portability and security of Java? 2) Which of the following is not a Java features? d) Dynamic binding between objects c) Use of exception handling a) Byte code is executed by JVM b) The applet makes the Java code secure and portable Answer : Option a) QUIZ a) Dynamic b) Architecture Neutral c) Use of pointers d) Object-oriented Answer : Option c)
  • 109. 109 Quiz 3) _____ is used to find and fix bugs in the Java programs. 4) What does the expression float a = 35 / 0 return? d) JDB c) JDK a) JVM b) JRE Answer : Option d) QUIZ d) Run time exception c) Infinity a) 0 b) Not a Number Answer : Option c)
  • 110. 110 Quiz 5) Evaluate the following Java expression, if x=3, y=5, and z=10: + +z + y - y + z + x++ 6)Which of the following tool is used to generate API documentation in HTML format from doc comments in source code? Answer : Option a) d) 25 c) 20 a) 24 b) 23 QUIZ d) javah command c) Javadoc tool a) javap tool b) javaw command Answer : Option c)
  • 111. 111 Quiz 7) Which method of the Class.class is used to determine the name of a class represented by the class object as a String? 8) Which keyword is used for accessing the features of a package? d) toString() c) getName() a) getClass() b) intern() Answer : Option c) QUIZ d) Export c) extends a) package b) import Answer : Option b)
  • 112. 112 Quiz 9) What will be the output of the following program? public class Test { public static void main(String[] args) { int count = 1; while (count <= 15) { System.out.println(count % 2 == 1 ? "***" : "+++++"); ++count; } } } d) Both will print only once c) 8 times *** and 7 times +++++ a) 15 times *** b) 15 times +++++ Answer : Option c) QUIZ
  • 113. 113 Quiz 10) Which of the following for loop declaration is not valid? d) for ( int i = 2; i <= 20; i = 2* i ) c) for ( int i = 20; i >= 2; - -i ) a) for ( int i = 99; i >= 0; i / 9 ) b) for ( int i = 7; i <= 77; i += 7 ) Answer : Option a) QUIZ
  • 114. Possible questions: 2 Marks 1. What is Java? 2. What are the differences between C++ and Java? 3. List the features of Java Programming language. 4. Compare JDK,JRE and JVM. 5. What is JIT compiler? 6. What gives Java its 'write once and run anywhere' nature? 7. Is Empty .java file name a valid source file name? 8. What is the difference between double and float variables in Java? 9. What if I write static public void instead of public static void? 114 Introduction to Java
  • 115. Possible questions:2 Marks 10. What is the purpose of identifier in programming language? 11. Define keyword. 12. List the rules for defining an identifier. 13. What is the advantage of Unicode in Java? 14. Define operator and its types. 15. Differentiate while and do..while loop. 16. What is the difference between continue and break statement? 17. Define array and its types. 18. What is the purpose of jagged array? 19. Define strings. 20. How can we create a string in java? 115 Introduction to Java
  • 116. Possible questions: 16 Marks: 1. Discuss the characteristics of java in detail. 2. Explain different types of operators involved in Java. 3. Discuss control statements in detail with its types. 4. Explain the advantage of labeled break and labeled continue. 5. Explain Jagged array with example. 6. What is array? Discuss its types with example. 7. Explain at least 5 array related inbuilt methods with example. 116 Introduction to Java
  • 117. Anna University Questions: 2 marks: 1. Can a Java source file be saved using a name other than the class name? Justify.(Apr/May 2018) 16 marks: Apr/May 2019 2. What are literals? Explain the types of literals supported by java.(6) 3. Explain the selection statements in java with suitable examples.(7) 4. Write a Java code using do-while loop that counts down to 1 from 10 printing exactly ten lines of “hello”.(6) 117 Introduction to Java