Letest

84
JAVA PROGRAMMING

Transcript of Letest

Page 1: Letest

JAVA PROGRAMMING

Page 2: Letest

What is Java?

• Java is a purely an Object Oriented programming language• Java began life as the programming language called ‘OAK’• OAK was developed in 1991 by the programmers of Sun

Microsystem, Now owned by Oracle Inc.• Oak developer team wanted a new way of computing, so

they decided to make programming language to run in different kinds of computers, consumer devices and OAK got the new name called ‘Java’

• The goal of java is “Write Once; run anywhere”. It is platform independent language

• Java is inspired by C, C++ syntax.

Page 3: Letest

Applications of Java

• Embedded Systems such as consumer devices• Personal Computers• Distributed Systems• World Wide Web(Eg. Applet, JSP etc)• Smart Phones, Mobiles

Page 4: Letest

Java Editions

• Java 2 Standard Edition(J2SE)- Used for standard desktop application development

• Java 2 Enterprise Edition(J2EE)- Used for developing Web or Distributed applications

• Java 2 Micro Edition(J2ME) – Used for application development for most of the featured mobiles phones i.e Nokia Series 40, eg. Nokia 2700.

Page 5: Letest

JAVA ENVIRONMENT

• Java is both compiled and interpreted

C Code

Machine Code(CPU Specific)

Compiled

JAVA Code

Bytecode(CPU independent)

Executed By CPU, Executed By Java Virtual Machine,

Compiled

Interpreted

Page 6: Letest

Java Virtual Machine

• JVM is a software program which can execute the byte codes. It runs on existing OS.It is a type of virtual machine.

Page 7: Letest

Byte code

• It is fully optimized set of instructions designed to be executed by JVM(Java Virtual Machine)

• Translating Java Program into byte code helps run program in wide variety of environment s because only task is to make JVM for that particular platform

• Byte code is interpreted by JVM.• It is secure because execution of Java program is

always under control of JVM• In computer, bytecode is stored in a Class file. Eg.

Test.class

Page 8: Letest

Features of Java• Simple and powerful:

– It is simple to understand by professional programmers– Every one with the knowledge of programming and Object oriented

programming concept feels it is simple• Secure

– Java programs are confined within Java execution environment or JVM, Java programs and Applets(Web GUI objects) can be downloaded without fear of virus

• Portable– Java uses byte code concept which is not executed by CPU but Java virtual

machine so we can use single code for multiple platforms• Object Oriented

– Java uses realistic approach of OOP. Every thing other than simple data types such as int, float etc are used as objects.

Page 9: Letest

Features of Java• Robust:

– Java programs are reliable from memory management view– Java forces programmers to find mistakes in early stage of development– Java has automatic Garbage Collection. So users need not to be worry

about memory management problems which is big disadvantage of C where users need to allocate and de-allocate memory manually.

– Garbage Collection is the feature of JVM where memory is allocated for object when uses and if objects are not used, they are cleared from memory

• Multithreaded– Thread is a particular part of a program. Java enables performing multiple

tasks within a program simultaneously.– E.g. Antivirus can do two repetitive tasks together. We can update antivirus

while virus scan is running• Architecture-Neutral

– Once java program is written, it can be executed in any environment.

Page 10: Letest

Features of Java• Interpreted and High Performance:

– Java programs run comparatively faster than other interpreted language like BASIC

– It is designed to run in low power CPU. So Java is the first choice for Mobile Programming.

• Distributed– Java programs can run over TCP/IP protocols. We can design

programs which can call the methods of Remote program. For this, java provides RMI(Remote Method Invocation)

• Dynamic– Java allows accessing objects dynamically in run time. Small

fragment of byte code can be updated dynamically in the run-time.

Page 11: Letest

Object Oriented Programming Concept

•Every Object has attributes(state) and behavior, for Tata-Nano Object

Particular TATA-Nano is a real world object

States or attributes Behaviour

Wheels Gear up

Model Run

Horse Power Gear down

Seats Brake

• For every Computer Object, attributes(state) are called data or behavior is called Method

Data(Variables) Methods(Functions)

totWheels gearUp()

modelNo run()

