Java guide

July 29, 2019 | Author: satishkumaryadam | Category: Java Virtual Machine, Data Type, Java (Programming Language), Software Development, Notation
Share Embed Donate


Short Description

java pdf...

Description

JAVA Features of java:

The features of any program language (or) their facilities (or) services provide by the language. The various features of java language are 1. Simple:

The learning and implementation of java language is simple based on the following reasons. * The syntax of java language is similar to other language like C, C++. * The complex topics like pointers, templates of other languages are eliminated in java language making it a simple program language. The pointer concept will head to confusion & they are threat to the data. * In java language the deallocation of the memory is done automatically by garbage collector & as a programmer we need not worry about memory deallocation. Object Oriented:

Java language is an object oriented program language. Any object oriented  program language will develop an application with the help classes and objects. * An object can be anything that exist physically in the real world which requires some memory (or) space. * Every object will contain some properties & some actions. Using the properties we can describe the object & the actions represents task performed by the object. * A class can be considered con sidered as a plan (or) a model mode l (or) a blueprint for creating the objects. * A class doesn’t exist physical ly but it provides a logical explanation to the objects. For a class

we can create any number of objects. * A class is a collection of common features of a group of objects. class: student object: surendra, srikanth, venkat etc.(Ex) class: movie object: Gamyam, Bommarillu etc.

Secured:

Security is one of the most important principle of any programming language. When we develop applications in java, we need not specially provide any security programs for  protecting the data from unauthorized usage because the java language comes with by default security programs. But in C++, we have to write security program to protect the data.

Robust:

The java language is said to be a robust (or) strong program language based on the following reasons. 1. Memory Management:

The memory management in java is very efficient because there will be no wastage of memory at the time of allocation and the unused memory will be deallocated immediately by the garbage collector. 2. Exception Handling:

The errors that occur at the time of execution (Runtime Errors) are called exceptions & the process of handling those errors is called as Exception Handling, which is very efficient in java.

Distributed:

The java language is said to be a distributed language. With the help of this distributed nature we can access the data available in multiple machines and provide it to the user. Using the distributed nature we can improve the performance because of the more availability and more accessibility of the data. Platform Independent (or) Architecture Neutral:

The java language is said to be a platform independent language because it can be executed on any machine irrespective of the operating system, their architecture, their hardware (or) s/w etc. When a ‘C’ program is compiled, the compiler will convert the ‘C’ language instructions into machine level instructions. The machine level instructions generated by ‘C’

compiler can be executed only on that machine where it is compiled. If we want to execute on

another machine then we have to compile it once again. This nature of ‘C’ language makes it “machine dependent”.

When a java program is compiled, the compiler will generate byte code instructions which are called as Special java instructions.

The byte code instructions available in demo.class can be executed on any machine with the help of JVM(Java Virtual Machine). This nature of java makes it machine independent (or) platform independent. Compiler:

It will compile all the code, while compiling if we get any errors, it will store all the errors in memory. Once the code the code gets compiled, then it will generated all the errors at a time. Interpreter:

It will compile line by line, it doesn’t has memory to store the value. While

compiling, if we get any error, they will throw the error & stops the execution at that line once error gets fixed, then continue execution with the next line. The java language is said to be a portable language using which we can develop applications which is a collection of small reusable and replacable components. Interpreted:

The java language contains an interpreter

along with the compiler which is

responsible for executing the code & therefore called as interpreted language. Other

language like C, C++ etc has compiler (or) Interpreter only.

High Performance:

In language the execution of a program is done by both compiler & interpreter which reduce the execution time & thereby improving the performance of the application.

Multi Threaded:

A language that supports multiple threads will be called as multi threaded language. Every thread can be considered as a part of a program which is controlling the application. The multi thread concept will reduce the waiting time & improves the performance of the application.

Dynamic:

The location of the memory in java language will be done at the time of execution.  In

C, memory allocation will be done at the time of compilation.

 Every  The

java program will have the extension has [.java].

[.java] file developed by the programmer will be provided to the compiler. The compiler

will take the (.java) file and verifies whether the java code is valid (or) not, if valid the compiler will generate a (.class) file containing byte code instructions (Special java instructions)  The

(.class) file generated by the compiler will be provided to the JVM for the execution.

JVM Architecture:

