[go: up one dir, main page]

0% found this document useful (0 votes)
309 views34 pages

Com 123 Java (I)

Introduction to Programming Using Java (I)

Uploaded by

Iorlaha Samuel
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
309 views34 pages

Com 123 Java (I)

Introduction to Programming Using Java (I)

Uploaded by

Iorlaha Samuel
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 34

COM 123 JAVA(1); java programming is sweet Mr. Iorlaha S.K.

(09079447627)

COM 123 JAVA PROGRAMMING 1

What is Java ?
 It is general-purpose, high level, object oriented programming language.
 It is developed by James Gosling.
 It is developed at Sun Microsystems in 1995

History of Java ?
 James Gosling and his team started to work on java for a client's set top box project
in 1991.
 The first version of java (java 1.0) is released in 1995.
 First name of java is Oak, next goes to Green and finally becomes JAVA.
 Java is the name of Coffee Seed.

Features of Java ?
 Platform Independent: Java is called platform independent because a java program
can be run on different kind of platform for example Window OS, Linux OS etc.
 Object Oriented: Java supports object oriented programming structure so it is called
object oriented.
 Security: Java is more secure language as compare to other programming
language.
 Flexible: An application developed in java can be modified as per user requirement
so it is called flexible programming language.
 Portable: A java program written in one system can be run in any other system. In
simple a java program can be transferred from one system to another.
 Multithreading: In java we can perform more than one task simultaneously so it is
called Multithreading.
 Simple: Java is very simple and easy to learn.

Application of Java ?
 It is used to develop Window Application.
 It is used to develop Web Application.
 It is used to develop Android/Mobile Application.
 It is used to develop Embedded System for example SIM card, Television etc.
 It is used to develop Scientific Application for example MATLAB.
 It is used to develop Games.
 It is used for Database Connectivity.

Why Use Java ?


 It is very simple and easy to learn.
COM 123 JAVA(1); java programming is sweet Mr. Iorlaha S.K. (09079447627)

 It powerful, fast and secure.


 It can be run on different kind of platform for example Window, Mac, Linux etc.
 It is free and open source.

Environment Setup in Java ?


 There are two step to setup the environment in Java
 Window 7
 Step 1: Copy the JDK Path
 Go to C Drive
click on Program Files(x86)/Program Files
click on java
click on jdk
click on bin
Now copy the url, It looks like this
C:\Program Files (x86)\Java\jdk1.8.0_45\bin
 Step 2: Setup the environment variable
 1. From desktop, right click on Computer icon.
2. Choose Properties
3. Click the Advanced system settings
4. Click Environment Variables
5. In the section System Variables, find the PATH environment variable and select it.
Click Edit. If the PATH environment variable does not exist, click New.
6. Now in next window there are two section Variable Name and Variable
Value now in Variable Name put PATH and in Variable Value paste the copied
URL in the Step 1 and add semicolon in the last then click ok.
Now open command prompt window and run java code.
 Window 10
 Step 1: Copy the JDK Path
 Go to C Drive
click on Program Files(x86)/Program Files
click on java
click on jdk
click on bin
Now copy the url,It looks like this
C:\Program Files (x86)\Java\jdk1.8.0_45\bin
or
C:\Program Files (x86)\Java\jdk1.8.0_45
 Step 2: Setup the environment variable
 1. In Search, type control panel and open it.
2. Choose System
3. Click the Advanced system settings
4. Click Environment Variables
5. In the section System Variables, find the PATH environment variable and select it.
Click Edit. If the PATH environment variable does not exist, click New.
COM 123 JAVA(1); java programming is sweet Mr. Iorlaha S.K. (09079447627)

6. Now in next window there are two sections: Variable Name and Variable
Value. Now in Variable Name put PATH and in Variable Value paste the copied
URL in the Step 1 then click ok.
Now open command prompt window and run java code.

Syntax of Java ?
class Easy
{
public static void main(String[] args)
{
System.out.println("Hello World");
}
}

1. It is a keyword which is used to declare a class.


class 2. Keyword: The word which is predefined in the library is called keyword. For
example class, void ,main etc.

Easy 1. It is an user-defined class name.

1. It is a keyword which is called access specifier/modifier.