horsePower gearDown()

totalSeats brakeDown()

In a Racing Game(Ferrari)

Page 12: Letest

Computer OBJECT

DefinitionAn Object is a software bundle of related state(fields or data) and behavior(Methods or functions). Software objects are often used to model real world objects that we find in everyday life. E.g. Button, Car, Cat etcTask: Make a list of objects you see in your everyday life and make a list of their

states and behavior.

Page 13: Letest

What is CLASS

CAR ANIMAL

Tata-Nano Ferrari Cow TigerTata-nano and Ferrari fall under CAR class, Cow and Tiger fall under Animal class

In object-oriented terms, we say that our bike(eg. Pulsar) is an instance of the class of objects known as motorbike. A class is the blueprint(outline) from which individual objects are created.

Page 14: Letest

What is Abstraction

Abstraction is one of the fundamental principle of OOP which helps to reduce the complexity. It helps to separate methods and data that change frequently. In makes system flexible.

You got a new mobile. You start using it without knowing the complexity of it’s internal structure. While using Mobile, we do not need to know about its internal parts. The frequently changeable features like Battery, cover, sim card are accessible. Other parts are hidden. This reduces complexity.

Page 15: Letest

EncapsulationEncapsulation is the mechanism that binds code and data together and keeps both safe from outside misuse. It is the protective wall to prevent code inside class being randomly accessed.

* Note : abstraction and encapsulation seem to be similar but abstraction uses interface and encapsulation uses access modifiers(private, public,protected) to hide data. These will be discussed later

Page 16: Letest

What is InheritanceVehicle

Bike

CBZ Discover

Car

Santro Maruti-SX4

Object

Controls

Button Textbox

Forms

MDI parent Dialog

•Different kinds of objects often have a certain amount in common with each other•Bike, Car class inherit from Vehicle class. CBZ, Discover inherit from Bike Class•The possible object for here becomes particular CBZ bike with particular engine number.•Here Vehicle is Super Class for derived class Bike, and Bike is called Base or derived class•In OOP, Inheritance is the way to reuse the code of existing class. Here one object acquires properties of another object.

Objects: Button save , exit;

Page 17: Letest

Polymorphism

•Polymorphism(“ Many Forms”) is the process of making methods in OOP to perform multiple tasks. eg;: we can make a function called ADD() to calculate the sum of two numbers or two Strings with a single name. Making such methods is also called Overloading

Page 18: Letest

Starting Java

To work with java, We need following:•Latest Java Development Kit(www.oracle.com) . It also JRE(java runtime environment)•Any text editors like Notepad, Notepad++•IDE(Integrated Development Environment) like Netbean or Eclipse for easier development

Page 19: Letest

Installing and configuring•Install JDK•Define following environment variables• Goto run• Type sysdm.cpl• Goto Advanced tab• Click environment variable

button

Page 20: Letest

Installing and configuring•Path: ;C:\Program Files (x86)\Java\jdk1.6.0\bin•CLASSPATH: D:\Java•JAVA_HOME: C:\Program Files (x86)\Java\jdk1.6.0\bin

Path: defining path helps to access java commands directly from Command Prompt(cmd)

CLASSPATH: the location where compiled classes are loaded, java searches classes here

JAVA_HOME:It is the path of directory where Java.exe can be found

Page 21: Letest

First Java Program//class name is First so save file as First.java

class First{public static void main(String args[]) {

System.out.println(“First Program”);}

}

•Save file as First.java• compile:• D:/java>javac First.java

•Run• D:/java>java First

First Program

Page 22: Letest

First Java Program

