You are on page 1of 78

1.

Introductions to Java and java Applications


qJames Gosling-1995
qJava is an OOP language that was designed to meet the need for the platform-
independent language.
qJava is used to create application that can run on a single computer as well as a
distributed network.
qJava is used to develop a stand-alone and Internet-based applications.
qThe Java programs works on any type of compatible device that supports Java.
qJava programming language was originally developed by Sun Microsystems, which was
initiated by James Gosling and released in 1995 .
qAs of December 08 the latest release of the Java Standard Edition is 6 (J2SE).
qSun Microsystems has renamed the new J2 versions as Java SE, Java EE and Java ME
respectively.
qJava is guaranteed to beWrite Once, Run Anywhere
1.1 Needs for Java
• Java can be used to write variety of application
o Applications that use CUI
o Application that use GUI
o Applets
o Servlets
o Packages
Year Development
1990 Sun Microsystems developed software to manipulate electronic devices.
1991 A new language named Oak was introduced using the most popular object-oriented
language C++.
1993 World Wide Web(WWW) appeared on the Internet that transformed the text-based
Internet into graphical Internet.
1994 The Sun Microsystems team developed a Web browser called HotJava to locate and run
applets programs on Internet.
1995 Oak was rename as Java.
1996 Java was established as an object-oriented language.
2. Java Virtual Machine: JDK,JRE, JVM,Byte code
3.What are the characteristics of java?
What are the characteristics of java?(cont'd)
Simple :
Java is Easy to write and more readable and eye catching.
Java has a concise, cohesive set of features that makes it easy to learn and use.
Most of the concepts are drew from C++ thus making Java learning simpler.
Secure :
Java program cannot harm other system thus making it secure.
Java provides a secure means of creating Internet applications.
Java provides secure way to access web applications.
Portable :
Java programs can execute in any environment for which there is a Java run-time
system.(JVM)
Java programs can be run on any platform (Linux,Window,Mac)
Java programs can be transferred over world wide web (e.g applets)
Object-oriented :
Java programming is object-oriented programming language.
Like C++ java provides most of the object oriented features.
Java is pure OOP. Language. (while C++ is semi object oriented)
Robust :
Java encourages error-free programming by being strictly typed and
performing run-time checks.
Multithreaded :
Java provides integrated support for multithreaded programming.
Architecture-neutral :
Java is not tied to a specific machine or operating system architecture.
Machine Independent i.e Java is independent of hardware .
Interpreted :
Java supports cross-platform code through the use of Java bytecode.
Bytecode can be interpreted on any platform by JVM.
High performance :
Bytecodes are highly optimized.
JVM can executed them much faster .
Distributed :
Java was designed with the distributed environment.
Java can be transmit,run over internet.
Dynamic :
Java programs carry with them substantial amounts of run-time type
information that is used to verify and resolve accesses to objects at run time.
3.1 Object Oriented Principles
Object oriented principles:
1. Object
2. Class
3. Abstraction
4. Encapsulation
5. Inheritance
6. Polymorphism

They are also known as pillars of the object oriented programming paradigm.
1. Object:
Any entity that has state and behaviour is known as an object. For example: chair, pen, table,
keyboard, bike etc. It can be physical and logical.
2. Class:
Collection of objects is called class. It is a logical entity.
3. Abstraction
•Abstraction in OOPs is very easy to understand when you relate it to the real time example. For example,
when you drive your car you do not have to be concerned with the exact internal working of your car.
What you are concerned with is interacting with your car via its interfaces like steering wheel, brake
pedal, accelerator pedal etc. Here the knowledge you have of your car is abstract.
•In computer science, abstraction is the process by which data and programs are defined with a
representation similar in form to its meaning (semantics) while hiding away the implementation details.
•In more simple terms, abstraction is to hide information that is not relevant to context or rather show
only relevant information and to simplify it by comparing it to something similar in the real world.
•Abstraction captures only those details about an object that is relevant to the current perspective.
3.1 Data abstraction
Data abstraction is the way to create complex data types from multiple smaller data types
– which is more close to real life entity. e.g. An Employee class can be a complex object of
having various small associations.
public class Employee
{
private Department department;
private Address address;
private Education education;
//So on...
}
So, if you want to fetch information of a employee, you ask it from Employee object – as
you do in real life, ask the person itself.
3.2 Control abstraction
Control abstraction is achieved by hiding the sequence of actions for a complex task – inside a simple
method call, so logic to perform the task can be hidden from the client and could be changed in future
without impacting the client code.
public class EmployeeManager
{
public Address getPrefferedAddress(Employee e)
{
//Get all addresses from database
//Apply logic to determine which address is preferred
//Return address
}
}
In above example, tomorrow if you want to change the logic so that everytime domestic address is
always the preferred address, you will change the logic inside getPrefferedAddress() method, and client
will be unaffected.
4.Encapsulation
Wrapping data and methods within classes in combination with implementation
hiding (through access control) is often called encapsulation in OOPs. The result is
a data type with characteristics and behaviors. Encapsulation essentially has both
i.e. information hiding and implementation hiding.

“Whatever changes, encapsulate it” – A famous design principle

Information hiding is done through using access control modifiers (public, private,
protected) and implementation hiding is achieved through creation of interface
for a class.
Implementation hiding gives the designer the freedom to modify how the
responsibility is fulfilled by an object. This is especially valuable at points where
the design (or even the requirements) are likely to change.
4.1. Information hiding
class InformationHiding
{
//Restrict direct access to inward data
private ArrayList items = new ArrayList();

//Provide a way to access data - internal logic can safely be changed in future
public ArrayList getItems(){
return items;
}
}
4.2 Implementation hiding
interface ImplemenatationHiding {
Integer sumAllItems(ArrayList items);
}
class InformationHiding implements ImplemenatationHiding
{
//Restrict direct access to inward data
private ArrayList items = new ArrayList();
//Provide a way to access data - internal logic can safely be changed in future
public ArrayList getItems(){
return items;
}
public Integer sumAllItems(ArrayList items) {
//Here you may do N number of things in any sequence
//Which you do not want your clients to know
//You can change the sequence or even whole logic
//without affecting the client
}
}
5. Inheritance
Inheritance is another important concept in object oriented programming. Inheritance in Java is
a mechanism by which one object acquires the properties and behaviors of the parent object.
It’s essentially creating a parent-child relationship between classes. In Java, you will use
inheritance mainly for code re-usability and maintainability.

Keyword “extends” is used to inherit a class in java. The “extends” keyword indicates that you
are making a new class that derives from an existing class. In the terminology of Java, a class
that is inherited is called a super class. The new class is called a subclass.

A subclass inherits all the non-private members (fields, methods, and nested classes) from its
superclass. Constructors are not members, so they are not inherited by subclasses, but the
constructor of the superclass can be invoked from the subclass.
class Employee
{
private Department department;
private Address address;
private Education education;
//So on...
}
class Manager extends Employee {
private List<Employee> reportees;
}
In above example, Manager is specialized version of Employee and reuses department, address
and education from Employee class as well as define it’s own reportees list.
6. Polymorphism
Polymorphism is the ability by which, we can create functions or reference
variables which behaves differently in different programmatic context.

In java language, polymorphism is essentially considered into two versions:

Compile time polymorphism (static binding or method overloading)


Runtime polymorphism (dynamic binding or method overriding)
4. A simple java program, compiling and executing
1. //Text-printing program.
2. Public class Welcome
3. { //main method begins execution of java application
4. Public static void main(String args[ ])
5. {
6. System.out.println(“welcome to Java Programming”);
7. }//end method main
8. }//end class Welcome
To compile the above program the command used is:
javac Welcome.java
To Execute:
java Welcome
Output : Welcome to Java Programming
5.Data types, Operators, Expressions, scope of the
variable, type conversion and casting
Variable: It is name of reserved area allocated in memory.
int data=50;//Here data is variable
Types of Variables:
Local Variable
A variable that is declared inside the method is called local variable.
Instance Variable
A variable that is declared inside the class but outside the method is called instance variable . It is
not declared as static.
Static variable
A variable that is declared as static is called static variable. It cannot be local.
Example :
class A{
int data=50;//instance variable
static int m=100;//static variable
void method(){
int n=90;//local variable
}
}//end of class
5.1 Data Types in Java
In java, there are two types of data types
primitive data types
non-primitive data types
Data Type Default Value Default size

boolean false 1 bit

char '\u0000' 2 byte

byte 0 1 byte

short 0 2 byte

int 0 4 byte

long 0L 8 byte

float 0.0f 4 byte

double 0.0d 8 byte

Why char uses 2 byte in java and what is \u0000 ?


because java uses unicode system rather than ASCII code system. \u0000 is the lowest range of
unicode system.
5.2 Operators & Expressions
java provides a rich set of operators to manipulate variables.
We can divide all the Java operators into the following groups:
Ø Arithmetic Operators
Ø Relational Operators
Ø Bitwise Operators
Ø Logical Operators
Ø Assignment Operators
Ø Misc Operators
The Arithmetic Operators:
Arithmetic operators are used in mathematical expressions in the same way that they are used in algebra. The
following table lists the arithmetic operators: Assume integer variable A holds 10 and variable B holds 20, then:

Operator Description Example with Expressions


Addition - Adds values on either side of
+ the operator A + B will give 30

Subtraction - Subtracts right hand operand from


- left hand operand A - B will give -10

Multiplication - Multiplies values on either side of


* the operator A * B will give 200

Division - Divides left hand operand by right hand


/ operand B / A will give 2

Modulus - Divides left hand operand by right


% hand operand and returns remainder B % A will give 0

Increment - Increases the value of operand by 1


++ B++ gives 21
Decrement - Decreases the value of operand by 1
-- B-- gives 19
The Relational Operators:
• There are following relational operators supported by Java language
• Assume variable A holds 10 and variable B holds 20, then:
Operator Description Examples with Expressions
Checks if the values of two operands are equal or not, if
== yes then condition becomes true. (A == B) is not true.

!= Checks if the values of two operands are equal or not, if (A != B) is true.


values are not equal then condition becomes true.

Checks if the value of left operand is greater than the


> value of right operand, if yes then condition becomes (A > B) is not true.
true.

Checks if the value of left operand is less than the value


< of right operand, if yes then condition becomes true. (A < B) is true.

Checks if the value of left operand is greater than or


>= equal to the value of right operand, if yes then (A >= B) is not true.
condition becomes true.

Checks if the value of left operand is less than or equal


<= to the value of right operand, if yes then condition (A <= B) is true.
becomes true.
The Bitwise Operators:
• Java defines several bitwise operators, which can be applied to the integer
types, long, int, short, char, and byte.
• Bitwise operator works on bits and performs bit-by-bit operation. Assume if a =
60; and b = 13; now in binary format they will be as follows:
a = 0011 1100
b = 0000 1101

a&b = 0000 1100


a|b = 0011 1101
a^b = 0011 0001
~a = 1100 0011
The following table lists the bitwise operators:
Assume integer variable A holds 60 and variable B holds 13 then:
Operator Description Examples with Expressions
Binary AND Operator copies a bit to the result if it
& exists in both operands. (A & B) will give 12 which is 0000 1100
Binary OR Operator copies a bit if it exists in either
| operand. (A | B) will give 61 which is 0011 1101
Binary XOR Operator copies the bit if it is set in one
^ operand but not both. (A ^ B) will give 49 which is 0011 0001
(~A ) will give -61 which is 1100 0011 in
~ Binary Ones Complement Operator is unary 2's complement form due to a signed
and has the effect of 'flipping' bits. binary number.
Binary Left Shift Operator. The left operands value is
<< moved left by the number of bits specified by the right A << 2 will give 240 which is 1111 0000
operand.

Binary Right Shift Operator. The left operands value is


>> moved right by the number of bits specified by the A >> 2 will give 15 which is 1111
right operand.

Shift right zero fill operator. The left operands value is


moved right by the number of bits specified by the
>>> A >>>2 will give 15 which is 0000 1111
right operand and shifted values are filled up with
zeros.
The Logical Operators:
• The following table lists the logical operators:
• Assume Boolean variables A holds true and variable B holds false, then:

Operator Description Example


Called Logical AND operator. If both the
&& operands are non-zero, then the condition (A && B) is false.
becomes true.

Called Logical OR Operator. If any of the


|| two operands are non-zero, then the (A || B) is true.
condition becomes true.

Called Logical NOT Operator. Use to


! reverses the logical state of its operand. If a !(A && B) is true.
condition is true then Logical NOT operator
will make false.
The Assignment Operators:
• There are following assignment operators supported by Java language:
Operator Description Example

Simple assignment operator, Assigns values from


= C = A + B will assign value of A + B into
right side operands to left side operand
C

Add AND assignment operator, It adds right


operand to the left operand and assign the result
+= to left operand C += A is equivalent to C = C + A

Subtract AND assignment operator, It subtracts


right operand from the left operand and assign
-= the result to left operand C -= A is equivalent to C = C - A

Multiply AND assignment operator, It multiplies


right operand with the left operand and assign
*= the result to left operand C *= A is equivalent to C = C * A
Operator Description Example
Divide AND assignment operator, It
/= divides left operand with the right operand and C /= A is equivalent to C = C / A
assign the result to left operand

Modulus AND assignment operator, It takes


%= modulus using two operands and assign the C %= A is equivalent to C = C % A
result to left operand

<<= Left shift AND assignment operator C <<= 2 is same as C = C << 2

>>= Right shift AND assignment operator C >>= 2 is same as C = C >> 2

&= Bitwise AND assignment operator C &= 2 is same as C = C & 2

bitwise exclusive OR and assignment operator


^= C ^= 2 is same as C = C ^ 2

bitwise inclusive OR and assignment


|= operator C |= 2 is same as C = C | 2
Misc Operators
There are few other operators supported by Java Language.
1.Conditional Operator ( ? : ):
Conditional operator is also known as the ternary operator. This operator consists
of three operands and is used to evaluate Boolean expressions.
The goal of the operator is to decide which value should be assigned to the
variable. The operator is written as:
Variable x=(expression) ? Value if true : value if false.
Consider a=20, b=30
x=(a<b)?a:b;
since a is less than b the value of a is stored in x which is 20.
2.instanceof Operator:
This operator is used only for object reference variables. The operator checks whether
the object is of a particular type(class type or interface type). instanceof operator is
written as:
Syntax:
( Object reference variable ) instanceof (class/interface type) Ex:
public class Test {
public static void main(String args[]){ String name = "James";
// following will return true since name is type of String boolean result = name
instanceof String; System.out.println( result );
}
}
Precedence of Java Operators:
• Operator precedence determines the grouping of terms in an expression. This
affects how an expression is evaluated. Certain operators have higher
precedence than others; for example, the multiplication operator has higher
precedence than the addition operator:
• For example, x = 7 + 3 * 2; here x is assigned 13, not 20 because operator * has
higher precedence than +, so it first gets multiplied with 3*2 and then adds into
7.
• Here, operators with the highest precedence appear at the top of the table,
those with the lowest appear at the bottom. Within an expression, higher
precedence operators will be evaluated first.
Category Operator Associativity
Postfix () [] . (dot operator) Left to right

Unary ++ - - ! ~ Right to left


Multiplicative */% Left to right
Additive +- Left to right
Shift >> >>> << Left to right
Relational > >= < <= Left to right
Equality == != Left to right
Bitwise AND & Left to right
Bitwise XOR ^ Left to right
Bitwise OR | Left to right
Logical AND && Left to right
Logical OR || Left to right
Conditional ?: Right to left
Assignment = += -= *= /= %= >>= <<= &= ^= |= Right to left

Comma , Left to right


5.3 Scope of Variables In Java
• Scope of a variable is the part of the program where the variable is accessible. Like C/C++,
in Java, all identifiers are lexically (or statically) scoped, i.e.scope of a variable can
determined at compile time and independent of function call stack.
Some Important Points about Variable scope in Java:
• In general, a set of curly brackets { } defines a scope.
• In Java we can usually access a variable as long as it was defined within the same set of
brackets as the code we are writing or within any curly brackets inside of the curly brackets
where the variable was defined.
• Any variable defined in a class outside of any method can be used by all member
methods.
• When a method has the same local variable as a member, this keyword can be used to
reference the current class variable.
• For a variable to be read after the termination of a loop, It must be declared before the
body of the loop.
Java programs are organized in the form of classes. Every class is part of some package. Java scope rules
can be covered under following categories.
Member Variables (Class Level Scope)
These variables must be declared inside class (outside any function). They can be directly accessed
anywhere in class. Let’s take a look at an example:
public class Test
{
// All variables defined directly inside a class are member variables
int a;
private String b
void method1() {....}
int method2() {....}
char c;
}
•We can declare class variables anywhere in class, but outside methods.
•Access specified of member variables doesn’t effect scope of them within a class.
Local Variables (Method Level Scope)
Variables declared inside a method have method Another example of method scope, except
level scope and can’t be accessed outside the this time the variable got passed in as a
method.
parameter to the method:

public class Test class Test


{ {
void method1() private int x;
{ public void setX(int x)
{
// Local variable (Method level scope)
this.x = x;
int x; }
} }
}
The above code uses this keyword to
Note : Local variables don’t exist after method’s differentiate between the local and class
execution is over. variables.
predict the output of following Java program.
public class Test
Output:
{
static int x = 11; Test.x: 22
private int y = 33;
public void method1(int x)
t.x: 22
{ t.y: 33
Test t = new Test(); y: 44
this.x = 22;
y = 44;

System.out.println("Test.x: " + Test.x);


System.out.println("t.x: " + t.x);
System.out.println("t.y: " + t.y);
System.out.println("y: " + y);
}

public static void main(String args[])


{
Test t = new Test();
t.method1(5);
}
}
Example of loop scope.
Predict the output of following program Output :
class Test
{ 6: error: variable a is already defined in method
public static void main(String args[]) go(int)
{ for (int a = 0; a < 5; a++)
int a = 5; ^
for (int a = 0; a < 5; a++) 1 error
{
System.out.println(a);
}
}
}
5.4 type Conversion & type casting
Basis for Type Casting Type Conversion
Comparison
Meaning One data type is assigned to another by the user, using a Conversion of one data type to another
cast operator then it is called "Type Casting". automatically by the compiler is called
"Type Conversion".
Applied Type casting can also be applied to two 'incompatible' Type conversion can only be implemented
data types. when two data types are 'compatible'.

Operator For casting a data type to another, a casting operator '()' is No operator required.
required.
Size of Data Types Destination type can be smaller than source type. Here the destination type must be larger
than source type.
Implemented It is done during program designing. It is done explicitly while compiling.
Conversion type Narrowing conversion. Widening conversion.

Example int a; int a=3;


byte b; float b;
... b=a; // value in b=3.000.
...
In Java, there are two types of casting:
1. Widening Casting (automatically) - converting a smaller type to a larger type
size
byte -> short -> char -> int -> long -> float -> double
2. Narrowing Casting (manually) - converting a larger type to a smaller size type
double -> float -> long -> int -> char -> short -> byte
• Widening Casting:
Widening casting is done automatically when passing a smaller size type to a
larger size type:
public class MyClass {
public static void main(String[] args) {
int myInt = 9;
double myDouble = myInt; // Automatic casting: int to double

System.out.println(myInt); // Outputs 9
System.out.println(myDouble); // Outputs 9.0
}
}
Narrowing Casting:
Narrowing casting must be done manually by placing the type in parentheses in
front of the value:
Example
public class MyClass {
public static void main(String[] args) {
double myDouble = 9.78;
int myInt = (int) myDouble; // Manual casting: double to int

System.out.println(myDouble); // Outputs 9.78


System.out.println(myInt); // Outputs 9
}
}
6.1 Branch Control Statements
Java If-else Statement
The Java if statement is used to test the condition. It returns true or false.
Types of if statement in java.
Øif statement
Øif-else statement
Ønested if statement
Øif-else-if ladder
Java IF Statement
The if statement tests the condition. It executes the if statement if condition is true.
Syntax:
if(condition){
//code to be executed
}
Example:
public class IfExample {
public static void main(String[] args) {
int age=20;
if(age>18){
System.out.print("Age is greater than 18");
}
}
}
Output:
Age is greater than 18
Java IF-else Statement
The if-else statement also tests the condition.It executes the if block if condition is true
otherwise else block.

Syntax:
if(condition){
//code if condition is true
}else{
//code if condition is false
}
Example:
public class IfElseExample {
public static void main(String[] args) {
int number=13;
if(number%2==0){
System.out.println("even number");
}
else{
System.out.println("odd number");
}
}
}
Output:
odd number
Java IF-else-if ladder Statement
The if-else-if ladder statement executes one condition from multiple
statements.
Syntax:
if(condition1){
//code to be executed if condition1 is true
}else if(condition2){
//code to be executed if condition2 is true
}
else if(condition3){
//code to be executed if condition3 is true
}
...
else{
//code to be executed if all the conditions are false
}
Example:
else if(marks>=80 && marks<90){
public class IfElseIfExample {
System.out.println("A grade");
public static void main(String[] args) {
}
int marks=65;
else if(marks>=90 && marks<100)
if(marks<50){ {
System.out.println("fail"); System.out.println("A+ grade");
} }else{
else if(marks>=50 && marks<60){ System.out.println("Invalid!");
System.out.println("D grade"); }
} }
else if(marks>=60 && marks<70){ }
System.out.println("C grade"); Output: C grade
}
else if(marks>=70 && marks<80){
System.out.println("B grade");
}
6.2 Selection Statement
Java Switch Statement
The Java switch statement is 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;
}
Example:
public class SwitchExample {
public static void main(String[] args) {
int number=20;
switch(number){
case 10: System.out.println("10");break;
case 20: System.out.println("20");break;
case 30: System.out.println("30");break;
default:System.out.println("Not in 10, 20 or 30");
}
}
}
Output:20
Java Switch Statement if 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
6.3 Iteration Statements
Java For Loop
The Java for loop is used to iterate a part of the program several times. If the
number of iteration is fixed, it is recommended to use for loop.
There are three types of for loop in java.
•Simple For Loop
•For-each or Enhanced For Loop
•Labeled For Loop
Java Simple For Loop
The simple for loop is same as C/C++. We can initialize variable,check condition and
increment/decrement value.
Syntax:
for(initialization;condition;incr/decr){
//code to be executed
} Output:
1
Example: 2
public class ForExample { 3
public static void main(String[] args) { 4
5
for(int i=1;i<=10;i++){ 6
System.out.println(i); 7
} 8
9
} 10
}
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:
Output:
public class ForEachExample {
12
public static void main(String[] args) {
23
int arr[]={12,23,44,56,78};
44
for(int i:arr){
56
System.out.println(i);
78
}
}}
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
}
Example:
public class LabeledForExample { Output:
11
public static void main(String[] args)
12
{ aa:
13
for(int i=1;i<=3;i++){ bb: 21
for(int j=1;j<=3;j++){ If you use break bb;, it will break
if(i==2&&j==2){ break inner loop only which is the default
aa; behavior of any loop.
}
System.out.println(i+" "+j);
}
}
}
}
Example:
public class LabeledForExample {
Output:
public static void main(String[] args) {
aa: 11
for(int i=1;i<=3;i++){ 12
bb:
13
for(int j=1;j<=3;j++){
if(i==2&&j==2){ break bb; 21
} 31
System.out.println(i+" "+j);
32
}
} 33
}
}
Java Infinitive For Loop
If you use two semicolons ;; in the for loop, it will be infinitive for loop.
Syntax: for(;;){
//code to be executed
}