public 2. It is used to provide accessibility of data member(variable) and member
funation(function).

1. It is a keyword.
static
2. It can be used with a variable or function or block. we will discuss it soon

1.It is a keyword.
2.It indicates that there is no value is returning by the function.
void
3.If we use any other keyword like int, float, character in place of void then we will
use return keyword.

1.It is the function which is called the entry point of any program.
main() 2.The execution of any program starts from the main function.
3.If in a program there is only one function then it should be main function.

1. It is an array of type String.


String[] args 2. It is also called command line argument.
3.you can write anything in place of args

1. It is used to print data or information on to the output screen.


System.out.printl
2. System.out means Standard output object.
n
3. println is a method/function.

Case sensitivity Java is case sensitive e.g. “Hello” is different from “hello” due to upper/lower cases
COM 123 JAVA(1); java programming is sweet Mr. Iorlaha S.K. (09079447627)

First Program in Java


class Easy {
public static void main(String[] args)
{
System.out.println("Hello World");
}
}

Run this Program


Nowadays there are many ways to run a java program. Some of these are given below

 Using Command Prompt


 Using Netbeans
 Using Eclipse
 Using Android phone

JAVA VARIABLES

What is Variable in JAVA?

 It is a name of storage space which is used to store data.


 Its value may be changed.
 It always contains last value stored to it.
 It is always declared with data type.

Variable Declaration
int rollNo;
float marks;
char grade;

 Here rollNo is a variable of type int, marks is a variable of type float and grade is a
variable of type char.

Variable Initialization
 We can initialize a variable at the time of declaration of variable or after declaration.

int rollNo=201;
COM 123 JAVA(1); java programming is sweet Mr. Iorlaha S.K. (09079447627)

float marks=85.6;
char grade='A';

 Here 201 is the value of rollNo, 85.6 is the value of marks and A is the value of
grade. Character value is always written in single quotes.

Other Methods of Variable Initialization


 We can also initialize a variable after the time of declaration of variable.

int rollNo;
float marks;
char grade;

rollNo=201;
marks=85.6;
grade='A';

Rules to Define a Variable


 The first letter of a variable should be alphabet or underscore (_).
 The first letter of variable should not be digit.
 After first character it may be combination of alphabets and digits.
 Blank spaces are not allowed in variable name.
 Variable name should not be a keyword.

Types of Variable
 Local Variable
 Instance Variable
 Static Variable

Local Variable
 A variable declared inside the body of the method or constructor or block is called
local variable.
 Local variable can be used only inside that method/function in which it is declared.
 A local variable can be a static variable.

class Easy {
public void add()
{
int x, y=10, z=20;//declaring local variable
x=y+z;
System.out.println("Add="+x);
COM 123 JAVA(1); java programming is sweet Mr. Iorlaha S.K. (09079447627)

}
public static void main(String[] args)
{
Easy obj=new Easy();
obj.add();
}
}
/*
### Output ###
Add=30
*/

Instance Variable
 A variable which is declared inside a class but outside the body of the method or
constructor or block is called instance variable.
 Instance variable can be used anywhere in the program.

class Easy
{
//these instance variabe can be used
//inside all the function of this class
int x,y=30,z=20;
public void add()
{
x=y+z;//accessing instance variable
System.out.println("Add="+x);
}
public void sub()
{
x=y-z;//accessing instance variable
System.out.println("Sub="+x);
}
public static void main(String[] args)
{
Easy obj=new Easy();
obj.add();
obj.sub();
}
}
/*
### Output ###
Add=50
Sub=10
*/

Static Variable
 A variable which is declared with static keyword, inside a class but outside the body
of the method or constructor or block is called static variable.
 Static variable is stored in the static memory.
COM 123 JAVA(1); java programming is sweet Mr. Iorlaha S.K. (09079447627)

 Static variables are created when the program starts and destroyed when the
program stops.
 Static variable can be called by class name directly.

class Easy
{
//declaring static variable
static String text="You are a smart guy.";
public static void main(String[] args)
{
System.out.println(Easy.text);
}
}
/*
### Output ###
You are a smart guy.
*/

USER INPUT IN JAVA