class First { It defines the name of the class

// this is single line comment/* thi is multi lineComment */

public static void main(String args[]){ •public : It is public access modifier which can be called from outside.•Static : this keyword tells that to call main() function, instance of First is not required. Every static data members can be directly accessed without creating object of class.•void refers an empty data type so this function does not return any value•main()- the function that is called automatically when application is launched•args[]-these are number of values which can be passed into program.• For example:• C:/>format c: enter

• Here c: is an argument

Enter

Page 23: Letest

Coding Conventions

•make all constants are written in UPPERCASE. Eg.MAX_HOURS,FILL_COLOR etc• Eg: static final MAX_SPEED=100;

• write all statements and other keywords in lowercase eg import,if,for,while•Name of the class is CamelCased. Eg MyFirstClass. If single word is used then : class First { }.•Objects, variables and function names are written in mixedCase. For example:• Button butSave=new Button();• public int findSum() {• Int firstNum,secondNum etc

•Always initialize values of the variables before use.

Page 24: Letest

Second Java Program//class name is First so save file as SecondJava.java

class SecondJava{public static void main(String args[]) {

int age=10;System.out.println(“I am ”+age+” years old.

After 10 years, I will be “+(age+10)+” years old”);}

}

•Save file as SecondJava.java• compile:• D:/java>javac SecondJava.java

•Run• D:/java>java SecondJava

I am 10 years old. After 10 years, I will be 20 years old

Page 25: Letest

Data Types

Java is called Strongly Typed or strict typed language because every identifier(variable or constant) has data type and these all needs to be strictly defined first with type and used later. It is similar to C, C++. But java is more strict. You can not assign floating point value to integer but in java you can not. Java compiler performs strong-type checking during compilation.

int a=2.2; is wrong in java but correct in c,c++

Page 26: Letest

Simple Data Types These are also called primitive data type. Integers: integer data type holds integer value which is signed. Java does not support positive only values like C.

byte 1byte -128 to 127short 2 bytes -32768 to 32767 int 4 bytes -(231 ) to (231)-1long 8 bytes(64bit) -(263) to (263)-1

Floating-Point Types hold real numbers and used with fractional values:float 32bits 1.4e-45 to 3.4e038double 64bits 4.9e-324 to 1.8e308

Characters: Java char data type uses 16 bit space where c, c++ char takes 8 bit. The reason is java also supports Unicode representation. Characters are treated numeric values as we can do calculations also, In java char is used

Page 27: Letest

Simple Data Types

Boolean: Boolean holds logical values such as true or false. It occupies 1 bit storage

class CharTest{public static void main(String args[]) {

char a='A';char b=66;System.out.printf("a is %c and b is %c ",a,b);++b;System.out.println(" and after increment, b is "+b);

}}

Output is : a is A and b is B and after increment, b is C

Page 28: Letest

Wrapper Class(Reference Types)

There are some situations where data types are required to be true objects.eg. If we want to derive data type. For this purpose java provides wrapper classes where primitive data types are written as object, here first letter is capitalized.Eg. Integer, String, Character etc.

public class First {public static void main(String args[]) {

int a=10;Integer obj=new Integer(15);System.out.println("premitive is "+a+" Wrapper is "+obj.intValue());

}}

Page 29: Letest

Literals

Literals are the values assigned to any variable.• Eg. Int a=5; here 5 is integer literal.• String literals are double quoted

String name=“Suman”• Boolean literal uses true or false keyword

boolean a=true;• A character is single quoted

char choice=‘Y’;

Page 30: Letest

Escape Sequence

Escape characters are written with \. These are used to represent control characters

Escape Description

\n New line

\t Tab

\’ Single quote

\” Double quote

\f Form feed

\b Backspace

\ddd Octal

\uxxx unicode

Page 31: Letest

Example

public class Escape{public static void main(String args[]) {

String quote="Programming is Fun";System.out.println("Many people say \""+quote+"\"");

}}

Output is : Many people say “Programming is Fun”

Page 32: Letest

Variables

Variable is an identifier which holds certain value that can be changed. A variable has type, scope and lifetime. Variable name can start with $ or an alphabet and can be followed by underscore. It can not contain whitespace.• Declaring variable

<type> <var_name>=[<value>]Eg.Int a=5; //declared and initializedInt x,y,z; //declared onlyInt m,n=6; //mixed declaration and initializationInt t; // declared and later initializedt=9;

Page 33: Letest

Dynamic initializationWhat is dynamic initialization? Give an example. (QB)Dynamic initialization is the process of assigning value to a variable dynamically during runtime. We can not perform dynamic initialization to the variables declared with final keyword.

public class Init{public static void main(String args[]) {

int a=10; // this is static initializationint b=a*10; //this is dynamic initializationSystem.out.println(“a is “+a+” and b is “+b);

}}

Output is : a is 10 and b is 100

Page 34: Letest

Variable scope and lifetime

Scope refers variable accessibility and lifetime refers to its’ existence. Curly brace defines the scope.

{ int a;

}

// a can not be accessed from here

Page 35: Letest

Variable scope and lifetime

Nested scope.

class test{ int a;

class inner{int a;

// wrong duplicate definition. Variable can be accessed from inner scope.

}

}

Where program exit from scope, variable is destroyed

Page 36: Letest

Type conversion and Casting

Type casting is the process of converting values from one type to another type.•Automatic conversion(implicit)• Automatic conversion takes place if two types are

compatible(ie. Int,float,byte,short,long etc)• If destination is larger than source.

If above conditions are met, Widening Conversion takes place

•Casting incompatible types(explicit)Casting between incompatible types, we need to use cast expression,(target-type) value;Eg. Convert int to byte

Page 37: Letest

Automatic type promotionConsider a situation

byte a=30;byte b=20;int c=b*c;

While converting using expression b*c may become more than 255. so while using short and byte to any expression, these are automatically promoted to int.

Another examplebyte a=20;b=a*2; //wrong can not assign int to byte // this is correct way because int is converted to byteb=(byte)(a*2);

Page 38: Letest

Type conversion and Casting

int a;a=258;byte b;b=(byte) a; // a is integer and casted to byte

Note: here b is byte which holds smaller values than int. byte can hold 8 bits. So maximum values are 28=256.When we assign 258 to byte, Narrowing Conversion takes place. If target smaller than only remainder will be assigned.So value of b becomes 258 % 256=2

Page 39: Letest

Examplepublic class cast {

public static void main(String args[]) {int a; // this is static initializationbyte b;a=258;b=(byte) a;System.out.println(b); //2 will be printed

float f=15.55f;int c=(int) f;

System.out.println(c); // 15 will be printed

double e=1554554.4582;float g=(float) e;System.out.println(g); // 1554554.5 will be printed because it can take upto 8 digits

}}

Page 40: Letest

Type promotion rulesWhen an expression contains many types. Other types are promoted to bigger one.

• In an expression byte and short are automatically promoted to int• If one operand is long, entire expression is converted to long• If any operand is float, entire expression is converted to float• If any operand is double, entire expression is converted to

double

Page 41: Letest

Example of promotionclass AutoPromote{

public static void main(String args[]) {byte a=50;short s=1000;int i=10550;float f=10.5f;double d=1.12546;double result=(a*s)+(i/f)+(d*i);System.out.println(result);

}}

Output:62878.36471875

Here,•Expression contains largest type double, so result type must be double•a*s becomes int so a*s=50000•In i/f, f is float so every thing becomes float so i/f=1004.7619f•In d*i, everything becomes double so d*i=11873.603

Page 42: Letest

OperatorsAn operator is a symbol which refers the type of calculation to be performed in any operation. Eg. +,-,* etc

An operand is the value or variable used with operators.Eg.5+6 here 5 and 6 are operands

An accumulator is a variable which holds(accumulates) the result returned by an expression.Eg. x=y+6 , here x is an accumulator

A Binary operator takes two or more operand. Eg, + requires two or more values.

6+10

Unary operator takes single operand, eg c++; here ++ takes single operand called c.

Page 43: Letest

Types of operators•Arithmetic Operators

Performs arithmetic operations.+,-,*,/,%(modulus)

• Arithmetic and assignment operators• ++(increment) ++a, pre increment, a++ post

increment• --(decrement) --a, pre decrement --a pre

decrement• += addition assignment• -= subtraction assignment• *= multiplication assignment• /= division assignment• %= modulus assignment

•Bitwise operators: These operators perform operation upon individual bits.

• & (Bitwise AND) 5 & 6=4101 & 110=100

• | (bitwise or)• ~ bitwise NOT• ^ bitwise XOR 5^6=3

• 101 ^110=011

Page 44: Letest

Types of operators>>(Bitwise right shift) 5>>2= 0 0000101>>2 = 00000001|01(01 is out)<<(Bitwise left shift) 5<<2= 0 0000101<<2 =20 00|00010100 (00 is out)

>>>(Unsigned right shift)-- above operators preserve sign but this does not care sign.

Int a=-124;Int b=a>>>3;

Here 1 0000100>>>3 red means - sign0001 000|100>>>3 (so -16) green means out

Page 45: Letest

Types of operatorsAn operator is a symbol which refers the type of calculation to be performed in any operation. Eg. +,-,* etc

An operand is the value or variable used with operators.Eg.5+6 here 5 and 6 are operands

An accumulator is a variable which holds(accumulates) the result returned by an expression.Eg. x=y+6 , here x is an accumulator

A Binary operator takes two or more operands. Eg, + requires two or more values.

6+10

Unary operator takes single operand, eg c++; here ++ takes single operand called c.

Page 46: Letest

Types of operatorsHow bitwise operators differ from other operators ? (QB)Bitwise operators are special type of operators which perform operation for single bit. This helps to manipulate each individual bit easily. There are many bitwise operators.& (bitwise AND), ~ (Bitwise NOT), |(Bitwise OR), ^(Bitwise XOR), >> (right Shift),<<(Left Shift) etc.For example:

class Test{public static void main(String args[]) {

int x=5;int y=6;int z=x & y;System.out.println(“Z is “+z);

}

} Here

5 means 101 6 means 110

Anding 100 means 4This program outputs 4

Page 47: Letest

Types of operatorsHow bitwise operators differ from other operators ? (QB) continued..Other operators use operand as single number. These perform arithmetic and other logical type of operations. Eg int x=5;

int y=6;int z=x+y;

Here z becomes 11

Page 48: Letest

Types of operatorsPost increment Vs. Pre increment ?The increment and decrement operators such as ++ and – can be used before or after operands.If operator proceeds operand then it is pre increment or pre decrement. Pre increment first increments the operand and returns result to the accumulator.Eg. int x=5;

int y=++x;

Here y is 6 because when expression is called, x is first incremented and then value is given to y.

And, Post increment has opposite nature, It first returns value to the accumulator and the increments.

int x=5;int y=x++;

Here y is still 5 because x first returns value to y and increments later.

Page 49: Letest

Relational operatorsRelational operators work with two operands which return either true or false but not both.>(Greater than)< >= <= !=Eg. 5>6 is false, 6<9 is true

Logical operators: These operators evaluate two or more relational operations logically. Eg. && (logical AND)|| (Logical OR)!(Logical NOT)

Ternary operator(? :) this operator is used to evaluate an expression as if-else statement and called ternary operator. Syntax is <var1>=(<cond>)?<value1>:<value2>

Here, if condition becomes true, value1 will be assigned to var1 otherwise value2 will be assigned

Page 50: Letest

Short-Circuit Logical OperatorsJava provides special version of AND(&&) or (||) as short circuit operator. Normally A || B gives true if one is true. So to determine the result Just it is enough to know the value of A and no mater what B is. In the same way A && B gives false if A is false. So java will not evaluate right hand operands if result is determined by left hand operand. This is called short circuit operation.

Eg.if(d!=0 && n/d>0) {}

Here if d is 0 then d!=0 becomes false then java knows result will become false so it will not evaluate n/d>0 this means possible runtime exception can be avoided.

If(d!=0 & n/d>0) {

}Here both operands are evaluated so runtime error may occur if d is 0

Page 51: Letest

Short-Circuit Logical Operatorspublic class First {public static void main(String args[]) {

int d=10;int n=100;if(d!=0 && n/d>5){

System.out.println(n/d);}else{

System.out.println("Division not possible");}

}}

public class First {public static void main(String args[]) {

int d=0;int n=100;if(d!=0 && n/d>5){

System.out.println(n/d);}else{

System.out.println("Division not possible");}

}}

public class First {public static void main(String args[]) {

int d=10;int n=100;if(d!=0 & n/d>5){

System.out.println(n/d);}else{

System.out.println("Division not possible");}

}}

public class First {public static void main(String args[]) {

int d=0;int n=100;if(d!=0 & n/d>5){

System.out.println(n/d);}else{

System.out.println("Division not possible");}

}}

Page 52: Letest

Short-Circuit Logical OperatorsOutput :10

Output:Diviison not possible

Output :10

Output:Exception: division by zero

Page 53: Letest

Operator Precedence Order

Order

[], (),.

++,--,~,!

* , /, %

+, -

>>, <<,>>>

>, <, >=, <=

==, !=

&

^

|

&&

||

?:

=

What is operator precedence? What is the use of? Operator. Give an example.QB

Operator precedence refers the order of execution of operators in the given expression. It tells which operator is used first in an expression.

?: operator is used to evaluate an expression as if-else statement and called ternary operator. Syntax is <var1>=(<cond>)?<value1>:<value2>

class Precedence{public static void main(String args[]) {int salary=10000;int tax=(salary>5000)?salary*10/100:salary*5/100;System.out.println("Tax is "+tax);}}

Page 54: Letest

Control StructureWhat are control flow statements?Control flow refers the flow(path) of execution of program instructions. Normally all programs have sequential flow where statements are executed from one after another. But Java (like other programming language) provides the way to control that flow by using control statements.Java provides conditional control statements for selection(if,switch) statements, for looping(for,while,do) and Unconditional branching statements like (break, continue, return).

Selective Statements:If construct:It takes a condition and performs selection on the basis of result.

Syntax:1) Single If : if(<condition>)

task1;task2;

here task1 will only be selected if condition is true.

Page 55: Letest

Control Structure2) Single If-else : if(<condition>)

task1;else

task2;task3;

here task1 will only be selected if condition is true otherwise task2; but not task3;

3) Block If : It allows us to execute multiple lines of code if condition satisfies or dissatisfies.