Example:
public class ForExample {
public static void main(String[] args) {
for(;;){
System.out.println("infinitive loop");
}
}
}
Output:
infinitive loop
infinitive loop CTRL+C
Java While Loop
The Java while loop is used to iterate a part of the program several times. If
the number of iteration is not fixed, it is recommended to use while loop.
Syntax:
while(condition){
//code to be executed
}
Output:
Example: 1
public class WhileExample { 2
public static void main(String[] args) { 3
int i=1;
4
while(i<=10){
5
System.out.println(i);
i++;
6
} 7
} 8
} 9
10
Java Infinitive While Loop
If you pass true in the while loop, it will be infinitive while loop.
Syntax:
while(true){ Output:
//code to be executed infinitive while loop
} infinitive while loop
Example: infinitive while loop
public class WhileExample2 { infinitive while loop
public static void main(String[] args) { infinitive while loop
while(true){ ctrl+c
System.out.println("infinitive while loop");
}
}
}
Java do-while Loop
The Java do-while loop is used to iterate a part of the program several times. If the number of iteration is not fixed and
you must have to execute the loop at least once, it is recommended to use do-while loop.
It is executed at least once because condition is checked after loop body.
Syntax:
do{
//code to be executed
}while(condition); Output:
Example: 1
public class DoWhileExample { 2
public static void main(String[] args) { 3
int i=1; 4
do{ 5
System.out.println(i); i++; 6
}while(i<=10); 7
}
8
}
9
10
Java Infinitive do-while Loop
If you pass true in the do-while loop, it will be infinitive do-while loop.
Syntax:
while(true){
//code to be executed
}
Example:
public class DoWhileExample2 {
public static void main(String[] args) {
do{
System.out.println("infinitive do while loop");
}while(true); Output:
} infinitive do while loop
infinitive do while loop
}
infinitive do while loop....
6.4 Jump statements
1.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:
break;
Java Break Statement with Loop
Example:
public class BreakExample { Output:
public static void main(String[] args) { 1
for(int i=1;i<=10;i++){ 2
if(i==5){
3
break;
} 4
System.out.println(i);
}
}
}
Java Break Statement with Inner Loop
It breaks inner loop only if you use break statement inside the inner loop.
Example:
public class BreakExample2 {
public static void main(String[] args) {
for(int i=1;i<=3;i++){
for(int j=1;j<=3;j++){
Output:
if(i==2&&j==2){ break;
11
}
12
System.out.println(i+" "+j);
13
}
21
}
31
}
32
}
33
2.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:
continue;
Example:
Output:
public class ContinueExample { 1
public static void main(String[] args) { 2
for(int i=1;i<=10;i++){
3
if(i==5){
continue; 4
} 6
System.out.println(i); 7
}
8
}
} 9
10
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) {
Output:
for(int i=1;i<=3;i++){ 11
for(int j=1;j<=3;j++){ 12
if(i==2&&j==2){ continue; 13
} 21
System.out.println(i+" "+j); 23
} 31
} 32
}
33
}
Difference bettween C++ and Java
Comparison Index C++ Java
Platform-independent C++ is platform-dependent. Java is platform-independent.