1. Scanner is a predefined class which is used to take user input in java.


2. Scanner class is defined inside java.util package.
3. Scanner class consists of many functions to take user input which is as given below.

 nextInt(): Used to read integer value from the user.


 nextFloat(): Used to read float value from the user.
 nextDouble(): Used to read double value from the user.
 next(): Used to read string value without space from the user.
 nextLine(): Used to read string value from the user.
 nextByte(): Used to read byte value from the user.
 nextShort(): Used to read short value from the user.
 nextLong(): Used to read long value from the user.

Example

//importing the package


import java.util.Scanner;
class Easy {
public static void main(String[]args)
{ //creating the instance of class Scanner
Scanner obj=new Scanner(System.in);
String name;
int rollNo;
float marks;
System.out.println("Enter your name");
name=obj.nextLine();//taking string input
System.out.println("Enter your roll_No");
rollNo=obj.nextInt();//taking integer input
System.out.println("Enter your marks");
COM 123 JAVA(1); java programming is sweet Mr. Iorlaha S.K. (09079447627)

marks=obj.nextFloat();//taking float input printing the output


System.out.println("Name="+name);
System.out.println("Roll_no="+rollNo);
System.out.println("Marks="+marks);
}
}
/*
### Output ###
Enter your name
Anil Singhania
Enter your roll_No
205
Enter your marks
86.4
Name=Anil Singhania
Roll_no=205
Marks=86.4
*/

Second way to take user input in Java

1. BufferedReader is a predefined class which is used to take user input in java.


2. It is defined inside the java.io package.

//importing the package


import java.io.BufferedReader;
import java.io.InputStreamReader;
class Easy
{
public static void main(String[]args)
{
//creating the instance of class BufferedReader
BufferedReader reader=newBufferedReader(newInputStreamReader(System.in));
String name;
try{
System.out.println("Enter your name");
name=reader.readLine();//taking string input
System.out.println("Name="+name);
}catch(Exception e){
}
}
}
/*
### Output ###
Enter your name
Lucy Martin
Name=Lucy Martin
*/
COM 123 JAVA(1); java programming is sweet Mr. Iorlaha S.K. (09079447627)

JAVA CONSTANTS

What are constants in Java ?


 An element of program whose value can not be changed at the time of execution of
program is called constant.
 It is also called a literal.
 It may be int, float and character, Boolean, and String data type.

Rules for constructing integer constant

 It must have at least one digit.


 It must not have a decimal point.
 It may be positive or negative.
 No comma or blank spaces are allowed in integer constant.

Rules for constructing floating point constant

 It must have at least one digit.


 It must have a decimal point.
 It may be positive or negative.
 No comma or blank spaces are allowed in floating point constant.

Rules for constructing character constant

 It is a single alphabet, digit or special symbol.


 The length of character constant is 1 character.
 Character constant is enclosed within single quotes (Example: char c='A';).

KEYWORDS IN JAVA

 The word which is pre-defined in the library is called keyword.


 It's functionality is also pre-defined.
 Keyword cannot be used as a variable, function name, class name or as an any
identifier.
 Example of keywords are int, float, char, void, main etc.

List of keywords in Java


char continue double else
COM 123 JAVA(1); java programming is sweet Mr. Iorlaha S.K. (09079447627)

default catch finally final

long interface int instanceof

assert abstract class extends

implements float const boolean

private public protected package

break byte case do

enum for goto if

import native new return

strictfp synchronized static short

super switch this throw

throws transient try void

volatile while

JAVA OPERATORS

Operator
 It is a special symbol which is used to perform logical or mathematical operation on
data or variable.

Operand
 It is a data or variable on which the operation is to be performed.

Types of Operator
 ⇒Arithmetic Operators
 ⇒Relational Operators
 ⇒Logical Operators
 ⇒Assignment Operators
 ⇒Bitwise Operators
 ⇒Increment/Decrement Operators
 ⇒Conditional Operators

Arithmetic Operators
These refers to all the mathematical operators such as plus, division, etc.
COM 123 JAVA(1); java programming is sweet Mr. Iorlaha S.K. (09079447627)

Symbol Operation Example

+ Addition x+y

- Subtraction x-y