if(<condition>){task1;task2;

}

if(<condition>){task1;task2;

}else{

task3;task4;

}

Page 56: Letest

Example:

//class name is Selection so save file as Selection.java

class Selection {public static void main(String args[]) {

int age=10;if(age>=18)

System.out.println(“You can vote”);else

System.out.println(“You can not vote”);}

}

Page 57: Letest

Nested ifWhen if statement contains another if inside, this is called nested if. When else statement is used with other multiple if, it refers nearest if.

class Nested{

public static void main(String args[]) {int a=5,b=6,c=7,x,y;if(a==5) {

if(b<20) x=b;if(c>100)y=c;else y=b;

}

}}

*Here else is related to nearest if, marked with red color

Page 58: Letest

public class First {public static void main(String args[]) {int m=75,s=40,e=18,c=19;int t=m+s+e+c;String div=null;float p=t/4;if(p>=80){

div="Dist";}else{

if(p>=60){div="First";

}else{

if(p>=50){div="Second";

}else{

div="Third";}

}}System.out.println("You got "+div+" Division");}

}

Page 59: Letest

Switchswitch statement in java performs the task similar to multiple if-else. It takes an expression and performs branching. Switch needs break for branching which means jumping out. The expression must be byte,short,int,char only. We can also use nested switch.Syntax:switch(expression){

case value1:task1;break;

case value2:task2;break;

.

.

.default:

task;}