Mainly used for C++ is mainly used for system Java is mainly used for application
programming. programming. It i s w i de l y u s e d in
window, web-based, enterprise and
mobile applications.

Goto C++ supports goto statement. Java doesn't support goto statement.

Multiple inheritance C++ supports multiple inheritance. Java doesn't support multiple inheritance
through class. It can be achieved by
interfaces in java.

Operator Overloading C++ supports operator overloading. Java doesn't support operator overloading.
Pointers C++ supports pointers. You can writ Java supports pointer internally. But you
pointer program in C++. e can't write the pointer program in java. It
means java has restricted pointer support in
java.
Compiler and Interpreter C++ uses compiler only. Java uses compiler and interpreter both.

Call by Value and Call by C++ supports both call by value and call Java supports call by value only. There is no call by
reference by reference. reference in java.

Structure and Union C++ supports structures and unions. Java doesn't support structures and unions.

Thread Support C++ doesn't have built-in support for Java has built-in thread support.
threads. It
relies on third-party libraries for thread
support.
Virtual Keyword C++ supports virtual keyword so that we Java has no virtual keyword. We can override all
can non-static methods by default. In other words, non-
decide whether or not override a function. static methods are virtual by default.

unsigned right shift >>> C++ doesn't support >>> operator. Java supports unsigned right shift >>> operator
that fills zero at the top for the negative numbers.
For p o s i t i v e n u m b e r s , i t w o r k s s a m e l i k e > >
operator.

Inheritance Tree C++ creates a new inheritance tree Java uses single inheritance tree always because all
always. classes are the child of Object class in java. Object
class is the root of inheritance tree in java.

You might also like