0% found this document useful (0 votes)
143 views16 pages

D1.1 What Makes Java More Powerful Than C and C++?

Java offers several advantages over C and C++ including being simpler, object-oriented, platform-independent, distributed, interpreted, secure, robust, and multithreaded. It is easier to write, compile, debug, and learn than other languages. Java uses automatic memory allocation and garbage collection making it simpler than C++. It is designed to make distributed computing and networking easy. The bytecode generated by Java's compiler can run on any machine with a Java interpreter, making programs platform-independent. Java was also designed with security in mind. Some disadvantages are that Java may be perceived as slower and using more memory than C or C++, and its default GUI look and feel is different than native applications.

Uploaded by

itforcex
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
143 views16 pages

D1.1 What Makes Java More Powerful Than C and C++?

Java offers several advantages over C and C++ including being simpler, object-oriented, platform-independent, distributed, interpreted, secure, robust, and multithreaded. It is easier to write, compile, debug, and learn than other languages. Java uses automatic memory allocation and garbage collection making it simpler than C++. It is designed to make distributed computing and networking easy. The bytecode generated by Java's compiler can run on any machine with a Java interpreter, making programs platform-independent. Java was also designed with security in mind. Some disadvantages are that Java may be perceived as slower and using more memory than C or C++, and its default GUI look and feel is different than native applications.

Uploaded by

itforcex
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 16

D1.1 What makes Java more powerful than C and C++?

Advantages of Java:

JAVA offers a number of advantages to developers.

Java is simple: Java was designed to be easy to use and is therefore easy to write, compile,
debug, and learn than other programming languages. The reason that why Java is much simpler than
C++ is because Java uses automatic memory allocation and garbage collection where else C++
requires the programmer to allocate memory and to collect garbage. 

Java is object-oriented: Java is object-oriented because programming in Java is centered on


creating objects, manipulating objects, and making objects work together. This allows you to
create modular programs and reusable code.

Java is platform-independent: One of the most significant advantages of Java is its ability to
move easily from one computer system to another. 

The ability to run the same program on many different systems is crucial to World Wide Web
software, and Java succeeds at this by being platform-independent at both the source and binary
levels.

Java is distributed: Distributed computing involves several computers on a network working


together. Java is designed to make distributed computing easy with the networking capability that
is inherently integrated into it. 

Writing network programs in Java is like sending and receiving data to and from a file. For
example, the diagram below shows three programs running on three different systems, communicating
with each other to perform a joint task.

Java is interpreted: An interpreter is needed in order to run Java programs. The programs are
compiled into Java Virtual Machine code called bytecode. 

The bytecode is machine independent and is able to run on any machine that has a Java
interpreter. With Java, the program need only be compiled once, and the bytecode generated by the
Java compiler can run on any platform.

Java is secure: Java is one of the first programming languages to consider security as part of
its design. The Java language, compiler, interpreter, and runtime environment were each developed
with security in mind. 

Java is robust: Robust means reliable and no programming language can really assure reliability.
Java puts a lot of emphasis on early checking for possible errors, as Java compilers are able to
detect many problems that would first show up during execution time in other languages. 

Java is multithreaded: Multithreaded is the capability for a program to perform several tasks
simultaneously within a program. In Java, multithreaded programming has been smoothly integrated
into it, while in other languages, operating system-specific procedures have to be called in
order to enable multithreading. Multithreading is a necessity in visual and network programming.

Disadvantages of Java:

Performance: Java can be perceived as significantly slower and more memory-consuming than natively
compiled languages such as C or C++.

Look and feel: The default look and feel of GUI applications written in Java using the Swing toolkit is
very different from native applications. It is possible to specify a different look and feel through the
pluggable look and feel system of Swing. 

Single-paradigm language: Java is predominantly a single-paradigm language. However, with the addition
of static imports in Java 5.0 the procedural paradigm is better accommodated than in earlier versions of
Java.
D1.2 What is Java? And why do we say Java is a Platform Independent
Language?
When Java Code is compiled a byte code is generated which is independent of the system. This byte code
is fed to the JVM (Java Virtual Machine) which resides in the system. Since every system has its own
JVM, it doesn't matter where you compile the source code. The byte code generated by the compiler can be
interpreted by any JVM of any machine. Hence it is called Platform independent Language. 

Java's byte codes are designed to be read and interpreted in exactly same manner on any computer
hardware or operating system that supports Java Runtime Environment.