Page 60: Letest

public class First {public static void main(String args[]) throws IOException {

int day=5;switch(day) {

case 1:System.out.println("Sunday");break;

case 2:System.out.println("Monday");break;

case 3:System.out.println("Tuesday");break;

case 4:System.out.println("Wednesday");break;

case 5:System.out.println("Thursday");break;

case 6:System.out.println("Friday");break;

default: System.out.println("Saturday");

}

}}

Page 61: Letest

Looping(Iteration)Looping is the process of executing one or more statements repetitively for number of times . Looping continues as long as the condition is satisfied.

1) for loop:for(init; condition; increment/decrement)

task;

Or

for(init; condition; increment/decrement) {task1;task2;

}

Where init is initial value

Page 62: Letest

ExampleWap to print 1,11,111 upto 8th term (QB)

public class First {public static void main(String args[]) throws IOException {

int num=1,i;for(i=1; i<=8; i++){

System.out.println(num+"\t");num=num*10+1;

}

}}

Page 63: Letest

While LoopWhile loop checks condition first and performs repetition if condition remains true.

Syntax:InitializationWhile(condition){

tasks;increment/decreement

}

Eg. Print numbers from 1 to 100;

int n=1;while(n<=100){

System.out.println(n);n++;

}

Page 64: Letest