* Multiplication x*y

/ Division x/y

% Modulus x%y

class Easy
{
public static void main(String[] args)
{
int a=5,b=3;
System.out.println("Add="+(a+b));
System.out.println("Sub="+(a-b));
System.out.println("Multi="+(a*b));
System.out.println("Div="+(a/b));
//Note:-modulus(%) always holds remainder value
System.out.println("Mod="+(a%b));
}
}
/*
### Output ###
Add=8
Sub=2
Multi=15
Div=1
Mod=2
*/

Relational Operators
Symbol Operation Example

== Equal to 2==3 returns 0

!= Not equal to 2!=3 returns 1

> Greater than 2>3 returns 0

< Less than 2<3 returns 1

>= Greater than or equal to 2>=3 returns 0


COM 123 JAVA(1); java programming is sweet Mr. Iorlaha S.K. (09079447627)

<= Less than or equal to 2<=3 returns 1

Logical Operators

SYMBOL OPERATION EXAMPLE


&& Logical AND If(x>y&& x>z)
|| Logical OR If(x>y||x>z)
! Logical NOT If(!(x>y))

(x>y)&&(x>z
Here this expression returns true if both conditions are true.
)

(x>y)||(x>z) Here this expression returns true if any one or both conditions are true.

Not operator reverses the state means if the condition is true it returns false
!(x>y)
and if the condition is false it returns true.

class Easy
{
public static void main(String[] args)
{
int a=10,b=60,c=40;
if(a>b&&a>c)
System.out.println("a is greatest");
if(b>a&&b>c)
System.out.println("b is greatest");
if(c>a&&c>b)
System.out.println("c is greatest");
}
}
/*
### Output ###
b is greatest
*/

Assignment Operators
These operators are mainly used in order to assign or apportion values to designated
variables in the program. Below are some of the assignment operators.
COM 123 JAVA(1); java programming is sweet Mr. Iorlaha S.K. (09079447627)

Symbol Example Same as

= x=y x=y

+= x+=y x=x+y

-= x-=y x=x-y

*= x*=y x=x*y

/= x/=y x=x/y

%= x%=y x=x%y

class Taxy
{
public static void main(String[] args)
{
int x1=5,y1=3;
x1+=y1;//x1=x1+y1
System.out.println(x1);
int x2=5,y2=3;
x2-=y2;//x2=x2-y2
System.out.println(x2);
int x3=5,y3=3;
x3*=y3;//x3=x3*y3
System.out.println(x3);
int x4=5,y4=3;
x4/=y4;//x4=x4/y4
System.out.println(x4);
int x5=5,y5=3;
x5%=y5;//x5=x5%y5
System.out.println(x5);
}
}
/*
### Output ###
8
2
15
1
2
*/

Bitwise Operators
Bitwise operators operate on bits
COM 123 JAVA(1); java programming is sweet Mr. Iorlaha S.K. (09079447627)

Symbol Operation Example

& Bitwise AND x&y

| Bitwise OR x|y

<< Shift Left x<<2

>> Shift Right x>>2

^ X-OR x^y

class Easy
{
public static void main(String[] args)
{//variable declaration
int a=5,b=3,c;
c=a&b;//AND Operation
System.out.println("a&b="+c);
c=a|b;//OR Operation
System.out.println("a|b="+c);
c=a>>2;//Shift right Operation
System.out.println("a>>2="+c);
c=a<<2;//Shift left Operation
System.out.println("a<<2="+c);
c=a^2;//X-OR Operation
System.out.println("a^2="+c);
}
}
/*
### Output ###
a&b=1
a|b=7
a>>2=1
a<<2=20
a^2=7
*/

Increment/Decrement Operators
Symbol Name Function Example

++ Increment It increments the value by 1 ++x

-- Decrement It decrements the value by 1 --x


COM 123 JAVA(1); java programming is sweet Mr. Iorlaha S.K. (09079447627)

class Easy
{
public static void main(String[] args)
{//variable declaration
int a=5,b=10;
System.out.println(++a);
System.out.println(--b);
}
}
/*
### Output ###
6
9
*/

Conditional Operators
Syntax:
Condition? If condition is true: if condition is false;
1 ? 2 : 3 ;

 If the condition is true second part will execute otherwise third part will execute.