D1.3 Discuss Constants, Variables, Operators. Explain the different types


Operators used in Java?

Types of Constants:

There are seven different animals loosely called constants:

1. Literals

 e.g.

42, "abc"

You may use byte, short, char and int literals as switch case labels. However longs and Strings


are not supported.

2. Compile Time Constants

 or just plain compile constants, Officially known as “compile-time constant expressions” these
are static finals whose value

// constants known at compile time


static final int ARMS = 2;
static final int LIMBS = ARMS * 2;

These can be used as switch case labels, subject, of course, to the usual byte, short,
char and int-only restriction.

3. Load-Time Class Constants

 or just plain load constants, static finals whose value is not known

static final int SERIALNUMBER = ++generator;

These cannot used in switch case labels. All the "variables" in an interface are


implicitly static finals. They may be either compile time constants or load time constants.

4. Instance Constants

instance finals whose value is not known until object instantiation time, e. g.


These too cannot used as switch case labels. It is sometimes possible for an instance constant
to be evaluated at compile time. In that case it is treated like a literal, much like
a static compile-time constant. You can use a compile-time local int constant as a case label.

5. Local Constants

 stack finals whose value is not known until the method executes, e. g.

final int bottomLine = getTax();

These too cannot used as switch case labels.

final int LEGS = 2;

As in the example above, it is sometimes possible for a local constant to be evaluated at


compile time. In that case it is treated like a literal, much like a static compile-time
constant. You can use a compile-time local int constant as a case label.

6. Parameter Constants

 A parameter marked final. This indicates the called method will never change its local copy of
the passed parameter.

7. enum Constants

 The names of the possibilities for an enum. These are under-the-hood static finals evaluated at
load time, but through the magic of Java, you can use them as if they were known at compile
time, e.g. as case labels.

Variable:

There are several types of variables. My personal preferred terms for each are show in bold.
Variables take on different values at different stages in the execution. You can have variables
that are part of the class (static class variables), variables that are part of an object
(instance variables). Collectively static variables and instance variables are called member
variables, or just members. Variables defined inside a method are
called local, temporary or stack variables. Static final variables are called constants by
normal humans and values by the Java Language spec. Fields collectively refer to static class
variables, instance variables and static final constants defined inside classes, but outside
methods. There is one copy of each static variable per class, one copy of each instance variable
per instantiated object, and one copy of each local variable for each incarnation of its
enclosing method currently executing. Static is a strange word, inherited from C. I use it in
preference to class variable because it matches the keyword used in code. There is no
corresponding explicit keyword forinstance. A variable is declared instance by the lack of the
keyword static. There is similarly no keyword local. You create local declarations using
identifiers other where declared as types in the middle of a method. There is no obvious visual
clue.

Operators:

!,~,&,&&,*,+,++,--,/,^,=,%,||

Explanation:

! ( Not )
Performs a logical negation on booleans. Every true becomes false and false becomes true;
The ! character is created by hitting shift-1. It can be hard to tell apart from Il1| in some
fonts.
! true → false
! false → true
For bitwise negation operations on ints use the ~ operator instead.

~
Performs a bit-wise logical, one’s complement negation, usually on an int. Every zero bit
becomes 1 and every 1 bit becomes 0.
~ 0b1110_0000 → 0b0001_1111
For operations on boolean use the ! operator instead.