While LoopWap to find the sum of digits of given Number(QB)

public class DigitSum{public static void main(String args[]) {

int n=123;int s=0,r;while(n>0){

r=n%10;s=s+r;n=n/10;

}System.out.println(s);

}}

Page 65: Letest

Do LoopDo loop checks condition at last and continues repetition if condition remains true. So if initially condition is false, loop executes at least once.

Syntax:Initializationdo{

tasks;increment/decreement

} while(condition)

Eg. Print numbers from 1 to 100;

int n=1;do{

System.out.println(n);n++;

} while(n<=100)

Page 66: Letest

Do LoopWap to reverse the given digit

public class DigitSum{public static void main(String args[]) {

int n=123;int s=0,r;while(n>0){

r=n%10;s=s*10+r;n=n/10;

}System.out.println(s);

}}

Page 67: Letest

Nested LoopIf one looping statement contains another loop inside, it is called nested loop.When for uses another for then that is called nested for.

for(…………………………..) {for(…………………..){

task;}

}

If outer executes 5 times and inner loop has 4 times then outer repeats inner 5 times in each loop. So total loop will be 5x4=20 timesClass Nested{

for(int i=1; i<=5; i++){for(j=1; j<=4; j++){

System.out.println(“nested loop, I is “+i+” j is “+j);

}}

}