The .class file will be provided as input to the class loader subsystem. The class loader subsystem will perform the following operations. * The class loader subsystem will load the (.class) file into the JVM. * Before loading the (.class) file it will verify whether the bytecode is valid (or) not with the help of bytecode verifier. * If the bytecode is valid then it will load bytecode in different locations called as Runtime Data Areas. The various Runtime Data Areas are: 1. Method Area:

This area can be used for storing all the class code and the method code. 2. Heap:

This area can be used for storing the objects. 3. Java Stack:

This area can be used for storing all the methods that are required for execution. The java stack can be considered as a collection of frames where each frame will contain the information of one method.

4. PC Register (Program Counter):

This register will contain the address of the next instruction that has to be executed. 5. Java Native Stack:

This area can be used for storing all the non-java code (Native code).

Execution Engine:

The execution engine is responsible for executing the byte code available in runtime data areas. The execution engine contains two parts: 1. Interpreter. 2. JIT compiler (Just In Time). Both the pass of the execution engine are responsible for executing the code simultaneously which reduces the execution time & there by improves the performance of the application. The bytecode available in the runtime data areas will be shared by the interpreter and JIT compiler. Most of the code will be used for executing the code whenever required. The code executed by the JIT compiler is called as HOTSPOTS. Native Library:

This interface will help the JVM to load the native library into the runtime data errors. OS:

The JVM has to interact with the operating system so that it can use the resources available in that machine.

Note:

The bytecode available in (.class) file can be executed on any machine with the help of JVM. Comments:

The comments are used for explaining the code or they make the code more understandable. The comments in a program will improve the readability of the code. Comments are not part of the logic, they are non-executable statements.

In java language we have different types of comments. They are 1. Single Level Comments:

The single level comment can be used for writing a comment in a single line. The single line comments begins with”//” symbols & end in the same line.

Ex:

//this is a single line comment.

2. Multiline Comment:

Multiline comments can be used for writing the comments in multiple lines. The multiple comments begins with “/*” ends with “*/”.

Ex: /* this is a line one comment this is a line two comment this is a line three comment */ These comments can begin in a line & end in any other line.  Single

line & multiple comments are used purely for explaining the code only.

Multiple Comments:

These comments can be used for creating a document (Manual) for the software that is developed i.e., using these comments we can create an API (Application Programming Interface). These comments will begin with”/**” & ends with “*/”. These comments can begin & end in any line. Syntax:

/** Author: Srikanth Created on: Last modified on:

*/ (What are the classes & methods are used everything will  be describing about prg (or) software)

DATA TYPES Data types will represent the type of data that can be stored into a memory location. The data types in java can be classified into three types 1. Primitive Data Types:

These data types are predefined and they are designed to store a single value. Ex: int char 2. Derived Data Types:

These data types are predefined and they are designed to store multiple values. Ex: array 3. User Defined Data Types:

These data types are created by user or programmer according to the application requirement. The user defined data type can contain any no of values and they can be of any type. Ex: class 1. Primitive Data Types:

These data types are predefined and they are used for sharing basic inputs required for a program. These data types are also called as fundamental data types which can be used for storing a single value. The java language provides eight primitive data types classified into 4 categories. i. Integer Category ii. Floating point Category iii. Character Category iv. Boolean Category

i. Integer Category:

This category is used for storing numbers which can be either +ve or  – ve without decimal point. Under the integer category we have four primitive data types. They are a)  byte  b) short

c) int d) long The purpose of all the 4 types under integer category is to store same kind of data but their size and ranges are different so that the memory can be utilized efficiently. Data Type

Size

Range

 byte

1byte

-128

to

127

short

2bytes

-32768

int

4bytes

-2147483648 to

long

8bytes

-9223372036854775808

to

32767 2147483648 to

9223372036854775807

 byte



1 byte



8 bits

ii. Floating point Category:

This category is used for storing numbers which can be either +ve or  – ve with decimal point. Under the floating point category we have two primitive data types. The y are a) Float  b) Double The purpose of both the primitive data types floating point category is to store same kind of data  but their size and ranges are different so that the memory can be utilized efficiently. Data Type

Size

Range

No of digits after decimal pts

float

4bytes

-1.4e -45 to 3.4e 38

7

double

8bytes

4.9e-324

15

to 1.8e308

iii. Character category:

This category is used for storing single character. A character can be represented  by either an alphabet (lowercase or uppercase) or digit or special symbol. * Under character category we have only 1 primitive data type. a) char Data Type

char

Size

Range

2bytes

0 to 65535