class Easy
{
public static void main(String[] args)
{//variable declaration
int a=5,b=10,max;
max=a>b?a:b;
//don't be confused, here + is separator in java
System.out.println("Greater value is "+max);
}
}

DATA TYPES IN JAVA


 It is a type of data which is used in the program.
 There are many predefined data types in java library like int,char,float etc.

Type of Data Type


COM 123 JAVA(1); java programming is sweet Mr. Iorlaha S.K. (09079447627)

Primitive Data Type


 The data type which is predefined in the library is called primitive data type.
 It is named by a keyword for example int, float, char etc.
 There are eight primitive data types in java. Byte, short, int, long, float, double,
boolean and char.

Integer Type

Type Size in bytes Range

byte 1 -128 to 127

short 2 -32,768 to 32,767

int 4 -2,147,483,648 to 2,147,483,647

long 8 -9,223,372,036,854,775,808 to 9,223.372,036,854,775,808

Float Type

Type Size in bytes Range

float 4 3.4e-038 to 3.4e+038.

double 8 1.7e-308 to 1.7e+038.

Boolean

Keyword boolean

Syntax boolean x;

Value True/False

Default False

Character

Keyword char

Syntax char x;

Value 'a','@','9'

Range 0 to 65536
COM 123 JAVA(1); java programming is sweet Mr. Iorlaha S.K. (09079447627)

Non-primitive Data Type


 The data type which is derived from primitive data type is called non-primitive data
type.
 It is also called reference data type.
 They don't store the value, but store a reference to that value.
 Example: Array, class, interface etc.

COMMENTS IN JAVA
 It is used to explain the code to make it more readable.
 It is not considered as a part of program, in other words we can say that compiler
ignores the comment.
 java comments are statements that are not executed by the compiler.

Types of Comments in Java


 Single line comment
 Multiline comment