&
Performs a bit-wise logical and, usually on two ints. It can also be used on booleans in logical
expressions, though normally you use &&. && is sometimes called short circuit & or McCarthy &.
0b0101_0101 & 0b0001_1100 → 0b0001_0100
& logical AND is a logical carryless bitwise multiply, used for masking (getting rid of parts of
a word you don’t want), 1s where both operands have a 1 otherwise 0. Don’t confuse this with &&.
0 & 0 → 0 
0 & 1 → 0 
1 & 0 → 0 
1 & 1 → 1
&&
Performs a short circuit logical and, on two booleans. && is sometimes called the short circuit
“and” operator or the McCarthy “and” operator. John McCarthy was one of the LISP pioneers.
false && false → false 
false && true → false 
true && false → false 
true && true →
xor
^ is both a both boolean and bitwise operator in Java. It gives the bitwise difference, e. g.
0b1100_0000 ^ 0b1010_0001 -> 0b0110_0001
The expression a ^ b is true if either a or b is true but not if both are true. We call this
the exclusive or. In contrast the expression a | b is true if either a or b is true or both are
true. We call this the inclusive or or the lawyer’s and/or.
XOR has almost magical properties:
|
Performs a bit-wise logical or, usually on two ints. It can also be used on booleans in logical
expressions, though normally you use ||. || is sometimes called short circuit | or McCarthy |.
The expression a | b is true if either a or b is true or both are true. We call this
the inclusive or or the lawyer’s and/or. In contrast the expression a ^ b is true if either a or
b is true but not if both are true. We call this the exclusive or.
The | character is created by hitting shift-\. Sometimes it is displayed with a break, sometimes
not. It can be hard to tell apart from Il1! in some fonts.
0b1110_0000 | 0b1000_0001 → 0b1110_0001
Logical OR is a logical carryless bitwise addition, 1s where either operand has a 1, otherwise
0.
0 | 0 → 0 
0 | 1 → 1 
1 | 0 → 1 
1 | 1 → 1
||
Performs a short-circuit logical or, on two booleans. || is sometimes called the short circuit
“or” operator or the McCarthy “or” operator. John McCarthy was one of the LISP pioneers.
The | character is created by hitting shift-\. Sometimes it is displayed with a small gap in the
bar, sometimes not. It can be hard to tell apart from Il1! in some fonts.
false || false → false 
false || true → true 
true || false → true 
true || true → true
D1.4 Differentiate Data types Supported in Java?

Primitive Data Types:

The Java programming language is statically-typed, which means that all variables must first be declared
before they can be used. This involves stating the variable's type and name, as you've already seen:

int gear = 1;
Doing so tells your program that a field named "gear" exists, holds numerical data, and has an initial
value of "1". A variable's data type determines the values it may contain, plus the operations that may
be performed on it. In addition to int, the Java programming language supports seven other primitive
data types. A primitive type is predefined by the language and is named by a reserved keyword. Primitive
values do not share state with other primitive values. The eight primitive data types supported by the
Java programming language are:

 byte: The byte data type is an 8-bit signed two's complement integer. It has a minimum value of
-128 and a maximum value of 127 (inclusive). The byte data type can be useful for saving memory
in large arrays, where the memory savings actually matters. They can also be used in place
of int where their limits help to clarify your code; the fact that a variable's range is limited
can serve as a form of documentation.
 short: The short data type is a 16-bit signed two's complement integer. It has a minimum value
of -32,768 and a maximum value of 32,767 (inclusive). As with byte, the same guidelines apply:
you can use a short to save memory in large arrays, in situations where the memory savings
actually matters.
 int: The int data type is a 32-bit signed two's complement integer. It has a minimum value of
-2,147,483,648 and a maximum value of 2,147,483,647 (inclusive). For integral values, this data
type is generally the default choice unless there is a reason (like the above) to choose
something else. This data type will most likely be large enough for the numbers your program
will use, but if you need a wider range of values, use long instead.
 long: The long data type is a 64-bit signed two's complement integer. It has a minimum value of
-9,223,372,036,854,775,808 and a maximum value of 9,223,372,036,854,775,807 (inclusive). Use
this data type when you need a range of values wider than those provided by int.
 float: The float data type is a single-precision 32-bit IEEE 754 floating point. Its range of
values is beyond the scope of this discussion, but is specified in section 4.2.3 of the Java
Language Specification. As with the recommendations for byte andshort, use a float (instead
of double) if you need to save memory in large arrays of floating point numbers. This data type
should never be used for precise values, such as currency. For that, you will need to use
the java.math.BigDecimal class instead. Numbers and Strings covers BigDecimal and other useful
classes provided by the Java platform.
 double: The double data type is a double-precision 64-bit IEEE 754 floating point. Its range of
values is beyond the scope of this discussion, but is specified in section 4.2.3 of the Java
Language Specification. For decimal values, this data type is generally the default choice. As
mentioned above, this data type should never be used for precise values, such as currency.
 boolean: The boolean data type has only two possible values: true and false. Use this data type
for simple flags that track true/false conditions. This data type represents one bit of
information, but its "size" isn't something that's precisely defined.
 char: The char data type is a single 16-bit Unicode character. It has a minimum value
of '\u0000' (or 0) and a maximum value of '\uffff' (or 65,535 inclusive).