* In C 1byte because of ASCII. * Here all languages can be used. *** Why size of char 1byte in C & 2byte in java? The application that are developed in C language and to store that characters of only english language and to store that characters 1byte of memory is sufficient. The C language uses ASCII character set. The application developed java language use character of all foreign languages. To store the characters of all the foreign languages 1byte of memory is not sufficient. Size of char is increased to 2bytes. Java language uses UNICODE set.

iv. Boolean Category:

This category can be used for storing only 2 values and they are true & false. Under the boolean category we have only one primitive data type and it is boolean. Data Type

 boolean

Size

JVM dependent

Range

true false

** Why it is JVM dependent? The JVM that is used for executive java program can be implemented by any organization. The size of the boolean will be decided by the organization that develops the JVM. Therefore boolean size JVM dependent.

Variables Variable is a name given to the memory location in which we can store some data or value. Ex:

Variable Declaration:

The process of specifying what type of data is to store into the memory is called as variable declaration. Syntax:

datatype variablename; datatype var1,var2,var3,….; Ex:

int age; int rollno,accno; double marks; char grade;  boolean result; When a variable is declared, the memory for the variable will be allocated and it can contain some data. The amount of memory allocated to a variable will depend upon the data type that is specified. Once the memory for the variable is allocated it can hold some data. If we do not  provide any value to a variable then the memory location will automatically contain default value of variable type.

Default Values

 byte - 0 short - 0 int

- 0

long - 0 float - 0.0 double - 0.0 char

- space

 boolean - false string

- null

student - null Any class –  null If a variable is declared and if we do not provide any value then the variable will be automatically initialized with their default value. If we do not want default values then we can initialize the variable with our own values at the time of declaration. Syntax:

datatype variablename; datatype var1,var2,var3,….;

Initialization:

Process of providing value to a variable for the first time is called initialization. The value of a variable can be changed any no of times during the execution of the program.

Assignment:

Process of providing value to a variable for the second time is called assignment.

Syntax:

int age = 20; Initialization age = 21;

Assignment

age = 22;

Assignment

int rollno = 123; double marks = 98.76; char grade = ‘A’;

 boolean result = false;

Keyword:

Words that are predefined meaning in java are whose meaning is already reserved are called as keywords.

Literal:

Value that we store in the variable are called literals.

Identifier:

Any name that is used for the purpose of identification will be called as identifier.

Rules for identifier:

* The identifier is combination of _, $, alphabets, digits. * Identifier should not begin with digit, alphabets, _, $. * Identifier cannot have any space. * Keywords of java cannot be used as identifiers. * There is no restriction on the length of the identifier but recommended not to use more than 16 characters. * The names of the identifier must be meaningful & appropriate to the application. Ex:

int x = 25;

Valid but not recommended

int age = 25;

Valid & recommended

Structure of java program:  package statement import statement class { Variables Methods Public static void main(String[] args) { Statements } }

* The package statement is an optional statement. A java program can contain atmost one  package statement. The package statement should be first executable statement in a java  program. * The import statement is an optional statement. A java program can contain any no of import statements. The import statement must be specified after the package statement before the class. * Java program can contain any no of classes. Every class can contain variables & methods which are together called as members of the class. A class can contain any no of variables & any no of methods. * The execution of a java program is done by main methods whose syntax must be as follows:

* The main method can contain any no of statements. A java program can have any no of commands and they can be specified anywhere in the program. The comments are nonexecutable statement of java program.

Procedure to Develop, Save, Compile & Execute java program: Step1: Develop a java program. We require an editor like notepad, wordpad, vi editor etc.

Class FirstProgram{ Public Static Void Main(String[] args){ System.out.println(“Welcome to java@inetsolv”);

} }

Step2: Saving a java program.

* A java program can be saved with any name but extension of java program must be java. Syntax: Firstprg.java

Step3:  Compiling a java program.

To compile a java program we require a command prompt and we use javac command. Syntax: javac filename/programme with extension Ex: javac firstprogram.java When a java program is compiled the compiler will check whether java code is valid or not, if valid then compiler generates .class file which contains byte code.

Step4: Executing a java program.

To execute a java program we require a command we use java command .class file generated by compiler will be provided to the JVM for execution. Syntax: java classname without extension Ex: java Firstprogram o/p Welcome to java@inetsolv

 To develop a java application we need to install java s/w. The java language is an open

source & freeware which can be downloaded free of cost.  Once the java s/w is installed then we need to set the path. The path is called as an