Single Line Comment


 It is used to comment only one line.
 Two forward slashes (//) is used for single line comment.
 Single line comment starts with double forward slashes.

//this is a single line comment


System.out.println("you are excellent");

Multiline comment
 Multiline comment is used to comment a block of code.
 Multiline comment starts with /* and ends with */.
 The text between /* and */ is not executed by the compiler.

class Easy {
public staticvoid main(String[] args)
{
/*
This is multiline comment
Write a program to add
two number and store it
in third number
*/
COM 123 JAVA(1); java programming is sweet Mr. Iorlaha S.K. (09079447627)

intx,y=10,z=30;
x=y+z;
System.out.println("Add="+x);
}
}

JAVA CONTROL STRUCTURES

If statement in Java
Syntax: if(condition){
//body of codes
}

 It is used to test the condition.


 If the condition is true its body will execute otherwise does not execute.

Example 1:
class Easy
{
public static void main(String[] args)
{
int x=10;
if(x>5)
{
System.out.println("x is greater than 5");
}
}
}

Example 2: Check given number is Negative or Positive or Zero


import java.util.Scanner;
class Easy{
public static void main(String[] args) {
Scanner in=new Scanner(System.in);
int no;
System.out.println("Enter any number");
no=in.nextInt();
if(no>0)
System.out.println("number is positive");
if(no<0)
System.out.println("number is negative");
if(no = = 0)
System.out.println("number is zero");
}
COM 123 JAVA(1); java programming is sweet Mr. Iorlaha S.K. (09079447627)

}
/*
### Output ###
Enter any number
-5
number is negative
*/

If else statement in Java


Syntax:

 It is used to test the condition.


 If the condition is true body of if will execute otherwise body of else execute.

Example 1:
class Easy
{
public static void main(String[] args)
{
int a=10,b=20;
if(a>b)//a greater than b(false)
{
System.out.println("a is greater");
}
else
{
System.out.println("b is greater");
}
}
}
/*
### Output ###
b is greater
*/

Example 2: Check given number is even or odd.

import java.util.Scanner;
class Easy
{
public static void main(String[] args)
{
Scanner in=new Scanner(System.in);
int no;
System.out.println("Enter any number");
no=in.nextInt();
//number exactly devided by 2 is called even
COM 123 JAVA(1); java programming is sweet Mr. Iorlaha S.K. (09079447627)

if(no%2==0)
System.out.println("number is even");
else
System.out.println("number is odd");
}
}
/*
### Output ###
Enter any number
5
number is odd
*/

Switch Statement in Java


 Switch statement allows us to execute one statement from many statement and the
statements are called case.
 Inside the body of switch there are a number of cases and there is a single number
is passed at the place of parameter to select and execute a case.

Syntax:

 In the switch statement a value/number is passed in the place of parameter and the
case from which the parameter is matched is executed.
 If no case matched with parameter then default case will execute.

Example 1:
COM 123 JAVA(1); java programming is sweet Mr. Iorlaha S.K. (09079447627)

class Easy
{
public static void main(String[]args)
{
int day=2;
switch(day)
{
case1:
System.out.println("Monday");
break;
case2:
System.out.println("Tuesday");
break;
case3:
System.out.println("Wednesday");
break;
case4:
System.out.println("Thrusday");
break;
case5:
System.out.println("Friday");
break;
case6:
System.out.println("Saturday");
break;
case7:
System.out.println("Sunday");
break;
default:
System.out.println("No case matched");
}
}
}

Exercise:
Run the above program using all the cases and print out the result.

Example 2: Check given Alphabet is vowel or consonant.

import java.util.Scanner;
class Easy
{
public static void main(String[]args)
{
Scanner in=new Scanner(System.in);
char ch;
System.out.println("Enter any alphabet");
ch=in.next().charAt(0);
COM 123 JAVA(1); java programming is sweet Mr. Iorlaha S.K. (09079447627)

switch(ch)
{
case'a':
case'e':
case'i':
case'o':
case'u':
System.out.println("Vowel");
break;
default:
System.out.println("Consonent");
}
}
}

Loop in Java
 Loop is a part of control flow statements.
 To run the particular block of code continuously until a required condition is fulfilled is
what we call looping.
 Loop is used when there is a need to execute a part of program for multiple times.

SOME POINT ABOUT THE ENTIRE LOOP:

 There is a control variable, called the loop counter.


 The control variable must be initialized; in other words, it must have an initial value.
 The increment/decrement of the control variable, which is modified each time the
iteration of the loop, occurs.
 The loop condition that determines if the looping should continue or the program
should break from it.

For Loop in Java


Syntax:
for (initialization; condition; increment/decrement)
{
// Body of the loop;
}

 In for loop there are three parts: initialization, condition and


increment/decrement.
COM 123 JAVA(1); java programming is sweet Mr. Iorlaha S.K. (09079447627)

 Initialization part executes only once.


 Condition part defines the condition for the execution of code block.
 All the three part of for loop are optional.

Example 1:
class Easy
{
public static void main(String[]args)
{
for(inti=1;i<5;i++)
{
System.out.println(i);
}
}
}
/*
### Output ###
1
2
3
4
*/
Explaination:
In the above example initialization part initialize the variable i with 1, condition is i less than 5 and at the
increment place there is an increment by 1 ,so the output will be 1 to 4.

Example 2:
/*
Example 1 can also be written
like the code below
*/
class Easy
{
public static void main(String[]args)
{
int i=1;
for(;i<5;)
{
System.out.println(i);
i++;
}
}
}
COM 123 JAVA(1); java programming is sweet Mr. Iorlaha S.K. (09079447627)

Example 3:
class Easy
{
public static void main(String[]args)
{
//all parts of for loop are optional
for(;;)
System.out.println("Hello");
}
}
/*
### Output ###
Hello
Hello
Hello
Hello
-----
-----
Infinite time Hello
*/

Example 4: Find factorial of any number


//factorial of 5=1x2x3x4x5
//factorial of 6=1x2x3x4x5x6
//factorial of N=1x2x3x....xN
import java.util.Scanner;
class Easy
{
public static void main(String[]args)
{
Scanner in=new Scanner(System.in);
intno,f=1;
System.out.println("Enter any number");
no=in.nextInt();
for(int i=1; i<=no; i++){
f=f*i;
}
System.out.println("The factorial of "+no+" is "+f);
}
}
/*
COM 123 JAVA(1); java programming is sweet Mr. Iorlaha S.K. (09079447627)

### Output ###


Enter any number
6
The factorial of 6 is 720
*/

While loop in Java

Syntax:
while(condition)
{
//body
}

 It's body will execute until the given condition is evaluated to FALSE..

Example 1:
class Easy
{
public static void main(String[]args)
{
int x=1;
while(x<10)
{
System.out.println(x);
x++;
}
}
}

Explaination:
In the above example the body of while will execute again and again as long as variable x is less than
10.

Example 2: Find factorial of any number


//factorial of 5=1x2x3x4x5
//factorial of 6=1x2x3x4x5x6
//factorial of N=1x2x3x....xN
import java.util.Scanner;
class Easy
{
public static void main(String[]args)
{
COM 123 JAVA(1); java programming is sweet Mr. Iorlaha S.K. (09079447627)

Scanner in=new Scanner(System.in);


int no, f=1, i=1;
System.out.println("Enter any number");
no=in.nextInt();
while(i<=no)
{
f=f*i;
i++;
}
System.out.println("The factorial of "+no+" is "+f);
}
}

Do while loop in Java


Syntax:
Do
{
// Body code
}
while(condition);

 It's body will execute until the given condition is true.

Example 1:
class Easy
{
public static void main(String[]args)
{
int x=1;
do
{
System.out.println(x);
x++;
}
while(x<10);
}
}

Explanation:
In the above example the body of while will execute again and again as long as variable x is less than
10.

Exercise:
Using the do..while loop, develop a factorial program.
COM 123 JAVA(1); java programming is sweet Mr. Iorlaha S.K. (09079447627)

Difference between while and do while loop


 The difference between while loop and do while is that in the case of while loop if the
condition is false it's body will not execute but in the case of do while loop it's body
will execute at least one time either condition true or false.
 While loop is a entry control loop and do while loop is a exit control loop.
 In structure, the do..while loop ends with a semi-colon.

For each loop in Java

Syntax:
for(variableName : ArrayName)
{
//body;
}

 It is a special type of loop which is used mostly with array.


 It stores each element of array in a variable and executes the body of loop.
 It starts with for keyword like a normal for loop.

Example 1:Program with for..each loop


class Easy
{
public static void main(String[]args)
{
//array declaration
int ar[]={10,50,60,80,90};
for(int element:ar)
System.out.print(element+" ");
}
}
Example 2: Same program with for loop
class Easy
{
public static void main(String[]args)
{
//array declaration
COM 123 JAVA(1); java programming is sweet Mr. Iorlaha S.K. (09079447627)

int ar[]={10,50,60,80,90};
for(int i=0; i<ar.length; i++)
System.out.print(ar[i]+" ");
}
}
/*
### Output ###
10 50 60 80 90
*/

Jump Statement in Java ?


 It is used to transfer the control from one point to another point in the program.
 There are three jump statements are used in java:
 break statement
 continue statement
 return statement

Break Statement
 It is used to transfer the control out of the body of loop.
 In other word we can say that it terminates the current loop.
 break statements are mostly used with loop(for,while,do while) and switch statement.

Example 1:Program without break


class Easy
{
public static void main(String[]args)
{
for(int i=1; i<=10; i++)
{
System.out.print(i+" ");
}
}
}

/*
### OUTPUT ###
1 2 3 4 5 6 7 8 9 10
*/
COM 123 JAVA(1); java programming is sweet Mr. Iorlaha S.K. (09079447627)

Example 2: Same Program with break

class Easy
{
public static void main(String[]args)
{
for(int i=1; i<=10; i++)
{
System.out.print(i+" ");
if(i==5)//terminate the loop when i=5
break;
}
}
}
/*
### OUTPUT ###
1 2 3 4 5
*/

Continue Statement
 It is used to skip the next statement and continue the loop.
 Continue statements are mostly used with loop (for,while,do while).

Example 1:
class Easy
{
public static void main(String[]args)
{
for(int i=1; i<=5; i++)
{
if(i==3)//skip the next statement when i=3
continue;
else
System.out.print(i+" ");
}
}
}
/*
### OUTPUT ###
COM 123 JAVA(1); java programming is sweet Mr. Iorlaha S.K. (09079447627)

1 2 4 5
*/
Example 2:

class Easy
{
public static void main(String[]args)
{
for(inti=1;i<=5;i++)
{
if(i>=3)//skip the next statement when i>=3
continue;
else
System.out.print(i+" ");
}
}
}
Exercise:
Run the code in example 2 above and produce the results, print and
submit.

Example 3:

class Easy
{
public static void main(String[]args)
{
for(int i=1; i<=5; i++)
{
if(i<=3)//skip the next statement when i<=3
continue;
else
System.out.print(i+" ");
}
}
}

Example 4:

class Easy
{
public static void main(String[]args)
COM 123 JAVA(1); java programming is sweet Mr. Iorlaha S.K. (09079447627)

{
for(int i=1; i<=5; i++)
{
if(i!=3)//skip the next statement when i!=3
continue;
else
System.out.print(i+" ");
}
}
}
Exercise:
1. Using examples 3 & 4 above; change the boundary to any figure
above 5.
2. Run the program, print out the results and submit

Return Statement
 return statement terminates the current function and transfer the control to the calling
function.
 we can also use return statement to trasfer value from one function to another.

class Easy
{
int add()
{
int x=10, y=30;
return(x+y);//returning x+y=40
}
public static void main(String[]args)
{
Easy obj=new Easy();
int rs=obj.add();//passing returning value to rs
System.out.println("Add="+rs);
}
}
COM 123 JAVA(1); java programming is sweet Mr. Iorlaha S.K. (09079447627)

ARRAYS IN JAVA
 It is a collection of data of same data type.
 It is used to store group of data simultaneously.
 It can store data of same data type; i.e. an integer array can store only integer
value ,character array can store only character value and so on.
 We can not fetch data from array directly therefore we use index point.
 The indexing of array always starts with 0.
 Index value is always an integer number.
 Array may be of any data type like int,char,float etc.

Syntax:
dataType arrayName[] = new dataType[arraySize];
E.g. int a[] = new int[5];

0 1 2 4 5
Memory Representation:

 Here a is the name of array.


 int is the data type of array.
 Size of array is 5 means we can store maximum 5 values in this array.

Initialization of Array Method 1:


int ar[]={45,23,89,12,78};
Initialization of Array Method 2:
int a[]=new int[5];
a[0]=45;
a[1]=23;
a[2]=89;
a[3]=12;
a[4]=78;

Printing of array element method 1:


class Hard
{
public static void main(String[]args)
{
//array declaration
int ar[]={10,50,80,40,60};
System.out.println("Value at ar[0]="+ar[0]);
COM 123 JAVA(1); java programming is sweet Mr. Iorlaha S.K. (09079447627)

System.out.println("Value at ar[1]="+ar[1]);
System.out.println("Value at ar[2]="+ar[2]);
System.out.println("Value at ar[3]="+ar[3]);
System.out.println("Value at ar[4]="+ar[4]);
}
}
/*
### Output ###
Value at ar[0]=10
Value at ar[1]=50
Value at ar[2]=80
Value at ar[3]=40
Value at ar[4]=60
*/

Printing of array element method using loop:


Class Diff {
Public static void main(String[]args)
{
//array declaration
int ar[]={10,50,80,40,60};
for(int i=0; i<=4; i++)
System.out.println("Value at array["+i+"]="+ar[i]);
}
}
/*
### Output ###
Value at ar[0]=10
Value at ar[1]=50
Value at ar[2]=80
Value at ar[3]=40
Value at ar[4]=60
*/

User Input in Array:


COM 123 JAVA(1); java programming is sweet Mr. Iorlaha S.K. (09079447627)

import java.util.Scanner;
class Payback{
public static void main(String[]args)
{
Scanner in=new Scanner(System.in);
//array declaration
int ar[]=newint[5];
int i;
for(i=0; i<=4; i++)
{
System.out.println("Enter element at "+(i+1));
ar[i]=in.nextInt();
}
for(i=0; i<=4; i++)
System.out.println("Value at ar["+i+"]="+ar[i]);
}
}

Exercise
Run the programs above and print out their results for submission.

You might also like