Department of computer Engineering
Subject: Programming Language Paradigm
Unit 4Java as object oriented Programming
Language- overview
1
Course Content
Basic Concepts of Java Data types and Size Arrays Control Statements String Handling
2
Basic Concepts of Java
Introduction to Java
History of Java
Java Virtual Machine
Java Installation
Java Program Structure
Variables
Java and Internet
Java and World Wide Web
3
Introduction to Java
Was developed in the early 90s by Sun Microsystems (but now owned by Oracle Corporation from 2010).
Java is a high-level language
Allows anyone to publish a web page with Java code in it.
The current popularly used version of Java is Java 11.
Compiled and interpreted both
4
HistoryProject started by James Gosling, Mike Sheridan, and Patrick Naughton, and others from Sun Microsystems in June 1991.
• Initially called “Oak”, then “Green”, and then “Java”.
• Java First appeared in May, 1995.
• HotJava – The first Java-enabled Web browser
• JDK Evolutions
5
6
JDK Versions
• JDK 1.0 (January 23, 1996)• JDK 1.1 (February 19, 1997)• J2SE 1.2 (December 8, 1998)• J2SE 1.3 (May 8, 2000)• J2SE 1.4 (February 6, 2002)• J2SE 5.0 (September 30, 2004)• Java SE 6 (December 11, 2006)• Java SE 7 (July 28, 2011)• Java SE 8 (March 18, 2014)• Java SE 9 (September 21, 2017)• Java SE 10 (March 20, 2018)• Java SE 11 (September 25, 2018)
7
JDK Editions
• Java Standard Edition (J2SE)
– J2SE can be used to develop client-side standalone
applications or applets.
• Java Enterprise Edition (J2EE)
– J2EE can be used to develop server-side applications such
as Java servlets and Java Server Pages.
• Java Micro Edition (J2ME).
– J2ME can be used to develop applications for mobile
devices such as cell phones.
8
Java IDE Tools
• NetBeans (open sourse IDE)• Eclipse• Android Studio• Forte by Sun MicroSystems • Borland JBuilder
• Microsoft Visual J++
• WebGain Café
• IBM Visual Age for Java
Java and Internet Java is strongly associated with the Internet. Internet users can use Java to create applet
programs and run them locally using a "Java-enabled browser" such as HotJava. They can also use a Java-enabled browser to download an applet located on a computer anywhere in the Internet and run it on his local computer. In fact, Java applets have made the Internet a true extension of the storage system of the local computer.
Internet users can also setup their websites containing java applets that could be used by other remote users of Internet. This feature made Java most popular programming language for Internet.
9
Java and www World Wide Web (WWW) is an open-ended information retrieval
system designed to be used in the Internet's distributed environment.
This system contains Web pages that provide both information and controls.
Web system is open-ended and we can navigate to a new document in any direction. This is made possible with the help of a language called Hypertext Markup Language (HTML). Web pages contain HTML tags that enable us to find, retrieve, manipulate and display documents worldwide.
Java was meant to be used in distributed environments such as Internet.
Since, both the Web and Java share the same philosophy, Java could be easily incorporated into the Web system.
Before Java, the World Wide Web was limited to the display of still images and texts.
However, the incorporation of Java into Web pages has made it capable of supporting animation, graphics, games, and a wide range of special effects.
10
Main Features of JAVA
Compiled and Interpreted Java is a platform independent language Java is an Object Oriented languageSimpleRobust LanguageSecureHigh PerformanceDistributedMultithreaded and InteractivePortable
11
Compiled and Interpreted
• Computer Languages – Complied or interpreted.
• Java combines both these approaches, thus making
Java 2 stage system.
1) First Java Compiler translates source code into
bytecode instruction.
2) And in second stage, Java Interpreter generates
machine code , that can be directly executed by the
machine that runs java program.
Thus java is both. Compiled and Interpreted Language.
12
Platform independent and Portable• A platform is a pre-existing environment in which a program
runs, obeying its constraints, and making use of its facilities.
Lets come back to the point. During compilation, the compiler converts java
program to its byte code. This byte code can run on any platform such as
Windows, Linux, Mac/OS etc. Which means a program that is compiled on
windows can run on Linux and vice-versa. This is why java is known as platform
independent language.
13
Total Platform Independence
JAVA COMPILER
JAVA BYTE CODE
JAVA INTERPRETER
(translator)
(same for all platforms)
(one for each different system)
Windows 95 Macintosh Solaris Windows NT 14
Java as Object OrientedAlmost everything in java is an object. All program
code and data reside within classes and objects.
4 main concepts of Object Oriented programming are:
Abstraction Encapsulation Inheritance Polymorphism
15
Simple
Java is considered as one of simple language because it does not have complex features like Operator overloading, Multiple inheritance, pointers and Explicit memory allocation.
16
Robust Language Two main problems that cause program failures
are memory management mistakes and mishandled runtime errors. Java handles both of them efficiently.
1) Memory management mistakes can be overcome by garbage collection. Garbage collection is automatic (Memory de-allocation of objects which are no longer needed).
2) Mishandled runtime errors are resolved by Exception Handling procedures.
17
Secure Threat of viruses and abuse of resources are everywhere
while working on Internet. Java system not only verify all memory access, but also ensures that , no viruses are communicated with an applet.
It provides a virtual firewall between the application and the computer.
Java codes are confined within Java Runtime Environment (JRE) thus it does not grant unauthorized access on the system resources.
High Performance Performance is impressive due to intermediate byte code. Architecture is also designed to reduce runtime overheads. Multithreading enhances the overall execution speed of
Java program.
18
Java is distributed
Java is designed as distributed Language for creating application on network.
RMI(Remote Method Invocation) and EJB(Enterprise Java Beans) are used for creating distributed applications in java.
In simple words: The java programs can open and access remote object on internet as easy as the do it on local system.
This enables multiple programmer at multiple location to collaborate and work together on single project.
Distributed computing involves several computers working together on a network. Java is designed to make distributed computing easy. Since networking capability is inherently integrated into Java, writing network programs is like sending and receiving data to and from a file.
19
Multithreading Multithreading in java is a process of executing multiple threads
simultaneously. That means we do not have to wait for the application to finish one
task before beginning another. Thread is basically a lightweight sub-process, a smallest unit of
processing. Multiprocessing and multithreading, both are used to achieve multitasking.
But we use multithreading than multiprocessing because threads share a common memory area. They don't allocate separate memory area so saves memory, and context-switching between the threads takes less time than process.
Java Multithreading is mostly used in games, animation etc.Advantage of Java Multithreading
1) It doesn't block the user because threads are independent and you can perform multiple operations at same time.
2) You can perform many operations together so it saves time.3) Threads are independent so it doesn't affect other threads if
exception occur in a single thread.20
21
Anatomy of a Java Program Comments Package Reserved words Modifiers Statements Blocks Classes Methods The main method
Java comments:Use // text when you want to comment a single line
of code. Use /* text */ when you want to comment multiple
lines of code. Use /** documentation */ when you would want to
add some info about the program that can be used for automatic generation of program documentation.
Package: A package is a namespace that organizes a set
of related classes and interfaces. Conceptually you can think of packages as being similar to different folders on your computer. You might keep HTML pages in one folder, images in another, and scripts or applications in yet another.
22
Reserved words: Java Reserved Words. A Java identifier is a
sequence of Java letters and digits, the first of which must be a letter. Programmer-defined identifiers cannot have the same spelling as identifiers that are reserved. Reserved identifiers include keywords, twoBoolean literals, and the null literal.
Modifiers:Access Modifier within class within package• Private Y N• Default Y Y• Protected Y Y• Public Y Y
23
Java
Write Once, Run Anywhere
24
Java and C
Java is lot like a c Major difference is : Java is OOPL Java did not include:
data types – struct ,union.modifiers-auto ,extern,registerexplicit pointer typeno preprocessors like #define, #include etc.
25
Java and C++• Java is truly OOPL, while C++ is C with OO
extension• Following are some features omitted from
java• No Typedefs, Defines, or Preprocessor• No Global Variables• No Goto statements• No Pointers• No Unsafe Structures• No Multiple Inheritance• No Operator Overloading
26
Added or Improved over C++
Interfaces: type Vs. class InterfaceGarbage collectionExceptions (More powerful than C++)Strings Instanceof PackageMulti-threads
27
Java Development Kit
• Java environment includes large no of development tools and hundreds of classes and methods.
• The development tools are the part of the system : JDK.
• And classes and methods are the parts of : JSL(Java Standard Library) also known as: API (application program interface)
• JDK includes: appletviewer. Javac, java, javah, jdb etc.
28
Java Software
JDK JRE
29
Java Environment/ Life Cycle of Java Code
JavaBytecodes
move locallyor through
network
JavaSource(.java)
JavaCompiler
JavaBytecod
e(.class )
JavaInterpreter
Just in Time
Compiler
Runtime System
Class Loader
BytecodeVerifier
Java Class
Libraries
Operating System
Hardware
Runtime EnvironmentCompile-time
Environment
30
2 ways of using javaJava
Source
Code
Java Compiler
Java enabled
Web Browser
Java Interpret
er
Output Output
Applet Type Application Type
31
JVM (Java virtual Machine)• JVM – java virtual machine executes java program
by converting byte code into machine language of the current operating system’s understandable format. So JVM is platform dependent.
• Role: it takes class name as input and searches for a .class file with the given class name. If it is found, it reads and loads that .class file byte codes in to JVM, then starts the class logic by calling main method.
• Main method is only mandatory for execution, not for compilation. If class has no main method, program is compiled easily but cannot be executed.
32
JVM
1) Class loader accepts class files2) Compilation creates class files3) The interim memory is required during execution4) It consists of heaps, stacks and registers to store data5) JRE has native methods and libraries6) JVM runs two main threadsa) demonb) Non-demon threads
33
• Daemon ThreadsIt has been Run by JVM for itself. JVM decides on a thread for being a demon thread
It provides service to user threads for background supporting task.
Its life depends on user thread.When all user thread dies, jvm terminates this
thread automatically. (low priority threads)Ex: gc, finalizer etc.• Non-daemon threads or user thread
Main() is the initial and non-demon thread. Other implemented threads are also non-demon threads. The JVM is active till any non-demon thread is active.
34
Compilation1) The compiler requires to know the TYPE of every CLASS used in the program source code2) This is done by setting a default user environment variable CLASSPATH3) The Javac (Java Compiler) reads the program and converts it into byte code files called as class files
35
Java Source code
1) It essentially consists of a main() method2) This method is public and thus can be called by any object3) This method is also static and so can be called without instantiating the object of the class4) It does not return any value5) The controlling class of every Java application usually contain a main method6) This can be avoided to allow the class to be tested in a stand-alone mode.7) Other methods can subsequently be called in main()
36
Java Installation1) To Download a jdk file(32or 64 bit versons),
http://www.oracle.com/technetwork/java/javase/downloads/index.html
2) Select the “jdk” download button for the corresponding verson. The download button will open another page which will list the various jdk installation files.
3) Choose Accept License Agreement in order to continue the download process.
4) After accepting Licens, choose a file to download- “windows x86” for 32 bit windows os
5) “Windows x64” for 64 bit windows os.6) Save file7) Run 37
How to set the Path variable1) After you install the jdk file,2) Right click on my computer and select properties3) Select Advanced system setting4) Select advanced tab and right click environment
variable5) Go in system variable and select path6) Click on edit button and go till the last variable
value , in new Edit system variable pop up and paste the java jdk path
38
Java Program Structure
• To create a java code an editor such as notepad, text pad or an IDE like eclipse can be used.
Sample Java Code:
public class java1
{
public static void main(String[] args)
{ System.out.println("This is my first program in java");
}//End of main
}
39
public static void main(String[] args)Public: public is access specifier that declares main method as
unprotected- making it accessible to all other class.Static: static declares this method as one that belongs to entire class
and not as the part of any object of the class. The main must always be declared as static since the interpreter uses this method before any object is created.
Void: The type modifier Void states that the main method does not return any value.
String[] args: for command line arguments in java, is a java array of string object. This means that main function accepts an array of strings.
System.out.println("This is my first program in java");
Similar to printf or cout<< statements.Since java is truly object oriented language, every method must be
part of an object.Here, println method is member of out object , which is static data
member of System class.40
Compiling and RunningIn order to run a Java program: • First you compile it
– that is, you run a program called compiler that checks whether the program follows the Java syntax
– if it finds errors, it lists them – If there are no errors, it translates the program into Java
bytecode– Example: assume you created a program called
FirstJavaProgram.javaprompt>javac FirstJavaProgram.java
– If successful, this creates a file FirstJavaProgram.class which contains the translation (Java bytecode) of FirstJavaProgram.java
• Then you execute it– That is, you call the Java Virtual Machine to interpret and
execute the Java bytecode of your program– Example:
prompt>java FirstJavaProgramThis is my first program in java
41
Example 2package myproject;class welcomeMessage{ void printMessage() { System.out.println("Hello World"); } } class ex2 { public static void main(String []args) { welcomeMessage obj=new welcomeMessage(); obj.printMessage(); } }Output: Hello World
42
Interpreting the codea) Line 1. The package myproject creates a folder to store the class files generated after compilationb) Line2. It imports the class library java.lang and its subsequent classes(Boolean,int, char,enum,and many more) object is root class of all.c) Line 3. Initiates a class with the name WelcomeMessaged) Line 5. Declares a method with name printMessagee) Line 7. Defines the actual working code of the methodf) Line 10. Initiates the class having the main method; it should bear the name of the file : ex2.javag) Line 12. Declares the main methodh) Line 14. Initiates the creation of the objecti) Line 15. Calls the method printMessage () with the help of the objectj) The above code is saved and compiled to run on JVM
43
Variable declaration
type variable-name;Meaning: variable <variable-name> will be a
variable of type <type>Where type can be:
– int //integer– double etc. //real number
Example: int a, b, c; double x;int sum;
44
There are three kinds of variables in Java − Local variables Instance variables Class/Static
Local Variables: Local variables are declared in methods, constructors, or
blocks. Local variables are created when the method, constructor or
block is entered and the variable will be destroyed once it exits the method, constructor, or block.
Access modifiers cannot be used for local variables. Local variables are visible only within the declared method,
constructor, or block. Local variables are implemented at stack level internally. There is no default value for local variables, so local variables
should be declared and an initial value should be assigned before the first use.
45
Instance Variables Instance variables are declared in a class, but outside a
method, constructor or any block. When a space is allocated for an object in the heap, a slot
for each instance variable value is created. Instance variables are created when an object is created
with the use of the keyword 'new' and destroyed when the object is destroyed.
Access modifiers can be given for instance variables.
46
import java.io.*; public class Employee { // this instance variable is visible for any child class. public String name; // salary variable is visible in Employee class only. private double salary; // The name variable is assigned in the constructor. public Employee (String empName) { name = empName; } // The salary variable is assigned a value. public void setSalary(double empSal) { salary = empSal; } // This method prints the employee details. public void printEmp() { System.out.println("name : " + name ); System.out.println("salary :" + salary); } public static void main(String args[]) { Employee empOne = new Employee("Ransika"); empOne.setSalary(1000); empOne.printEmp(); } }
47
• Class/Static Variables Class variables also known as static variables are declared
with the static keyword in a class, but outside a method, constructor or a block.
There would only be one copy of each class variable per class, regardless of how many objects are created from it.
Static variables are stored in the static memory. It is rare to use static variables other than declared final and used as either public or private constants.
Static variables are created when the program starts and destroyed when the program stops.
48
49
Getting Input Using Scanner
1. Create a Scanner object
Scanner scanner = new Scanner(System.in);
2. Use the methods next(), nextByte(), nextShort(), nextInt(), nextLong(), nextFloat(), nextDouble(), or nextBoolean() to obtain to a string, byte, short, int, long, float, double, or boolean value. For example,
System.out.print("Enter a double value: ");Scanner scanner = new Scanner(System.in);double d = scanner.nextDouble();
package a;import java.util.Scanner;class GetInputData{ public static void main(String args[]) { int num; float fnum; String str; Scanner in = new Scanner(System.in); //Get input String System.out.println("Enter a string: "); str = in.nextLine(); System.out.println("Input String is: "+str); //Get input Integer System.out.println("Enter an integer: "); num = in.nextInt(); System.out.println("Input Integer is: "+num); //Get input float number System.out.println("Enter a float number: "); fnum = in.nextFloat(); System.out.println("Input Float number is: "+fnum); }}
50
Exercise Java Program ask to the user to enter the
number to check whether it is a prime number or not, then display it on the screen:
Java Program ask to the user to enter the year to check whether it is a leap year or not, then display it on the screen:
51
Basic Data Types Data type gives information about 1) Size of memory location and range of data that
can be stored on that location2) possible legal operations that can be performed
Java provides major two types of data types:1) Primitive or basic data types2) Referenced or derived data type
52
Data Types
Basic Types Referenced Types
Long8
Array
classinterface
enum
Float4
Double8
Boolen1
Char2
Short2
Byte1
Int 4
53
Data Types• For all data, assign a name (identifier) and a
data type • Data type tells compiler:
– How much memory to allocate– Format in which to store data– Types of operations you will perform on data
• Compiler monitors use of data– Java is a "strongly typed" language
• Java "primitive data types" byte, short, int, long, float, double, char,
boolean
Integer Types - Whole Numbers
Type Size Minimum Value Maximum Value in Bytesbyte 1 -128 127short 2 -32,768 32,767int 4 -2, 147, 483, 648 2, 147, 483, 647long 8 -9,223,372,036,854,775,808 9,223,372,036,854,775,807
Example declarations: int testGrade; int numPlayers, highScore, diceRoll; short xCoordinate, yCoordinate; byte ageInYears; long cityPopulation;
Floating-Point Data Types
• Numbers with fractional partsType Size Minimum Value Maximum
Value in Bytesfloat 4 1.4E-45 3.4028235E38double 8 4.9E-324
1.7976931348623157E308
Example declarations: float salesTax; double interestRate; double paycheck, sumSalaries;
char Data Type
• One Unicode character (16 bits - 2 bytes)
Type Size Minimum Value Maximum Value
in Byteschar 2 character
character encoded as 0
encoded as FFFFExample declarations: char finalGrade; char newline, tab, doubleQuotes;
boolean Data Type
• Two values only: true false
• Used for decision making or as "flag" variables
• Example declarations: boolean isEmpty; boolean passed, failed;
Assigning the Values of Other Variables
• Syntax: dataType variable2 = variable1;
• Rules:1. variable1 needs to be defined before
this statement appears in the source code
2. variable1 and variable2 need to be compatible data types; in other words, the precision of variable1 must be lower than or equal to that of variable2.
Compatible Data Types
Any type in right column can be assigned to type in left column:
Data Type Compatible Data Types byte byteshort byte, shortint byte, short, int, charlong byte, short, int, long, charfloat float, byte, short, int, long, chardouble float, double, byte, short, int, long, charboolean booleanchar char
Sample Assignments
• This is a valid assignment: float salesTax = .05f;
double taxRate = salesTax;
• This is invalid because the float data type is lower in precision than the double data type:
double taxRate = .05; float salesTax = taxRate;
Shortcut Operators++ increment by 1 -- decrement by
1Example: count++; // count = count + 1; count--; // count = count - 1;
Postfix version (var++, var--): use value of var in expression, then increment or decrement.
Prefix version (++var, --var): increment or decrement var, then use value in expression
See Example 2.11 ShortcutOperators
More Shortcut Operators
Operator Example Equivalent
+= a += 3; a = a + 3;
-= a -= 10; a = a - 10;
*= a *= 4; a = a * 4;
/= a /= 7; a = a / 7;
%= a %= 10; a = a % 10;
Common Error Trap
• No spaces are allowed between the arithmetic operator and the equals sign
• Note that the correct sequence is +=, not =+
Example: add 2 to a // incorrect a =+ 2; // a = +2; assigns 2 to 2
// correct a += 2; // a = a + 2;
Operator Precedence
Operator Order of
evaluationOperation
( ) left - right parenthesis for explicit grouping
++ -- right - left preincrement, predecrement
++ -- right - left postincrement, postdecrement
* / % left - right multiplication, division, modulus
+ - left - right addition or String concatenation, subtraction
= += -= *= /= %=
right - left assignment
Array Collection of values of similar data types,Syntax of 1 d array :1) datatype variablename[]= new datatype[size];or 2) datatype variablename[];Variablename= new datatype[size];
Example: 2) int a[]=new int[5];
3) int a[]; a=new int[5];
4) Int[] a=new int[5];
66
Example 1. import java.util.*;public class arr{public static void main(String x[]){ Scanner xyz=new Scanner(System.in);int a[]=new int[5];System.out.println("Length of array is"+a.length);System.out.println("enter the array elements");for(int i=0;i<a.length;i++){ a[i]=xyz.nextInt();}System.out.println("Display the array elements");for(int i=0;i<a.length;i++){System.out.println("a[]-----"+i+" "+a[i]);}}} 67
Two Dimentional ArrayTwo dimentional matrix is used to create the 2 d array, but memory cannot store 2d array as matrix it is stored sequentially in memory.
Syntax:datatype variablename[][]=new datatype[row][column];ordatatype variablename[][];Variablename= new datatype[row][column]; Example:int a[][]=new int[3][3];Java Program ask to the user to enter row and column size
of the array then ask to the user to enter the array elements, and the program will display the two dimensional array
68
Decision Making &Control Statements
In Java we have three types of basic loops: • For Loop• While Loop• Do While Loop
And three Decision making statement.If statementSwitch statementConditional operator statement
69
Syntax of for loop:
for (initialization; condition; increment/decrement) { statement(s) //block of statements }Mind the semicolon (;) after initialization and
condition in the above syntax.
70
• For loop example:class ForLoopExample { public static void main(String args[])
{ for(int i=10; i>1; i--){ System.out.println("The value of i is: "+i); } }
}The output of this program is:The value of i is: 10 The value of i is: 9 The value of i is: 8 The value of i is: 7 The value of i is: 6 The value of i is: 5 The value of i is: 4 The value of i is: 3 The value of i is: 2 71
• Infinite for loop: The importance of Boolean expression and increment/decrement operation co-ordination:
class ForLoopExample2 { public static void main(String args[])
{ for(int i=1; i>=1; i++){ System.out.println("The value of i is: "+i); } }
}• Here is another example of infinite for loop:// infinite loop for ( ; ; ) { // statement(s) }
72
• For loop example to iterate an array:• Here we are iterating and displaying array elements
using the for loop.class ForLoopExample3 { public static void main(String args[])
{ int arr[]={2,11,45,9}; for(int i=0; i<4; i++){ System.out.println(arr[i]); } }
}
Output:• 2 11 45 9
73
Java For-each Loop• The for-each loop is used to traverse array or collection in java. It is easier
to use than simple for loop because we don't need to increment value and use subscript notation.
• It works on elements basis not index. It returns element one by one in the defined variable.
Syntax:for(Type var:array){ //code to be executed }
Example:public class ForEachExample { public static void main(String[] args) { int arr[]={12,23,44,56,78}; for(int i:arr){ System.out.println(i); } Output: (on each new line) 12,23,44,56,78
74
Java Labeled For Loop• We can have name of each for loop. To do so,
we use label before the for loop. It is useful if we have nested for loop so that we can break/continue specific for loop.
• Normally, break and continue keywords breaks/continues the inner most for loop only.
Syntax:labelname: for(initialization;condition;incr/decr){ //code to be executed }
75
Example:public class LabeledForExample { public static void main(String[] args) { aa: for(int i=1;i<=3;i++){ bb: for(int j=1;j<=3;j++){ if(i==2&&j==2){ break aa; } System.out.println(i+" "+j); } } } } Output:1 1 1 2 1 3 2 1
76
While loop in Java Syntax of while loopwhile (Boolean expression) { statement(s) //block of statements }The logic in while loop is simple it executes the block of statements
when the Boolean expression returns true. It gets terminated when the Boolean expression returns false.
While loop exampleclass WhileLoopExample { public static void main(String args[]){ int i=10 while(i>1){ System.out.println(i); i--; } } }The output of this program is:
1098765,4,3,2,
77
Infinite while loopclass WhileLoopExample2
{ public static void main(String args[]){ int i=10; while(i>1) { System.out.println(i); i++; } } }This loop would never end, its an infinite while loop. This is because
condition is i>1 which would always be true as we are incrementing the value of i inside while loop.
• Here is another example of infinite while loop:• while (true){ statement(s); }
78
While loop example to iterate an array• Here we are iterating and displaying array elements using
while loop.class WhileLoopExample3
{ public static void main(String args[])
{ int arr[4]={2,11,45,9}; //i starts with 0 as array index starts with 0 too int i=0; while(i<4)
{ System.out.println(arr[i]); i++; }
} }Output:• 2 11 45 9
79
do-while loop in Java • do-while loop is similar to while loop, however there is a
single difference between these two. Unlike while loop, do-while guarantees at-least one execution of block of statements. This happens because the do-while loop evaluates the boolean expression at the end of the loop’s body. Therefore the set of statements gets executed at-least once before the check of boolean expression.
• Syntax of while loop:do{ statement(s) //block of statements }while (Boolean expression);
80
do-while loop example
class DoWhileLoopExample {
public static void main(String args[]){ int i=10; do{ System.out.println(i); i--; }while(i>1);
} }The output of this program is:
1098765432
81
do-while loop example to iterate an array
• Here we are iterating and displaying array elements using do-while loop.class DoWhileLoopExample2 { public static void main(String args[])
{ int arr[4]={2,11,45,9}; int i=0; do{ System.out.println(arr[i]); i++; }while(i<4);
} }
Output:211459
82
Java If-else Statement
• The Java if statement is used to test the condition. It checks boolean condition: true or false. There are various types of if statement in java.
if statement if-else statementnested if statement if-else-if ladder
83
public class IfElseIfExample { public static void main(String[] args) { int marks=65; if(marks<50){ System.out.println("fail"); } else if(marks>=50 && marks<60){ System.out.println("D grade"); } else if(marks>=60 && marks<70){ System.out.println("C grade"); } else if(marks>=70 && marks<80){ System.out.println("B grade"); } else if(marks>=80 && marks<90){ System.out.println("A grade"); }else if(marks>=90 && marks<100){ System.out.println("A+ grade"); }else{ System.out.println("Invalid!"); } } } Output: C grade 84
Java Switch StatementThe Java switch statement executes one statement from
multiple conditions. It is like if-else-if ladder statement.Syntax:switch(expression){ case value1: //code to be executed; break; //optional case value2: //code to be executed; break; //optional ...... default: code to be executed if all cases are not matched; }
85
Java Switch Statement is fall-through
• The java switch statement is fall-through. It means it executes all statement after first match if break statement is not used with switch cases.
Example:public class SwitchExample2 { public static void main(String[] args) { int number=20; switch(number){ case 10: System.out.println("10"); case 20: System.out.println("20"); case 30: System.out.println("30"); default:System.out.println("Not in 10, 20 or 30"); } }}
Output:20 30 Not in 10, 20 or 30
86
Java Break Statement• The Java break is used to break loop or switch statement. It breaks the
current flow of the program at specified condition. In case of inner loop, it breaks only inner loop.
Syntax:jump-statement; break; Example:public class BreakExample { public static void main(String[] args) { for(int i=1;i<=10;i++){ if(i==5){ break; } System.out.println(i); } } } Output:1 2 3 4 87
Java Continue Statement
• The Java continue statement is used to continue loop. It continues the current flow of the program and skips the remaining code at specified condition. In case of inner loop, it continues only inner loop.
Syntax:jump-statement; continue;
88
Java Continue Statement with Inner Loop• It continues inner loop only if you use continue statement
inside the inner loop.Example:public class ContinueExample2 { public static void main(String[] args) { for(int i=1;i<=3;i++){ for(int j=1;j<=3;j++){ if(i==2&&j==2){ continue; } System.out.println(i+" "+j); } } } } Output: (using tab)1 1 1 2 1 3 2 1 2 3 3 1 3 2 3 3 89
90
Java StringIn java, string is basically an object that represents sequence of char
values.An array of characters works same as java string.
For example:char[] ch={'j','a','v','a'};
Java String provides a lot of concepts that can be performed on a string such as compare, concat, equals, split, length, replace, compareTo, substring etc.
String s=new String(ch); is same as:String s=“java";
The java.lang.String class
The java String is immutable i.e. it cannot be changed but a new instance is created. For mutable class, you can use StringBuffer and StringBuilder class.
91
What is String in java
Generally, string is a sequence of characters. But in java, string is an object that represents a sequence of characters. String class is used to create string object.
How to create String object?There are two ways to create String object: By string literal By new keyword
92
1) String LiteralJava String literal is created by using double quotes. For Example:String s="welcome"; Each time you create a string literal, the JVM checks the string
constant pool first. If the string already exists in the pool, a reference to the pooled instance is returned. If string doesn't exist in the pool, a new string instance is created and placed in the pool. For example:
String s1="Welcome"; String s2="Welcome";//will not create new instance Note: String objects are stored in a special memory area
known as string constant pool.
93
2) By new keywordString s=new String("Welcome");//creates two objects and one reference variable In such case, JVM will create a new string object in normal(non pool) heap memory
and the literal "Welcome" will be placed in the string constant pool. The variable s will refer to the object in heap(non pool).
Java String Example
public class StringExample{public static void main(String arg[]){String s1="java";//creating string by java string literalchar ch[]={'s','t','r','i','n','g','s'};String s2=new String(ch);//converting char array to stringString s3=new String("example");
//creating java string by new keywordSystem.out.println(s1);System.out.println(s2);System.out.println(s3);}}
94
Java String class methodsThe java.lang.String class provides many useful methods
to perform operations on sequence of char values.No. MethodDescription1) char charAt(int index) returns char value for
the particular index
2) int length() returns string length
3) String substring(int beginIndex) returns substring for given begin index
4) String substring(int beginIndex, int endIndex) returns substring for given begin index and end index
95
Java String class methods Java String toUpperCase() and toLowerCase() methodThe java string toUpperCase() method converts this string into
uppercase letter and string toLowerCase() method into lowercase letter.
String s="Sachin"; System.out.println(s.toUpperCase());//SACHIN System.out.println(s.toLowerCase());//sachin System.out.println(s);//Sachin(no change in original)
Java String trim() methodThe string trim() method eliminates white spaces before and
after string.
Java String startsWith() and endsWith() methodString s="Sachin"; System.out.println(s.startsWith("Sa"));//true System.out.println(s.endsWith("n"));//true
96
Java String charAt() methodThe string charAt() method returns a character at specified index.String s="Sachin"; System.out.println(s.charAt(0));//S System.out.println(s.charAt(3));//h
Java String length() methodThe string length() method returns length of the string.String s="Sachin"; System.out.println(s.length());//6
Java String replace() methodThe string replace() method replaces all occurrence of first
sequence of character with second sequence of character.String s1="Java is a programming language. Java is a platform. Ja
va is an Island."; String replaceString=s1.replace("Java","Kava");//
replaces all occurrences of "Java" to "Kava" System.out.println(replaceString); 97
Java String compareTo()The java string compareTo() method compares the given string with current
string lexicographically. It returns positive number, negative number or 0.It compares strings on the basis of Unicode value of each character in the
strings.if s1 > s2, it returns positive number if s1 < s2, it returns negative number if s1 == s2, it returns 0
public class CompareToExample{ public static void main(String args[]){ String s1="hello"; String s2="hello"; String s3="meklo"; String s4="hemlo"; String s5="flag"; System.out.println(s1.compareTo(s2));//0 because both are equal System.out.println(s1.compareTo(s3));//-5 because "h" is lower by 5 than "m" System.out.println(s1.compareTo(s4)); // -1
because "l" is 1 times lower than "m" System.out.println(s1.compareTo(s5));//
2 because "h" is 2 times greater than "f" }}
98
Java String compareTo(): empty stringIf you compare string with blank or empty string, it returns
length of the string. If second string is empty, result would be positive. If first string is empty, result would be negative.
Java String concatThe java string concat() method combines specified string
at the end of this string. It returns combined string. It is like appending another string.
public class ConcatExample{ public static void main(String args[]){ String s1="java string"; s1.concat("is immutable"); System.out.println(s1); s1=s1.concat(" is immutable so assign it explicitly"); System.out.println(s1); }}
99
Substring in JavaA part of string is called substring. In other words, substring is a
subset of another string. In case of substring startIndex is inclusive and endIndex is exclusive.
You can get substring from the given string object by one of the two methods:
1. public String substring(int startIndex): This method returns new String object containing the substring of the given string from specified startIndex (inclusive).
2. public String substring(int startIndex, int endIndex): This method returns new String object containing the substring of the given string from specified startIndex to endIndex.
In case of string:startIndex: inclusiveendIndex: exclusive
String s="hello"; System.out.println(s.substring(0,2));//he
100
Java String split
The java string split() method splits this string against given regular expression and returns a char array.
Syntax:1. public String split(String regex) and, 2. public String split(String regex, int limit) Parameterregex : regular expression to be applied on string.limit : limit for the number of strings in array. If it is zero, it will returns all
the strings matching regex.
public class SplitExample{ public static void main(String args[]){ String s1="java string split method"; String[] words=s1.split("\\s");//splits the string based on whitespace //using java foreach loop to print elements of string array for(String w:words){ System.out.println(w); } }} 101
2. Java String split() method with regex and length example
public class SplitExample2{ public static void main(String args[]){ String s1="welcome to split world"; System.out.println("returning words:"); for(String w:s1.split("\\s",0)){ System.out.println(w); } System.out.println("returning words:"); for(String w:s1.split("\\s",1)){ System.out.println(w); } System.out.println("returning words:"); for(String w:s1.split("\\s",2)){ System.out.println(w); } }}
102
Java StringBuffer class Java StringBuffer class is used to created mutable (modifiable) string.
The StringBuffer class in java is same as String class except it is mutable i.e. it can be changed.
Important Constructors of StringBuffer class:StringBuffer(): creates an empty string buffer with the initial capacity of
16.StringBuffer(String str): creates a string buffer with the specified string.StringBuffer(int capacity): creates an empty string buffer with the
specified capacity as length.
Important methods of StringBuffer class1. public synchronized StringBuffer append(String s): is used to
append the specified string with this string. The append() method is overloaded like append(char), append(boolean), append(int), append(float), append(double) etc.
2. public synchronized StringBuffer insert(int offset, String s): is used to insert the specified string with this string at the specified position. The insert() method is overloaded like insert(int, char), insert(int, boolean), insert(int, int), insert(int, float), insert(int, double) etc.
103
public StringBuffer replace(int startIndex, int endIndex, String str): is used to replace the string from specified startIndex and endIndex.
public StringBuffer delete(int startIndex, int endIndex): is used to delete the string from specified startIndex and endIndex.
public synchronized StringBuffer reverse(): is used to reverse the string. public int capacity(): is used to return the current capacity.
public void ensureCapacity(int minimumCapacity): is used to ensure the capacity at least equal to the given minimum.
public char charAt(int index): is used to return the character at the specified position.
public int length(): is used to return the length of the string i.e. total number of characters.
public String substring(int beginIndex): is used to return the substring from the specified beginIndex.
public String substring(int beginIndex, int endIndex): is used to return the substring from the specified beginIndex and endIndex.
104
105
Java I/OWriting to user
(output)System.out.println(variable-name);
prints the value of variable <variable-name> to the user
System.out.println(“any message “);prints the message within quotes to the user
System.out.println(“hello” + “world” + a + “plus“ + b);assuming the value of a is 3 and of b is 7, it printshelloworld3plus7
Note: System.out.println() always prints on a new line.
106
InputIf we want to calculate the addition of two numbers,by runtime accepting the input values from keyboard, java provides us following ways:
1) Use command line argument: i.e if we pass parameter to main function from command prompt at runtime because main method has one single parameter of type string – is called command line argument.We can overload main method using different parameters ,but we cannot execute java application string parameter in main, because JVM has only one signature of main method having string[].
107
Example of command line argument
• public class Cal• {public static void main(String x[])• {• int a,b,c;• //x[5]=new String();• a= Integer.parseInt(x[0]);• b=Integer.parseInt(x[1]);• c=a+b;• System.out.println("Addition is:"+c);• }• }• //run configuration-Arguments-run
108
2) Use of Scanner class:-Member of java.util package-This is used to accept the input at runtime on new line.
If we want to use scanner class in java, following steps are requiredi) Add java.util package in a programii) create the object of scanner classiii) By using some methods, perform operations on
scanner class
109
Example using scanner class• import java.util.*;• public class Cal1• { public static void main (String x[])• {• Scanner xyz=new Scanner(System.in);• System.out.println("enter the first value");• int a,b,c;• a=xyz.nextInt();• System.out.println("enter second no");• b=xyz.nextInt();• c=a+b;• System.out.println("Addition is"+c);• xyz.close();• }• }
110