Output :

Page 68: Letest

Nested LoopNested loop, I is 1 j is 1Nested loop, I is 1 j is 2Nested loop, I is 1 j is 3Nested loop, I is 1 j is 4Nested loop, I is 2 j is 1Nested loop, I is 2 j is 2Nested loop, I is 2 j is 3Nested loop, I is 2 j is 4Nested loop, I is 3 j is 1Nested loop, I is 3 j is 2Nested loop, I is 3 j is 3Nested loop, I is 3 j is 4Nested loop, I is 4 j is 1Nested loop, I is 4 j is 2Nested loop, I is 4 j is 3Nested loop, I is 4 j is 4Nested loop, I is 5 j is 1Nested loop, I is 5 j is 2Nested loop, I is 5 j is 3Nested loop, I is 5 j is 4

Page 69: Letest

Using comma with forRewrite the program to reverse number

public class First {public static void main(String args[]) {

int n,s;int r;for(n=123,s=0; n>0; n=n/10){

r=n%10;s=s*10+r;

}System.out.println(s);

}}

Output: 321

Page 70: Letest

Jump StatementsJava provides following jump statements:

1) break: this statement is used to exit from a loop. break statement can also be used to exit from certain block.Syntax:break;

Or

break block_name;

class First {public static void main(String args[]) {

for(int i=1; i<=100; i++){System.out.print (i+” “);if(i==5) break;

}}

}

1 2 3 4 5

Page 71: Letest

Jump StatementsJava provides following jump statements:

2) continue: This statement forces to skip remaining code in the loop and continue to early part of loop.continue;

class First {public static void main(String args[]) {

for(int i=1; i<=10; i++){if(i==5) continue; // 5 will not be printed because next code will be skippedSystem.out.print (i+” “);

}}

}

1 2 3 4 6 7 8 9 10

Page 72: Letest

Jump StatementsJava provides following jump statements:

3) return: This statement is used to return from function body. This causes remaining code ina function to be skipped.

class First {public static void main(String args[]) {

System.out.print ("Hello");if(true) return;

System.out.print ("Hi");}

}

Output: Hello

Page 73: Letest

ArraysAn array is a group of variables which are referred by common name. An array can hold multiple values of similar type which can be accessed by using index. • One dimensional Array: This type of array holds single row of data.Declaring an array:Syntax:type var_name[]

Eg. int nums[];

Allocating Memory:var_name=new type[size];eg;.nums=new int[10];

Direct method:int nums[]=new int[10];

Alternate Direct method:int[] nums=new int[10];

Page 74: Letest