environment variable. The operating system variables are called as environment variables.  The path variable should contain address or the location where the java is installed.

Syntax:

Set PATH = java installation folder Set PATH = c:\program files\java\jdk1.6.0_12\bin; * Setting the path means proving the address to java installation to OS.

Program 2:

Class secondprogram{ Public static void main(String[] arg){ System.out.println(“this is my second”); System.out.println(“java program”); System.out.println(“at inetsolv”);

} }

Java Coding Conventions (Hungarian Notations)

Every predefined class, predefined method, variable follow java coding conventions and we are also recommended to follow the same coding conventions. It is always a good programming practice for developing applications following the conventions.

1. Conventions for a Class:

A class name can contain any no of words. The first letter of every word should  be specified in uppercase. Ex: System StringBuffer FirstProgram.

2. Conventions for a Interface:

Interface name can contain any no of words. The first letter of every word should  be specified in uppercase. Ex: Runnable WindowListener MyInterface.

3. Conventions for a Method:

A method name can contain any no of words. The first letter of every word should  be specified in lowercase. The first letter of remaining words if available should be specified in uppercase. Ex: main()

tocharArray()

areaOfTheCircle()

4. Conventions for a Variable:

The variable name should be any no of words. The first letter of every word should be specified in lowercase. The first letter of remaining words if available should be specified in uppercase. Ex: length

breadthOfRectangle

numberOfStudents

5. Conventions for a Constant:

The constant name should be any no of words. All the letters of all words should  be specified in lowercase. It contains multiple words separated them by underscore. Ex: MAX_VALUE

MIN_PRIORITY

6. Conventions for a package:

The package name can contain any no of words. It should be specified completely in lowercase. Ex: java.lang

java.io

pack1.pack2

Note: The keywords of java should be specified in lowercase.

* java is case sensitive.

Operators * Any symbol that is used for performing an operation will be called as an operator. * The values on which the operator performs the operations will be called as operands.

* Based on the no of operands the operator considers they are classified into following categories. 1. Unary Operators: These operators will perform operations on single operand. 2. Binary Operators: These operators will perform operations on two operands. 3. Ternary Operators: These operators will perform operators on three operands. * The operators of java language are classified into various categories based on task they  perform.

1. Arithematic Operators:

These operators can be used for calculating mathematical operations. The various arithematic operators are i. Addition (+) ii. Subtraction (-) iii. Multiplication (*) iv. Division (/) v. Modulus (%) * If both operands are of integer type the result will be integer. * If any one of operand is of float type the result is float.

Ex: 7 + 2 = 9 7-2=5 7 * 2 = 14 7 / 2 = 3 or 7 / 2.0 = 3.5 7%2=1 * An arithematic expression will be evaluated from left to right. int x=10;

O/P : 10

int y=x * 3 – 2;

O/P : 28

* We can change order of evaluation by changing pair of parenthesis. int x=10;

O/P : 10

int y=x * (3 – 2);

O/P : 10

* The arithematic expression will be evaluated from left to right. If operators have same  precedence otherwise evaluate the higher precedence operators first and then lower precedence operators. * The arithematic operators */% +Ex:

Ex:

 higher

 lower

precedence

precedence

int x=10;

O/P: 10

int y=x * 5 / 2;

O/P : 25

int x=10;

O/P: 10

int y=x - 5 / 2;

O/P : 8

2. Unary Operators:

These operators will perform operations on single operand. The various unary operators are -, ++, --. i.Unary Minus (-):

Converts positive to negative & negative to positive. Ex: int temp=23; int temp= -23; int temp= -(-23);

ii. Increment Operator (++):

This operator will increment value by 1.Based on the position of increment operator the increment operator is classified into two types. a) Pre-increment operator:

If increment operator is placed before the variable is called pre-increment operator (++x). The pre-increment value will use the value after increasing it. b) Post-increment operator:

If increment operator is placed after the variable is called post-increment operator (x++). The post-increment value will use the value before increasing it. ii. Decrement Operator (++):

This operator will decrement value by 1.Based on the position of decrement operator the decrement operator is classified into two types. a) Pre-decrement operator:

If decrement operator is placed before the variable is called pre-decrement operator (--x). The pre-decrement value will use the value after decreasing it. b) Post-decrement operator:

If decrement operator is placed after the variable is called post-decrement operator (x--). The post-decrement value will use the value before decreasing it. Ex: Class Operators { Public static void main(String[] args){ int a=7;

//8 9

int b=++a;

//8 7 6

int c=b--;

//8 7

int d=a++ + --b - --c;

//8 + 6 - 7

System.out.println(a); System.out.println(b); System.out.println(c); System.out.println(d); } }

7

* The increment & decrement operators can be applied to all numeric data types. The numeric data types are byte, short, int, long, double, float and char. * Increment & decrement operators can be applied to only variables. * Increment & decrement operators cannot be nested. Ex: (++(++a)); 3. Assignment Operators:

This operator is used for assigning value to a variable. The assignment operator is =. * This operator will copy value from right to left. * On the right side we can specify either a value (or) variable (or) an expression but left side we can specify only variable. x=5 y=x z=x + y * If the assignment operator is combined with other operator it is called compound assignment operators. += , -= , *= , /= , %= . Ex: x=x+3 x+=3 y=y-2

y-=2

4. Relational Operators:

These operators can be used for comparing the values. These operators are also called as comparision operators. The various relational operators are >, >=, , >.

~ (Tilde):

This operator will convert bits from one to zeros and 0’s to 1.

Ex: ~ (Negation operator) (Tilde)

2’s compliment = 1’s compliment + 1

 ~x

= - (x + 1)

& (Bitwise &):

This operator will perform operation on bitwise of a number.

| (Bitwise |):

This operator will perform operation on bits of a number.

^ (Bitwise ^):

This operator will perform operation on bits of a number.

> (Right Shift)

This operator will shift bits of a number towards right side by the specified no of  positions.

Ex:

* Shifting the bits of a number towards right side by 1 position dividing number by 2.

>>> (Unsigned Right Shift):

This operator will shift bits of a number towards right side by the specified no of  positions.

Diff between >> and >>>? * When the bits of a number are shifted towards right side by using >>,the sign bit will be copied

as it is into the resultant. i.e., the positive input will give positive output & negative input will give negative output. * When we shift bits of a number towards right side by using >>>,we always insert bit 0 into the signed bit. i.e., the result will be always positive whether the in put is either negative or positive.

Rules for logical operator:

* Logical operators can be applied to combination of boolean type. * Bitwise operators can be applied to an combination of numbers without decimal point. (Byte, Short, int, long, char) * The operators &, |, ^ can be applied any combination of boolean types or any combination of numeric types with decimal points.

7. Conditional Operator: (?:)

This operator can perform task based on result of a condition. The condition operator is ?: Syntax:  cond ? exp1 : exp2

This operator will be called as ternary operator. If the result of condition is true then it will evaluate exp1 & if result of condition is false then it will evaluate exp2. Ex: max = (x > y)? x : y Diff = x > y ? x –  y : y –  x * Conditional operator can be nested. Ex: System.out.println(23?:”hai”:”hello”):”bye”);

8. New Operator:

 New operator is used for creating an object of a class means allocating memory for members of class in the heap memory. Ex: Class Sample{ } Sample s = new sample(); * For every class in java language we can create any no of objects. * Using new operator we can create object for any predefined or user defined class. * S is called reference variable because they point to refer to object of the class. * The name of the reference variable can be any valid java identifier.

9. Dot (.) Operator:

The dot operator can be used for accessing the members(variables,methods) from a class from a package.

className.variable reference.variable

className.method reference.method

Package.className

Control Statements The statements of a java program will always be executed in sequential order. If we do not want to execute the statements in a sequential order then we need to take the help of control statements. The control statements will help the programmer to decide the flow of execution in a program. The control statements are classified into following categories. 1. Conditional Statements 1.1 if-else statement 1.2 Switch statement 2. Iterating Statements 2.1 for loop 2.2 while loop 2.3 do-while loop 2.4 for-each loop 1. Conditional Statements:

These statements can execute a group of statements based on a condition or a value. 1.1 If else statement:

The if-else stmt can be used for executing a group of statements based on condition. Syntax:

if(condition){ Stmt1 } else { stmt2 }

* If the condition is satisfied then if block will be executed and if the condition is not satisfied then execute else block.

Ex: Class IfElseDemo { Public static void main (String [] args) { int n=2; if (n%2=0) { System.out.println(“Even Number”);

} else { System.out.println(“Odd Number”);

} } } Rules:

* Specifying condition to the if statement is mandatory and it should be only Boolean type. * Specifying an else block is optional. * Specifying flower braces is optional. If we do not specify flower braces then it will consider only one statement and that one statement is mandatory. If we want to consider multiple stmts then specify the flower braces is mandatory and within the flower braces we can specify any no of stmts (0 or more). * In if-else stmt we can execute exactly one block either if block or else block. There is no chance of slipping both the blocks and no chance of executing both the blocks.

1.2 Switch statement:

The switch stmt can be used for executing a group of stmts based on a value.

Syntax: Switch (argument) { Case label 1: statement1;  break; Case label 2: statement2;  break; Case label 3: statement3;  break; default: statement; } * If an application contains less no of options then use if else. But if an application contain multiple options then recommended to use switch statement because it improves the readability of the code. Ex: Class SwitchDemo{ Public static void main(String[] args){ int ch=3; Switch(ch){ Case 1: System.out.println(“first choice”);

 break; Case 2: System.out.println(“second choice”);

 break; Case 3: System.out.println(“third choice”);

 break; Case 4: System.out.println(“fourth choice”);

 break; default: System.out.println(“wrong choice”);

} } } * Replace switch statement by if else ladder.

Class SwitchDemo { Public static void main (String[] args) { int ch=3; if(ch==1){ System.out.println(“first choice”);

} elseif(ch==2){ System.out.println(“second choice”);

} elseif(ch==3){ System.out.println(“third choice”);

} elseif(ch==4){ System.out.println(“fourth choice”);

} else{ System.out.println(“wroong choice”);

} } } Rules: * Specifying the argument to switch stmt is mandatory and it should be either byte type, short type, char type or int type. * Specifying the case & default both are optional. * Specifying the flower braces to the switch stmt is mandatory. * The default stmt can be specified within the switch block. Generally the default stmt will be specified after all the cases. * A switch stmt can contain any no of case (0 or more).

* A switch stmt can contain atmost one default stmt. * The case labels must be unique. Most not be empty and must not be repeated.

PROGRAM: To read data from keyboard.

import java.io.*; class ReadData{ Public static void main (String[] args) Throws IOException{ BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); System.out.print(“Enter first number:”);

String s1=br.readline(); int a=Integer.parseInt(s1); System.out.print(“Enter second number:”);

String s2=br.readline(); int b=Integer.parseInt(s2); System.out.print(“sum:”+(a+b));

} }

Ex: Program to write the biggest number using If Else condition.

class IfElseDemo {  public static void main(String[] args) { int a=10, b=30, c=20, d=8; if((a>b)&(a>c)&(a>d)) { System.out.println("a is big); } elseif((b>c)&(b>c)&(b>d)) {

System.out.println("b is big); } if((c>a)&(c>b)&(c>d)) { System.out.println("c is big); } else { System.out.println("d is big); } } } O/P: b is big

Ex: Write a program to perform mathematical calculations using switch statement.

Class SwitchDemo{ Public static void main(String[] args){ int a=8, b=4, c; int ch=3; Switch(ch){ Case 1: c=a+b; System.out.println(“sum is:”+c);

 break; Case 2: c=a-b; System.out.println(“subtraction is:”+c);

 break; Case 3: c=a*b; System.out.println(“multiplication is:”+c);

 break; Case 4: c=a/b; System.out.println(“division is:”+c);

 

break; } } } O/P: multiplication is: 32

* Switch argument & continues until it encounters a break statement (or) teachers end of the switch statement. * The break statements is a transfer statement which will transfer from inside switch to outside. So that it stops (or) skips the execution of remaining cases. So that remaining statements are not executed. * Replacing switch with else if ladder.

Class SwitchDemo{ Public static void main(String[] args){ int ch=2; if(ch==1){ System.out.println(“first choice”);

} if(ch==2){ System.out.println(“second choice”);

} if(ch==3){ System.out.println(“third choice”);

} if(ch==4){ System.out.println(“fourth choice”);

} else{ System.out.println(“wrong choice”);

}

} } O/P: Second choice

Replacing switch with else if ladder is not recommended to reduce the readability of the  program.

Iterating statements:

The iterating statements can be used if we want to execute a group of statements repeatedly multiple times.

1. For Loop: Purpose: A for loop has to be used if we want to execute a group of statements multiple

times & it should be used when we know the exact number of iterations. Syntax:

* Program to write multiplication table using for loop: Class forDemo{  public static void main(String[] args) { int n=6; for(int i=1; i
View more...

Comments

Copyright ©2017 KUPDF Inc.
SUPPORT KUPDF