In addition to the eight primitive data types listed above, the Java programming language also provides
special support for character strings via the java.lang.String class. Enclosing your character string
within double quotes will automatically create a newString object; for example, String s = "this is a
string";. String objects are immutable, which means that once created, their values cannot be changed.
The String class is not technically a primitive data type, but considering the special support given to
it by the language, you'll probably tend to think of it as such. You'll learn more about
the String class in Simple Data Objects

Default Values:
It's not always necessary to assign a value when a field is declared. Fields that are declared but not
initialized will be set to a reasonable default by the compiler. Generally speaking, this default will
be zero or null, depending on the data type. Relying on such default values, however, is generally
considered bad programming style.

The following chart summarizes the default values for the above data types.

Data Type Default Value (for fields)

byte 0

short 0

int 0

long 0L

float 0.0f

double 0.0d

char '\u0000'

String (or any object)   null

boolean false

Local variables are slightly different; the compiler never assigns a default value to an uninitialized
local variable. If you cannot initialize your local variable where it is declared, make sure to assign
it a value before you attempt to use it. Accessing an uninitialized local variable will result in a
compile-time error.

Literals:

You may have noticed that the new keyword isn't used when initializing a variable of a primitive type.
Primitive types are special data types built into the language; they are not objects created from a
class. A literal is the source code representation of a fixed value; literals are represented directly
in your code without requiring computation. As shown below, it's possible to assign a literal to a
variable of a primitive type:

boolean result = true;


char capitalC = 'C';
byte b = 100;
short s = 10000;
int i = 100000;
The integral types (byte, short, int, and long) can be expressed using decimal, octal, or hexadecimal
number systems. Decimal is the number system you already use every day; it's based on 10 digits,
numbered 0 through 9. The octal number system is base 8, consisting of the digits 0 through 7. The
hexadecimal system is base 16, whose digits are the numbers 0 through 9 and the letters A through F. For
general-purpose programming, the decimal system is likely to be the only number system you'll ever use.
However, if you need octal or hexadecimal, the following example shows the correct syntax. The
prefix 0 indicates octal, whereas 0x indicates hexadecimal.

int decVal = 26; // The number 26, in decimal


int octVal = 032; // The number 26, in octal
int hexVal = 0x1a; // The number 26, in hexadecimal

The floating point types (float and double) can also be expressed using E or e (for scientific
notation), F or f (32-bit float literal) and D or d (64-bit double literal; this is the default and by
convention is omitted).

double d1 = 123.4;
double d2 = 1.234e2; // same value as d1, but in scientific notation
float f1 = 123.4f;

Literals of types char and String may contain any Unicode (UTF-16) characters. If your editor and file
system allow it, you can use such characters directly in your code. If not, you can use a "Unicode
escape" such as '\u0108' (capital C with circumflex), or "S\u00ED se\u00F1or" (Sí Señor in Spanish).
Always use 'single quotes' for char literals and "double quotes" for String literals. Unicode escape
sequences may be used elsewhere in a program (such as in field names, for example), not just in char or
String literals.

The Java programming language also supports a few special escape sequences
for char and String literals: \b (backspace), \t (tab), \n (line feed), \f (form feed), \r (carriage
return), \" (double quote), \' (single quote), and \\ (backslash).

There's also a special null literal that can be used as a value for any reference type. null may be
assigned to any variable, except variables of primitive types. There's little you can do with
a null value beyond testing for its presence. Therefore, null is often used in programs as a marker to
indicate that some object is unavailable.

Finally, there's also a special kind of literal called a class literal, formed by taking a type name and
appending ".class"; for example, String.class. This refers to the object (of type Class) that represents
the type itself.

D1.5 Briefly explain the structure of a Java program and input and output
statements used in Java?

Input and Output in Java:


 There are no standard statements in Java for input and output. All input and output is done using
methods in a number of standard Java classes.  These classes are found in a number of Java packages,
however the most common Java package is java.io. Several IO packages are available, and a programmer can
choose the one that contains the required classes.  The most common IO package is the package java.io.

IO Streams:
 A stream is a sequence of characters or bytes used for program input or output.  In general there may
be several input streams and output streams.  Java provides many different input and output stream
classes in the java.io API.  The most commonly used IO objects are:

 System.in (input stream)


 System.out (output stream for normal results)
 System.err (output stream for error messages)
 

These objects are used to input data from the user into the application, and output data to the user. 

 Generally System.in is connected to the keyboard and inputs character data*, and
 System.out and System.err are connected to the monitor and output character data.
 