ArraysAssigning values:nums[0]=15;nums[1]=20;nums[2]=24’Etc.

Direct assignment:int[] odds={1,3,5,7};

Or

int odds[]={1,3,5,7};

Accessing value:System.out.println(odds[0]); ---------- prints 1

Page 75: Letest

ArraysExample:class First {

public static void main(String args[]) {int[] odds={1,3,5,7,9};int i;for(i=0; i<odds.length;i++){

System.out.println(odds[i]);}

}}

Multidimensional Array: Multidimensional Array holds values in tabular format. It is actually an array of arrays. To declare multidimensional array, we need to use multiple sets of brackets. []

Example: int a[][]=new int[2][3];

Or int[][] a=new int[2][3];

Page 76: Letest

ArraysAssigning values in multi-dimensional array.int a[][]={

{1,3,5},{4,8,9}

};Here

a[0][0] is 1 a[0][1] is 3 a[0][2] is 5

a[1][0] is 4 a[1][1] is 8 a[1][2] is 9

Page 77: Letest

ArraysExample:class First {

public static void main(String args[]) {int i,j;int n[][]={

{1,8,7},{2,5,9}

};

for(i=0; i<2; i++){

for(j=0; j<3; j++){

System.out.println(n[i][j]);}

}}

}

Page 78: Letest

Variable size arrayVariable size array is a type of multi-dimensional array where number of array elements are not equal.Wap to print following array (QB)Int[][] a={{1,2,3},{4,5},{6,7,8,9,10,11},{12},{13,14}};

class First {public static void main(String args[]) {

int[][] a={{1,2,3},{4,5},{6,7,8,9,10,11},{12},{13,14}};int i;for(i=0; i<4;i++){

for(int j=0; j<odds[i].length; j++){System.out.print(odds[i][j]);

}System.out.print("\n");

}

}}

Page 79: Letest

Classes and methods•Using Methods in a class requires :• Method return type eg. Int float,char,void etc• Function name

Syntax: type methodName(paramater list) {

return value;}

Here return is not required if method is defined with void keyword.

Parameter is the variable which is used to pass values inside methods.

Page 80: Letest

Classes and methodsclass First {

public static void main(String args[]) {First obj=new First();obj.greetings();int result=obj.sum(55,50);System.out.println("Sum is "+result);

}

void greetings(){System.out.println("Hi, Good Morning \n");

}

int sum(int a, int b){return a+b;

}}

Output:Hi, Good MorningSum is 105

Page 81: Letest

Classes and methodsIn this example, obj is the instance of class First. We can access methods of First using . (dot) operator. This example uses two functions. Greetings() uses void so no return is required and sum uses return type as int and two parameters also.

new operator: This operator dynamically allocates memory for an object. It allocates memory during runtime. When memory is insufficient then outOfMemory exception is raised.

Page 82: Letest

Classes and methodsclass MyRectangle{

int l;int b;void area(){

int a=l*b;System.out.println("Area is "+a);

}}

class First {public static void main(String args[]) {

MyRectangle big,small; //declare reference objectbig=new MyRectangle(); // allocate memory to big objectbig.l=20;big.b=15;big.area();

small=new MyRectangle();small.l=5;small.b=3;small.area();

}}

Area is 300Area is 15

Page 83: Letest

ConstructorConstructor is similar to method but it is called automatically when object of the class is created. A constructor has similar name to class. It is used to initialize the values upon creation of object. A constructor can take parameters also. Consructor can also be overloaded.

class MyRectangle{MyRectangle(){

System.out.println("Object created");}

}

class First {public static void main(String args[]) {

MyRectangle a;

a=new MyRectangle(); // here constructor is called

}

}

Output:Object Created

Page 84: Letest

Parameterized Constructorclass MyRectangle{

int length,breadth;MyRectangle(int l,int b){

length=l;breadth=b;

}int area(){

return length*breadth;}int perimeter(){

return 2*(length+breadth);}

}

class First {public static void main(String args[]) {

MyRectangle a;

a=new MyRectangle(5,10); // here constructor is calledSystem.out.println("Area is "+a.area());System.out.println("Perimeter is "+a.perimeter());

}}

Area is 50Perimeter is 30