*The data collected by the System.in object is character data, even if they are entered as numeric
digits. Therefore if the application performs any calculations, the input characters, it must first be
converted to the primitive data type before it is used. 

 
 

The Standard Output Stream: System.out:


 We have already used the standard output stream, System.out, which is declared in the System class and
is associated with the console window.  Writing characters to the System.out using method print() or
println() displays these characters on your screen.  Any character, printable or not can be read from or
written to a stream.  A stream has no fixed size, as we write information to a stream we are just adding
characters to the end of the stream.  The stream output methods keep track of the size of the stream.

Example:

For the statement

System.out.println(“Age is ” + age + “\nName is “ + name);

The string expression in parentheses is evaluated, and the characters are appended to the standard
output stream.  During the evaluation process, the binary numbers stored in age is converted to a
seqence of decimal digit characters.

 
User Input using the Keyboard:
 

There are a number of ways to accept input from the user.  We will look at three of them,
1. Buffered Reader
2. Scanner
3. JOptionPane
 

Buffered Reader (java.io)


 

In the System class, there are objects that can be used to accept and output data to the user. The
object, System.in, represents the keyboard (unless you specify otherwise), and is used to read user data
(entered using the keyboard) into your program.

 The class BufferedReader reads data from standard input (System.in, the keyboard.  It may look
confusing, but it does this in two steps.

Step 1: Create an InputStreamReader object

 InputStreamReader objects read characters from an input stream, in this case, the keyboard input
stream, System.in.  The constructor method of class InputStreamReader takes the input stream object as
an argument.  However objects from this class offer limited functionality because they read a single
character at a time.  When we read in data from the user, we do not want to have to process the data
character by character, we want to read and process the characters as a whole.  This is why the next
step is necessary.

Step 2: Create a BufferedReader object

 The class BufferedReader offers additional functionality.  It has methods that allow us to read
characters and lines of data more easily.  We ‘wrap’ our InputStreamReader object inside a
BufferedReader object, to add on extra functions.  The two step process looks like the one below:

InputStreamReader sysIn = new InputStreamReader(System.in);

BufferedReader input = new BufferedReader(sysIn);

Step 3: Get input from user


 
In the next step, we read the data from the user from the command line.  The user enters data, followed
by the return key, and the text that preceeded (came before) the return can be stored in our program.

Generally, because we want to give some instruction to the user (i.e. enter something now) we will
output an instruction, before we read the users data. 

 
System.out.println(“Hey You, enter something!”);

String userInput = input.readLine();

After this, the String object reference now points to the user-entered data.  In the example above, the
method readLine() is a method that belongs to the BufferedReader class, that reads a line of text from
the user.

IMPORTANT: Data collected using the readLine() method is always CHARACTER data.  Therefore, if we want
to do some calculations with the data, we first have to convert the data to numeric data before we can
process it.

Step 4: Convert character data to numeric data (if required)

We talked about “type wrappers” before.  A type wrapper is a class that has methods we can use to
convert objects such as ‘String’ objects to primitive data types, such as int or double.

To convert String data to int data, we use the wrapper class Integer (and Double for double etc).  The
class Integer has a method, parseInt() that we invoke on a String object and which returns an int
result.

int myData =Integer.parseInt(userInput);

Now we are free to use myData in our application.

Example: EchoSquare.java

Exceptions:
 Java is a programming language that is designed to help the programmer deal with bad data, and common
input failures.  An exception is an indication of a problem that occurs during a program’s
execution.  The name exception implies that the problem occurs infrequently (i.e. exception to the
rule). There are many situations that can cause an exception in a Java application. 

When an exception occurs, an exception object is created that contains information about what went
wrong.  Exception handling allows programmers to create applications that can resolve exceptions.  There
are two ways to deal with the exception; one is to write code to elegantly handle the exception, in the
section where an exception may occur.  The second is to bypass the exception.  This is called throwing
an exception, and is required in cases where exceptions may occur.  When you are throwing an exception,
you are basically acknowledging that an error may occur, but that you wish to bypass the error.  We will
look at exception handling later in the course, and for now we will just throw exceptions.
 There are a number of types of exceptions.  With input/output operations, when an operation fails, the
application will generate an IOException. In order to tell the application to bypass or throw the error,
we include the following code in our main method declaration.

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

 In the previous statement, throws is a keyword that indicates we wish to throw an
exception.  IOException indicates that the exception generated will be related to input/output
operations.  Without the throw statement, when you compile your program, you would get the following
compile time error:

 Error: unreported exception java.io.IOException; must be caught or declared to be thrown

Scanner:
The Scanner class is a class in java.util, which allows the user to read values of various types. The
Scanner class has many methods, but we will only use a few of them.  We will first look at the ones that
allow us to read in numeric values from either the keyboard without having to convert them from strings
and determine if there are more values to be read.
 

Useful Scanner methods are listed below:

 
Method Returns

nextInt() Next token as an integer

nextDouble() Next token as a double

next() Next token as a String

nextLine() Returns the entire line (or remaining line) as a String.

The Scanner object looks for ‘tokens’ in the input.  A token is a group of characters that are separated
by whitespace (space, tab, line return, end of file). A token is a series of characters that ends with
what Java calls whitespace.   If we read a line that is a series of numbers, separated by blanks, the
Scanner sees each number as a separate token.  The numeric values may all be on one line with blanks
between each value or may be on separate lines.  Whitespace characters (blanks or carriage returns) act
as separators. 
 

Example: ScannerExampleHere.java

JOptionPane:

 The JOptionPane class is part of the package javax.swing.  This class contains methods for displaying
input panes (dialog windows) which return user entered data and displaying output panes that output to
program data.

 
The common methods that we will use are shown in the table below.

Method Returns

showInputDialog(String message) Displays input window and returns the String


object entered by the user.

showMessageDialog(Container parent, String Displays a message window that takes the


message) user entered String as an argument and
returns void.

For each of the methods, there are more than one constructor.  The constructor that we invoke, and the
arguments that we pass to the constructor determine the appearance of the window.

Both methods are Class methods.  This means that they belong to the class as a whole, rather than a
specific instance of the class.  We do not need to create a JOptionPane object in order to use the
methods.  To invoke the methods we use the class name.

JOptionPane.showInputDialog(“Your message here”);

D1.6 Explain the control statements in java with syntax?

Control Statements in Java:

A program is a group of statements that are executed to achieve a predetermined task. Statements in a
program are generally executed in a sequential manner, which is called sequential execution or
sequential control flow. However, by putting the decision-making statement in the program, the normal
flow of the program can be controlled. Statements that control the flow of the program are called
control statements.

Control statements are used in programming languages to cause the flow of control to advance and branch
based on changes to the state of a program. In Java, control statements can be divided under the
following three categories:

1. Selection statements
2. Iteration statements
3. Jump statements
Selection statements in Java

Selection statements are used in a program to choose different paths of execution based upon the outcome
of an expression or the state of a variable. Java supports two selection statements: if and switch.

 The if statement
The if statement is a conditional statement. It is used to execute a statement or group of statements
based on some condition. The general form of the if statement is given below:

if (condition)
   statement1;
else
   statement2;

The condition to the if statement must be an expression that evaluates to a boolean value. If the
condition evaluates to true, the statement following the if statement is executed. However, if more
than one statement is needed to be executed, then these statements must be put within a pair of curly
braces forming a block of code. The else statement is optional, but if it is present, it must be
placed immediately after the code block attached to the if statement. The code block attached to the
else statement is executed when the condition to the if statement evaluates to false.

Argument to the if statement

The argument to the if statement must be an expression that evaluates to a boolean value. Therefore,
for the declaration int a = 1, the following statements show some of the valid boolean expressions to
the if statement:

if (a > 1)
   System.out.println(“Greater than 1″);
if (a < 1)
   System.out.println(“Less than 1″);
if (a != 1)
   System.out.println(“Not equal to 1″);

 The switch statement
The switch statement is used to select multiple alternative execution paths depending on the value of
a variable or expression. The general form of a switch statement is given below:

switch(expression){
   case val1:
       code_block1
   case val2:
       code_block2 
   .
   .
   .
   default:
       code_default;
}

where, the expression to the switch must be of a type byte, short, char, or int. A code block is
attached to the switch statement that contains multiple case statements and an optional default
statement. Each of the values (following the case statements) must be unique within the code block and
must be assignment compatible with the type of the expression without the loss of information.

The switch statement executes by comparing the value of the expression with each of the constants
after the case statements. If a match is found, the statements following that case statement are
executed. Otherwise, the statements following the default statement (if present) are executed.
Conventionally, the default label is put after all the case labels, but it may appear anywhere in the
block.

The break statement is used within the code block attached to the switch statement to terminate a
statement sequence.

The argument to the switch must be an integral expression that must evaluate to a 32-bit or smaller
integer type: byte, short, char, or int. Moreover, the legal range of the argument’s data type must
cover all the case constants used in the code block. For example, the following code fragment will not
compile successfully:
byte b = 10;
switch( b ){
   case 10 :
       System.out.print(“ten”);
       break ;
   case 1000 :
   System.out.print(“thousand”) ;
   break ;
}

In the given code, the compiler will object to the value 1000 because it is not in the range of a byte
data type.

The constants following the case statements may be integer literals or they can be variables defined
as static and final. Moreover, these constants must be unique within the code block. For example, the
following code block will not compile successfully:

 byte b = 10;
 switch( b ){
    case 10 :
       System.out.print(“ten”);
       break ;
    case 10 :
       System.out.print(“10″) ;
       break ;
 }

In the given code, the compiler will object to the second appearance of the value 10 in line number 6.

Iteration statements

Iteration statements enable program execution to repeat one or more statements, i.e., iteration
statements form loops. In Java, there are three iteration statements: for, while, and do.

 The for statement
The for loop is the most versatile looping construct. It is used to continuously execute a block of
code until a particular condition is satisfied. It comprises three parts: initialization, condition,
and iteration.

The initialization portion is generally an expression that sets the value of the loop control
variable. The loop control variable acts as a counter and controls the execution of the loop. The
initialization portion executes only once. The condition portion must be a boolean expression. It
usually tests the loop control variable against a target value and hence works as a loop terminator.
The iteration portion is usually an expression that increments or decrements the loop control
variable.

The general form of the for loop is:

for(initialization; condition; iteration){


//body of the loop
}

All the three components, i.e., initialization, condition, and iteration are optional. In case there
is only a single statement in the body of the loop, the curly braces can be omitted.

The for loop executes in the following three steps:


 When the loop first starts, the initialization expression is executed and then the
control is transferred to step 2.
 The condition is evaluated. If the condition evaluates to true, the body of the loop
executes and the program control is transferred to step 3. If the condition evaluates to false, the
loop terminates.
 The iteration expression executes and then the control is transferred to step 2.
 The while statement
The general form of the while loop is as follows:

while(condition){
   block}

where, the condition may be any expression that evaluates to a boolean value. The code block attached
to the while statement is repeatedly executed unless the condition evaluates to false.

 The do statement
The general form of the do statement is given below:

do{
code_block
} while(condition)

This statement is similar to the while statement discussed above. The only difference in this case is
that the code block attached to the do statement is executed before the condition is checked.
Therefore, even in the case of the condition evaluating to false, the code block executes at least
once.

Jump statements

Jump statements are used to unconditionally transfer the program control to another part of the program.
Java has three jump statements: break, continue, and return.

 The break statement
A break statement is used to abort the execution of a loop. The general form of the break statement is
given below:

break label;

It may be used with or without a label. When it is used without a label, it aborts the execution of
the innermost switch, for, do, or while statement enclosing the break statement. When used with a
label, the break statement aborts the execution of any enclosing statement matching the label.

Note: A label is an identifier that uniquely identifies a block of code.

 The continue statement
A continue statement is used to alter the execution of the for, do, and while statements. The general
form of the continue statement is given below:

continue label;

It may be used with or without a label. When used without a label, it causes the statement block of
the innermost for, do, or while statement to terminate and the loop’s boolean expression to be re-
evaluated to determine whether the next loop repetition should take place. When used with a label, the
continue statement transfers control to an enclosing for, do, or while statement matching the label.

 The return statement
A return statement is used to transfer the program control to the caller of a method. The general form
of the return statement is given below:

return expression;
If the method is declared to return a value, the expression used after the return statement must
evaluate to the return type of that method. Otherwise, the expression is omitted.

D1.7 ( Using IF condition ): Design a java program to check whether the given
number is Odd or Even?
import java.io.*;

public class IfElseDemo{


public static void main(String[] args) throws IOException{
try{
int n;
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
n = Integer.parseInt(in.readLine());
if (n % 2 == 0)
{
System.out.println("Given number is Even.");
}
else
{
System.out.println("Given number is Odd.");
}
}
catch(NumberFormatException e){
System.out.println(e.getMessage() + " is not a numeric value.");
System.exit(0);
}
}
}

D1.8 ( Using If and Logical Operators ): Accept a character from the user and
display weather it is a vowel or not?

You might also like