Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
2 views

Java Notes Introduction

Java, developed by Sun Microsystems in 1991 and later acquired by Oracle, is a platform-independent, object-oriented programming language known for its simplicity, robustness, and security. Key features include multithreading, portability, and high performance, with a strong emphasis on error checking and memory management. The document also covers Java's architecture, including the Java Virtual Machine (JVM), Java Development Kit (JDK), and Java Runtime Environment (JRE), along with essential programming concepts such as classes, methods, and tokens.

Uploaded by

Chaya Anu
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Java Notes Introduction

Java, developed by Sun Microsystems in 1991 and later acquired by Oracle, is a platform-independent, object-oriented programming language known for its simplicity, robustness, and security. Key features include multithreading, portability, and high performance, with a strong emphasis on error checking and memory management. The document also covers Java's architecture, including the Java Virtual Machine (JVM), Java Development Kit (JDK), and Java Runtime Environment (JRE), along with essential programming concepts such as classes, methods, and tokens.

Uploaded by

Chaya Anu
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 24

Page 1 of 24

Java Notes

JAVA was developed by Sun Microsystems Inc in 1991, later acquired by Oracle Corporation. It was
developed by James Gosling and Patrick Naughton.

Java history is interesting to know. The history of java starts from Green Team. Java team members (also
known as Green Team), initiated a revolutionary task to develop a language for digital devices such as set-
top boxes, televisions etc.

1) James Gosling, Mike Sheridan, and Patrick Naughton initiated the Java language project in June 1991.
The small team of sun engineers called Green Team.

2) Originally designed for small, embedded systems in electronic appliances like set-top boxes.

3) Firstly, it was called Oak and was developed as a part of the Green project.

4) In 1995, Oak was renamed as "Java" because it was already a trademark by Oak Technologies.

5) Why had they choosen java name for java language? The team gathered to choose a new name. Java is
an island of Indonesia where first coffee was produced (called java coffee).

6) Originally developed by James Gosling at Sun Microsystems (which is now a subsidiary of Oracle
Corporation) and released in 1995.

7) In 1995, Time magazine called Java one of the Ten Best Products of 1995.

Features of Java

 Java is a platform independent language

Compiler (javac) converts source code (.java file) to the byte code(.class file). As mentioned above,
JVM executes the bytecode produced by compiler. This byte code can run on any platform such as
Windows, Linux, Mac OS etc. Which means a program that is compiled on windows can run on Linux
and vice-versa. Each operating system has different JVM, however the output they produce after
execution of bytecode is same across all operating systems. That is why we call java as platform
independent language.

Page 1 of 24
Page 2 of 24

 Java is an Object Oriented language

Object oriented programming is a way of organizing programs as collection of objects, each of which
represents an instance of a class.
4 main concepts of Object Oriented programming are:
1. Abstraction
2. Encapsulation
3. Inheritance
4. Polymorphism
 Simple

Java is considered as one of simple language because it does not have complex features like
Operator overloading, multiple inheritance, pointers and explicit memory allocation.

 Robust Language

Robust means reliable. Java programming language is developed in a way that puts a lot of emphasis
on early checking for possible errors, that’s why java compiler is able to detect errors that are not
easy to detect in other programming languages. The main features of java that makes it robust are
garbage collection, Exception Handling and memory allocation.

 Secure

Java is designed to be secure in a networked environment. The Java run-time environment uses a
bytecode verification process to ensure that code loaded over the network does not violate Java
security constraints.

 Distributed

Using java programming language we can create distributed applications. RMI(Remote Method
Invocation) and EJB(Enterprise Java Beans) are used for creating distributed applications in java. In
simple words: The java programs can be distributed on more than one systems that are connected
to each other using internet connection. Objects on one JVM (java virtual machine) can execute
procedures on a remote JVM.

 Multithreading

Java supports multithreading. Multithreading is a Java feature that allows concurrent execution of
two or more parts of a program for maximum utilization of CPU.

 Portable

As discussed above, java code that is written on one machine can run on another machine. The
platform independent byte code can be carried to any platform for execution that makes java code
portable.

 High performance.

Although Java is an interpreted language, it was designed to support “just-in-time” compilers, which
dynamically compile bytecodes to machine code.

Java Terminologies

 Java Virtual Machine (JVM)

This is generally referred as JVM. Before, we discuss about JVM lets see the phases of program
execution. Phases are as follows: we write the program, then we compile the program and at last we
run the program.

Page 2 of 24
Page 3 of 24

1) Writing of the program is of course done by java programmer like you and me.

2) Compilation of program is done by javac compiler, javac is the primary java compiler included in
java development kit (JDK). It takes java program as input and generates java bytecode as output.

3) In third phase, JVM executes the bytecode generated by compiler. This is called program run
phase.

So, now that we understood the primary function of JVM is to execute the bytecode produced by
compiler. Each operating system has different JVM, however the output they produce after
execution of bytecode is same across all operating systems. That is why we call java as platform
independent language.

 bytecode

As discussed above, javac compiler of JDK compiles the java source code into bytecode so that it can
be executed by JVM. The bytecode is saved in a .class file by compiler.

JVM (Java Virtual Machine)

JVM (Java Virtual Machine) is an abstract machine. It is a specification that provides runtime
environment in which java bytecode can be executed.

JVMs are available for many hardware and software platforms (i.e. JVM is platform dependent).

What is JVM?

It is:

1. A specification where working of Java Virtual Machine is specified. But implementation


provider is independent to choose the algorithm. Its implementation has been provided by
Sun and other companies.
2. An implementation. Its implementation is known as JRE (Java Runtime Environment).
3. Runtime Instance Whenever you write java command on the command prompt to run the
java class, an instance of JVM is created.

What it does?

The JVM performs following operation:

Loads code

Verifies code

Executes code

Provides runtime environment

JVM provides definitions for the:

Memory area

Class file format

Register set

Garbage-collected heap

Fatal error reporting etc.

Page 3 of 24
Page 4 of 24

 Java Development Kit(JDK)

While explaining JVM and bytecode, I have used the term JDK. As the name suggests this is complete
java development kit that includes JRE (Java Runtime Environment), compilers and various tools like
JavaDoc, Java debugger etc.

In order to create, compile and run Java program you would need JDK installed on your computer.

 Java Runtime Environment(JRE)

JRE is a part of JDK which means that JDK includes JRE. When you have JRE installed on your system,
you can run a java program however you won’t be able to compile it. JRE includes JVM, browser
plugins and applets support. When you only need to run a java program on your computer, you
would only need JRE.

Internal Architecture of JVM

1) Classloader - Classloader is a subsystem of JVM


that is used to load class files.

2) Class(Method) Area - Class(Method) Area stores


per-class structures such as the runtime constant
pool, field and method data, the code for methods.

3) Heap - It is the runtime data area in which


objects are allocated.

4) Stack - Java Stack stores frames.It holds local


variables and partial results, and plays a part in
method invocation and return.

Each thread has a private JVM stack, created at the


same time as thread.

A new frame is created each time a method is


invoked. A frame is destroyed when its method invocation completes.

5) Program Counter Register - PC (program counter) register. It contains the address of the Java virtual
machine instruction currently being executed.

6) Native Method Stack - It contains all the native methods used in the application.

7) Execution Engine - It contains:

 A virtual processor
 Interpreter: Read bytecode stream then execute the instructions.
 Just-In-Time(JIT) compiler: It is used to improve the performance.JIT compiles parts of the byte code
that have similar functionality at the same time, and hence reduces the amount of time needed for
compilation. Here the term “compiler” refers to a translator from the instruction set of a Java virtual
machine (JVM) to the instruction set of a specific CPU.

Structure of Java Program

Page 4 of 24
Page 5 of 24

 A package is a collection of classes, interfaces and sub-packages. A sub package contains collection
of classes, interfaces and sub-sub packages etc. java.lang.*; package is imported by default and this
package is known as default package.
 Class is keyword used for developing user defined data type and every java program must start with
a concept of class.
 "ClassName" represent a java valid variable name treated as a name of the class each and every class
name in java is treated as user-defined data type.
 Data member represents either instance or static they will be selected based on the name of the
class.
 User-defined methods represents either instance or static they are meant for performing the
operations either once or each and every time.
 Each and every java program starts execution from the main() method. And hence main() method is
known as program driver.
 Since main() method of java is not returning any value and hence its return type must be void.
 static: static is a reserved keyword which means that a method is accessible and usable even though
no objects of the class exist.
 Since main() method must be accessed by every java programmer and hence whose access specifier
must be public.
 Each and every main() method of java must take array of objects of String.
 Block of statements represents set of executable statements which are in term calling user-defined
methods are containing business-logic.
 The file naming conversion in the java programming is that which-ever class is containing main()
method, that class name must be given as a file name with an extension .java.

Java Tokens
A java Program is made up of Classes and Methods and in the Methods are the Container of the various
Statements and a Statement is made up of Variables, Constants, operators etc.

Page 5 of 24
Page 6 of 24

Tokens are the various Java program elements which are identified by the compiler. A token is the smallest
element of a program that is meaningful to the compiler. Tokens supported in Java include keywords,
variables, constants, special characters, operations etc.
When you compile a program, the compiler scans the text in your source code and extracts individual
tokens. While tokenizing the source file, the compiler recognizes and subsequently removes whitespaces
(spaces, tabs, newline and form feeds) and the text enclosed within comments. Now let us consider a
program
//Print Hello
Public class Hello{
Public static void main(String args[]) {
System.out.println(“Hello Java”);
}
}
The source code contains tokens such as public, class, Hello, {, public, static, void, main, (, String, [], args, {,
System, out, println, (, "Hello Java", }, }. The resulting tokens· are compiled into Java bytecodes that is
capable of being run from within an interpreted java environment. Token are useful for compiler to detect
errors. When tokens are not arranged in a particular sequence, the compiler generates an error message.
Tokens are the smallest unit of Program There is Five Types of Tokens
1) Reserve Word or Keywords
2) Identifier
3) Literals
4) Operators
5) Separators

Literal
By literal we mean any number, text, or other information that represents a value. This means what you type
is what you get. We will use literals in addition to variables in Java statement.
While writing a source code as a character sequence, we can specify any value as a literal such as an integer.
This character sequence will specify the syntax based on the value's type. This will give a literal as a result.
For instance
int month = 10;
In the above statement the literal is an integer value i.e 10. The literal is 10 because it directly represents the
integer value.
In Java programming language there are some special type of literals that represent numbers, characters,
strings and boolean values. Lets have a closer look on each of the following.
Number Literals
Number literals is a sequence of digits and a suffix as L. To represent the type as long integer we use
L as a suffix. We can specify the integers either in decimal, hexadecimal or octal format. To indicate a
decimal format put the left most digit as nonzero. Similarly put the characters as ox to the left of at least one
hexadecimal digit to indicate hexadecimal format. Also we can indicate the octal format by a zero digit
followed by the digits 0 to 7.
659L Decimal integer literal of type long integer
0x4a Hexadecimal integer literal of type integer
057L Octal integer literal of type long integer
Character Literals
We can specify a character literal as a single printable character in a pair of single quote characters
such as 'a', '#', and '3'. You must be knowing about the ASCII character set. The ASCII character set includes
128 characters including letters, numerals, punctuations etc. There are few character literals which are not
readily printable through a keyboard. The table below shows the codes that can represent these special
characters. The letter d such as in the octal, hex etc represents a number.
Escape Meaning
\n New line
\t Tab

Page 6 of 24
Page 7 of 24

\b Backspace
\r Carriage return
\f Formfeed
\\ Backslash
\' Single quotation mark
\" Double quotation mark
\d Octal
\xd Hexadecimal
\ud Unicode character

It is very interesting to know that if we want to specify a single quote, a backslash, or a nonprintable
character as a character literal use an escape sequence. An escape sequence uses a special syntax to
represents a character. The syntax begins with a single backslash character.
Lets see the table below in which the character literals use Unicode escape sequence to represent printable
and nonprintable characters both.
'u0041' Capital letter A
'\u0030' Digit 0
'\u0022' Double quote "
'\u003b' Punctuation ;
'\u0020' Space
'\u0009' Horizontal Tab

Boolean Literals
The values true and false are also treated as literals in Java programming. When we assign a value to
a boolean variable, we can only use these two values. Unlike C, we can't presume that the value of 1 is
equivalent to true and 0 is equivalent to false in Java. We have to use the values true and false to represent a
Boolean value. Like
boolean chosen = true;
Remember that the literal true is not represented by the quotation marks around it. The Java compiler will
take it as a string of characters, if its in quotation marks.
Floating-point literals
Floating-point numbers are like real numbers in mathematics, for example, 4.13179, -0.000001. Java
has two kinds of floating-point numbers: float and double. The default type when you write a floating-point
literal is double.
Type Size Range Precision
name bytes bits approximate in decimal digits
float 4 32 +/- 3.4 * 10386-7
double 8 64 +/- 1.8 * 1030815

A floating-point literal can be denoted as a decimal point, a fraction part, an exponent (represented by E or
e) and as an integer. We also add a suffix to the floating point literal as D, d, F or f. The type of a floating-
point literal defaults to double-precision floating-point.
The following floating-point literals represent double-precision floating-point and floating-point values.
6.5E+32 (or 6.5E32) Double-precision floating-point literal
7D Double-precision floating-point literal
.01f Floating-point literal

String Literals
The string of characters is represented as String literals in Java. In Java a string is not a basic data
type, rather it is an object. These strings are not stored in arrays as in C language. There are few methods
provided in Java to combine strings, modify strings and to know whether to strings have the same value.
We represent string literals as
String myString = "How are you?";

Page 7 of 24
Page 8 of 24

The above example shows how to represent a string. It consists of a series of characters inside double
quotation marks.
Lets see some more examples of string literals:

"" // the empty string


"\"" // a string containing "
"This is a string" // a string containing 16 characters
"This is a " + // actually a string-valued constant expression,
"two-line string" // formed from two string literals

Strings can include the character escape codes as well, as shown here:
String example = "Your Name, \"Sumit\"";
System.out.println("Thankingyou,\nRichards\n");

Null Literals
The final literal that we can use in Java programming is a Null literal. We specify the Null literal in the
source code as 'null'. To reduce the number of references to an object, use null literal. The type of the null
literal is always null. We typically assign null literals to object reference variables. For instance
s = null;
An this example an object is referenced by s. We reduce the number of references to an object by assigning
null to s. Now, as in this example the object is no longer referenced so it will be available for the garbage
collection i.e. the compiler will destroy it and the free memory will be allocated to the other object. Well, we
will later learn about garbage collection.

Identifiers

Identifiers are the names of variables, methods, classes, packages and interfaces. Unlike literals they are not
the things themselves, just ways of referring to them. In the HelloWorld
program, HelloWorld, String, args, main and println are identifiers.

Identifiers must be composed of letters, numbers, the underscore _.

You cannot begin a variable name with a number. It is important to note that all variable names are case-
sensitive. MyVariable is not the same as myVariable. There is no limit to the length of a Java variable name.
The following are legal variable names:
 MyVariable
 myvariable
 MYVARIABLE
 x
 This_is_an_insanely_long_variable_name

The following are not legal variable names:


 My Variable // Contains a space
 9pins // Begins with a digit
 a+c // The plus sign is not an alphanumeric character
 testing1-2-3 // The hyphen is not an alphanumeric character
 O'Reilly // Apostrophe is not an alphanumeric character
 OReilly_&_Associates // ampersand is not an alphanumeric character

Keywords
Keywords are identifiers like public, static and class that have a special meaning inside Java source
code and outside of comments and Strings. Four keywords are used in Hello
World, public, static, void and class. Keywords are reserved for their intended use and cannot be used by the
programmer for variable or method names. There are about 50 - 55 reserved keywords in Java.

Page 8 of 24
Page 9 of 24

Operators
Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the
following groups −
Arithmetic Operators
Relational Operators
Bitwise Operators
Logical Operators
Assignment Operators
Ternary Operators

The Arithmetic Operators


Arithmetic operators are used in mathematical expressions in the same way that they are used in algebra.
The following table lists the arithmetic operators −
Assume integer variable A holds 10 and variable B holds 20, then −
Show Examples
Operator Description Example
Adds values on either side of the
+ (Addition) A + B will give 30
operator.
Subtracts right-hand operand from left-
- (Subtraction) A - B will give -10
hand operand.
Multiplies values on either side of the
* (Multiplication) A * B will give 200
operator.
Divides left-hand operand by right-hand
/ (Division) B / A will give 2
operand.
Divides left-hand operand by right-hand
% (Modulus) B % A will give 0
operand and returns remainder.
++ (Increment) Increases the value of operand by 1. B++ gives 21
-- (Decrement) Decreases the value of operand by 1. B-- gives 19

The Relational Operators


There are following relational operators supported by Java language.
Assume variable A holds 10 and variable B holds 20, then −
Show Examples
Operator Description Example
Checks if the values of two operands are equal or
== (equal to) (A == B) is not true.
not, if yes then condition becomes true.
Checks if the values of two operands are equal or
!= (not equal to) not, if values are not equal then condition (A != B) is true.
becomes true.
Checks if the value of left operand is greater than
> (greater than) the value of right operand, if yes then condition (A > B) is not true.
becomes true.
Checks if the value of left operand is less than the
< (less than) value of right operand, if yes then condition (A < B) is true.
becomes true.
Checks if the value of left operand is greater than
>= (greater than or equal
or equal to the value of right operand, if yes then (A >= B) is not true.
to)
condition becomes true.
Checks if the value of left operand is less than or
<= (less than or equal to) equal to the value of right operand, if yes then (A <= B) is true.
condition becomes true.

Page 9 of 24
Page 10 of 24

The Bitwise Operators


Java defines several bitwise operators, which can be applied to the integer types, long, int, short, char, and
byte.
Bitwise operator works on bits and performs bit-by-bit operation. Assume if a = 60 and b = 13; now in binary
format they will be as follows −
a = 0011 1100
b = 0000 1101
-----------------
a&b = 0000 1100
a|b = 0011 1101
a^b = 0011 0001
~a = 1100 0011
The following table lists the bitwise operators −
Assume integer variable A holds 60 and variable B holds 13 then −
Show Examples
Operator Description Example
Binary AND Operator copies a bit to the result if (A & B) will give 12 which is
& (bitwise and)
it exists in both operands. 0000 1100
Binary OR Operator copies a bit if it exists in (A | B) will give 61 which is
| (bitwise or)
either operand. 0011 1101
Binary XOR Operator copies the bit if it is set in (A ^ B) will give 49 which is
^ (bitwise XOR)
one operand but not both. 0011 0001
(~A ) will give -61 which is 1100
Binary Ones Complement Operator is unary and
~ (bitwise compliment) 0011 in 2's complement form
has the effect of 'flipping' bits.
due to a signed binary number.
Binary Left Shift Operator. The left operands
A << 2 will give 240 which is
<< (left shift) value is moved left by the number of bits
1111 0000
specified by the right operand.
Binary Right Shift Operator. The left operands
A >> 2 will give 15 which is
>> (right shift) value is moved right by the number of bits
1111
specified by the right operand.
Shift right zero fill operator. The left operands
value is moved right by the number of bits A >>>2 will give 15 which is
>>> (zero fill right shift)
specified by the right operand and shifted 0000 1111
values are filled up with zeros.

The Logical Operators


The following table lists the logical operators −
Assume Boolean variables A holds true and variable B holds false, then −
Show Examples
Operator Description Example
Called Logical AND operator. If both the operands are
&& (logical and) (A && B) is false
non-zero, then the condition becomes true.
Called Logical OR Operator. If any of the two operands
|| (logical or) (A || B) is true
are non-zero, then the condition becomes true.
Called Logical NOT Operator. Use to reverses the logical
! (logical not) state of its operand. If a condition is true then Logical !(A && B) is true
NOT operator will make false.

The Assignment Operators


Following are the assignment operators supported by Java language −

Page 10 of 24
Page 11 of 24

Show Examples
Operator Description Example
Simple assignment operator. Assigns values from
= C = A + B will assign value of A + B into C
right side operands to left side operand.
Add AND assignment operator. It adds right operand
+= to the left operand and assign the result to left C += A is equivalent to C = C + A
operand.
Subtract AND assignment operator. It subtracts right
-= operand from the left operand and assign the result C -= A is equivalent to C = C – A
to left operand.
Multiply AND assignment operator. It multiplies right
*= operand with the left operand and assign the result C *= A is equivalent to C = C * A
to left operand.
Divide AND assignment operator. It divides left
/= operand with the right operand and assign the result C /= A is equivalent to C = C / A
to left operand.
Modulus AND assignment operator. It takes modulus
%= using two operands and assign the result to left C %= A is equivalent to C = C % A
operand.
<<= Left shift AND assignment operator. C <<= 2 is same as C = C << 2
>>= Right shift AND assignment operator. C >>= 2 is same as C = C >> 2
&= Bitwise AND assignment operator. C &= 2 is same as C = C & 2
^= bitwise exclusive OR and assignment operator. C ^= 2 is same as C = C ^ 2
|= bitwise inclusive OR and assignment operator. C |= 2 is same as C = C | 2

Conditional Operator ( ? : )
Conditional operator is also known as the ternary operator. This operator consists of three operands
and is used to evaluate Boolean expressions. The goal of the operator is to decide, which value should be
assigned to the variable. The operator is written as −
variable x = (expression) ? value if true : value if false
Example
public class Test {
public static void main(String args[]) {
int a, b;
a = 10;
b = (a == 1) ? 20: 30;
System.out.println( "Value of b is : " + b );
b = (a == 10) ? 20: 30;
System.out.println( "Value of b is : " + b );
}
}

This will produce the following result −


Output
Value of b is : 30
Value of b is : 20

Java Operator Precedence

Type Operators

Page 11 of 24
Page 12 of 24

Unary ! ~ ++ -- + - () new

Arithmetic */%+-

Shift << >> >>>

Comparison < <= > >= instanceof == !=

Bitwise &^|

Short- && ||
circuit

Ternary ?:

Assignment = "op=" (for example, *=, +=,


%=, ^=)

Type Casting in Java


Type casting is used to convert an object or variable of one type into another.
Syntax
dataType variableName = (dataType) variableToConvert;
There are two casting directions: narrowing (larger to smaller type) and widening (smaller to larger type).
Widening can be done automatically (for example, int to double), but narrowing must be done explicitly (like
double to int).

Control Statements
Java if (if-then) Statement
The syntax of if-then statement in Java is:
if (expression) {
// statements
}
Here expression is a boolean expression (returns either true or false). If the expression is evaluated to true,
statement(s) inside the body of if (statements inside parenthesis) are executed. If the expression is
evaluated to false, statement(s) inside the body of if are skipped from execution.
Example 1: Java if Statement
class IfStatement {
public static void main(String[] args) {

int number = 10;

if (number > 0) {

Page 12 of 24
Page 13 of 24

System.out.println("Number is positive.");
}
System.out.println("This statement is always executed.");
}
}
When you run the program, the output will be:

Number is positive.
This statement is always executed.
When number is 10, the test expression number > 0 is evaluated to true. Hence, codes inside the body of if
statements are executed.
Now, change the value of number to a negative integer. Let's say -5. The output in this case will be:

This statement is always executed.


When number is -5, the test expression number > 0 is evaluated to false. Hence, Java compiler skips the
execution of body of if statement.

Java if...else (if-then-else) Statement


The if statement executes a certain section of code if the test expression is evaluated to true. The if
statement can have optional else statement. Codes inside the body of else statement are executed if the test
expression is false.
The syntax of if-then-else statement is:
if (expression) {
// codes
}
else {
// some other code
}
Example 2: Java if else Statement
class IfElse {
public static void main(String[] args) {
int number = 10;
if (number > 0) {
System.out.println("Number is positive.");
}
else {
System.out.println("Number is not positive.");
}
System.out.println("This statement is always executed.");
}
}

When you run the program, the output will be:


Number is positive.
This statement is always executed.
When number is 10, the test expression number > 0 is evaluated to true. In this case, codes inside the body
of if are executed, and codes inside the body of else statements are skipped from execution.
Now, change the value of number to a negative number. Let's say -5. The output in this case will be:
Number is not positive.
This statement is always executed.
When number is -5, the test expression number > 0 is evaluated to false. In this case, codes inside the body
of else are executed, and codes inside the body of if statements are skipped from execution.
In Java, it's possible to execute one block of code among many. For that, you can use if..else...if ladder.

Page 13 of 24
Page 14 of 24

if (expression1)
{
// codes
}
else if(expression2)
{
// codes
}
else if (expression3)
{
// codes
}
.
.
else
{
// codes
}
The if statements are executed from the top towards the bottom. As soon as the test expression is true,
codes inside the body of that if statement is executed. Then, the control of program jumps outside if-else-if
ladder.

If all test expressions are false, codes inside the body of else is executed.

Example 3: Java if..else..if Statement


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

int number = 0;

if (number > 0) {
System.out.println("Number is positive.");
}
else if (number < 0) {
System.out.println("Number is negative.");
}
else {
System.out.println("Number is 0.");
}
}
}
When you run the program, the output will be:

Number is 0.
When number is 0, both test expression number > 0 and number < 0 is evaluated to false. Hence, the
statement inside the body of else is executed.

The above program checks whether number is positive, negative or 0.

It's possible to have if..else statements inside a if..else statement in Java. It's called nested if...else
statement. Here's a program to find largest of 3 numbers:

Page 14 of 24
Page 15 of 24

Example 4: Nested if...else Statement


class Number{
public static void main(String[] args) {
double n1 = -1.0, n2 = 4.5, n3 = -5.3, largestNumber;
if (n1 >= n2) {
if (n1 >= n3) {
largestNumber = n1;
}
else {
largestNumber = n3;
}
}
else {
if (n2 >= n3) {
largestNumber = n2;
}
else {
largestNumber = n3;
}
}
System.out.println("Largest number is " + largestNumber);
}
}
When you run the program, the output will be:
Largest number is 4.5
Note: In above programs, we have assigned value of variables ourselves to make this easier. However, if real
world applications these values may come from user input data, log files, form submission etc.

Switch statement
Switch case statement is used when we have number of options (or choices) and we may need to perform a
different task for each choice.
The syntax of Switch case statement looks like this –
switch (variable or an integer expression)
{
case constant:
//statements
;
case constant:
// statements
;
default:
// statements
;
}
Switch Case statement is mostly used with break statement even though it is optional.
public class SwitchCaseExample1 {
public static void main(String args[]){
int num=2;
switch(num+2)
{
case 1:
System.out.println("Case1: Value is: "+num);
case 2:

Page 15 of 24
Page 16 of 24

System.out.println("Case2: Value is: "+num);


case 3:
System.out.println("Case3: Value is: "+num);
default:
System.out.println("Default: Value is: "+num);
}
}
}
output
Default: Value is: 2

In switch I gave an expression, you can give variable also. I gave num+2, where num value is 2 and after
addition the expression resulted 4. Since there is no case defined with value 4 the default case got executed.
public class SwitchCaseExample2 {
public static void main(String args[]){
int i=2;
switch(i)
{
case 1:
System.out.println("Case1 ");
case 2:
System.out.println("Case2 ");
case 3:
System.out.println("Case3 ");
default:
System.out.println("Default ");
}
}
}
Output:
Case2
Case3
Default

Example with break statement


public class SwitchCaseExample2 {
public static void main(String args[]){
int i=2;
switch(i) {
case 1:
System.out.println("Case1 ");
break;
case 2:
System.out.println("Case2 ");
break;
case 3:
System.out.println("Case3 ");
break;
default:
System.out.println("Default ");
}
}
}

Page 16 of 24
Page 17 of 24

Output:
Case2
Now you can see that only case 2 had been executed, rest of the cases were ignored.
Points on switch
 Case doesn’t always need to have order 1, 2, 3 and so on. It can have any integer value after case
keyword. Also, case doesn’t need to be in an ascending order always, you can specify them in any order
based on the requirement.
 You can also use characters in switch case.
 The expression given inside switch should result in a constant value otherwise it would not be valid.
For example:
Valid expressions for switch:
 switch(1+2+23)
 switch(1*2+3%4)
Invalid switch expressions:
 switch(ab+cd)
 switch(a+b+c)
 Nesting of switch statements are allowed, which means you can have switch statements inside another
switch. However nested switch statements should be avoided as it makes program more complex and
less readable.
 No ranges. It doesn't allow ranges, eg case 90-100.
 Error-prone. It is error-prone and a common source of bugs - forgetting break or default silently ignores
errors. Some languages have eliminated these dangerous situations.
Where to use switch?
The ability of switch to choose between many sections of code seems to make it more powerful than if.
However, selecting sections of code depending on specific integer values turns out not to be very common. If
you are handling specific coded values (eg, the number of the button that was clicked in a JOptionPane), or
processing characters (whose codes are treated like numbers), you may find it useful.

LOOPS
In Java we have three types of basic loops: for, while and do-while. Loops are used to execute a set of
statements repeatedly until a particular condition is satisfied.

While Loop
Syntax of while loop
while(condition)
{
statement(s);
}
In while loop, condition is evaluated first and if it returns true then the statements inside while loop execute.
When condition returns false, the control comes out of loop and jumps to the next statement after while
loop.
Note: The important point to note when using while loop is that we need to use increment or decrement
statement inside while loop so that the loop variable gets changed on each iteration, and at some point
condition returns false. This way we can end the execution of while loop otherwise the loop would execute
indefinitely.

class WhileLoopExample {
public static void main(String args[]){
int i=10;
while(i>1){
System.out.print(i+” “);
i--;

Page 17 of 24
Page 18 of 24

}
}
}
Output:
10 9 8 7 6 5 4 3 2

Infinite while loop


class WhileLoopExample2 {
public static void main(String args[]){
int i=10;
while(i>1)
{
System.out.println(i);
i++;
}
}
}
This loop would never end, its an infinite while loop. This is because condition is i>1 which would always be
true as we are incrementing the value of i inside while loop.
Here is another example of infinite while loop:
while (true){
statement(s);
}

Do while loop
do-while loop is similar to while loop, however there is a difference between them: In while loop, condition
is evaluated before the execution of loop’s body but in do-while loop condition is evaluated after the
execution of loop’s body.
Syntax of do-while loop:
do
{
statement(s);
} while(condition);
First, the statements inside loop execute and then the condition gets evaluated, if the condition returns true
then the control gets transferred to the “do” else it jumps to the next statement after do-while.
class DoWhileLoopExample {
public static void main(String args[]){
int i=10;
do{
System.out.print(i+ “ “);
i--;
}while(i>1);
}
}
Output:
10 9 8 7 6 5 4 3 2

Page 18 of 24
Page 19 of 24

For Loop
The for statement is similar to the while statement, but it is often easier to use if you are counting or
indexing because it combines three elements of many loops: initialization, testing, and incrementing.
General Form
The for and equivalent while statements have these forms.
for (init-stmt; condition; next-stmt) { init-stmt;
body while (condition) {
} body
next-stmt;
}
There are three clauses in the for statement.
 The init-stmt statement is done before the loop is started, usually to initialize an iteration variable.
 The condition expression is tested before each time the loop is done. The loop isn't executed if the
boolean expression is false (the same as the while loop).
 The next-stmt statement is done after the body is executed. It typically increments an iteration
variable.
Example - Printing a table of squares
for (int number = 1; number <= 12; number++) {
System.out.println(number + " squared is " + (number * number));
}

For-each Loop
This for statement is called the enhanced for or foreach (because it is called this in other programming
languages). It is also called the for-in loop.
Series of values. The for-each loop is used to access each successive value in a collection of values.
Arrays and Collections. It's commonly used to iterate over an array or a Collections class (eg, ArrayList).

General Form
The for-each and equivalent for statements have these forms. The two basic equivalent forms are given,
depending one whether it is an array that is being traversed. In this case an extra variable is required, an
index for the array.
//... Foreach loop over all elements in arr. //... For loop using index.

Page 19 of 24
Page 20 of 24

for (type var : arr) { for (int i = 0; i < arr.length; i++) {


body-of-loop type var = arr[i];
} body-of-loop
}

double[] ar = {1.2, 3.0, 0.8};


int sum = 0;
for (double d : ar) { // d gets successively each value in ar.
sum += d;
}

break Statement
The break statement is usually used in following two scenarios:
a) Use break statement to come out of the loop instantly. Whenever compiler finds a break statement inside
a loop, the control directly comes out of loop and passed to the statement following the loop. It is used
along with if statement, whenever used inside loop.
b) It is also used in switch case control. Generally all cases in switch case are followed by a break statement
so that whenever the program control jumps to a case, it doesn’t execute subsequent cases (see the
example below). Whenever it is encountered in switch-case block, the control comes out of the switch-case
body.

Syntax of break statement:


break;
Example – Use of break in a while loop

In the example below, we have a while loop running from o to 100 but since we have a break statement that
only occurs when the loop value reaches 2, the loop gets terminated and the control gets passed to the next
statement in program after the loop body.

public class BreakExample1 {


public static void main(String args[]){
int num =0;
while(num<=100) {
System.out.println("Value of variable is: "+num);
if (num==2) {
break; }
num++;
}
System.out.println("Out of while-loop");
}
}
Output:
Value of variable is: 0
Value of variable is: 1
Value of variable is: 2
Out of while-loop

continue Statement
Continue statement is mostly used inside loops. Whenever it is encountered inside a loop, control directly
jumps to the beginning of the loop for next iteration, skipping the execution of statements inside loop’s body
for the current iteration.
Syntax:

Page 20 of 24
Page 21 of 24

continue;

Example: continue statement inside for loop


public class ContinueExample {
public static void main(String args[]){
for (int j=0; j<=6; j++) {
if (j==4) {
continue; }
System.out.print(j+" ");
}
}
}
Output:
012356

As you may have noticed, the value 4 is missing in the output, why? because when the value of variable j is 4,
the program encountered a continue statement, which makes it to jump at the beginning of for loop for next
iteration, skipping the statements for current iteration (that’s the reason println didn’t execute when the
value of j was 4).

Arrays
Array is a collection of similar type of elements that have contiguous memory location. Array is an object the
contains elements of similar data type. It is a data structure where we store similar elements. We can store
only fixed elements in an array.

Array is index based, first element of the array is stored at 0 index.

Creation of arrays:
Arrays are data structures that can store large amount of information of the same data type grouped
together and known by a common name. Each member is called an element of the array.
Arrays are capable of storing primitive data types as well as objects. The elements of the array can be
accessed by its index value that starts from 0. Once array is declared, its size cannot be altered dynamically.

Arrays can be :-
a) declared and later assigned or
b) initialized.
// declaration of an array
int subject[ ] = new int[ 10 ] ;
// if not assigned, default 0 is assigned for int element
System.out.println( subject[ 1 ] ) ; // output is 0
// assigning a value to an element
subject[ 1 ] = 45 ;
// now, prints 45
System.out.println( subject[ 1 ] ) ;

Advantages of Array

Page 21 of 24
Page 22 of 24

1. Code Optimization: It makes the code optimized, we can retrive or sort the data easily.
2. Random access: We can get any data located at any index position.

Disadvantage of Array
Size Limit: We can store only fixed size of elements in the array. It doesn't grow its size at runtime. To solve
this problem, collection framework is used in java.
This code declares and initializes an array.
int[] a = {1, 2, 4, 8, 16};
How arrays are stored and accessed in memeory
Arrays are often represented with diagrams that represent their memory use. The diagrams below are
typical ways to represent the memory used by an array.
Each box represents the amount of memory needed to hold one array element. For ints this is 4 bytes. The
array variable, a, is a reference (ie, memory address in the heap) of the block of memory that holds the
actual array elements. References are often represented by a black disk with an arrow pointing to the data
they reference. Most often array diagrams are written vertically, but sometimes the cells are arranged
horizontally, especially for arrays of characters. Of course in the actual physical memory there is no such idea
as vertical or horizontal.

How to get the size of array?


a.length gives the size of the Array.
Types of Array
1-, 2-, and higher-dimensional arrays
Java, as with most languages, supports multi-dimensional arrays - 1-dimensional, 2-dimensional, 3-
dimensional and so on.
The below example initializes the array elements to 1,2,3,4,5,6, reverse the array and print the array.
public class ArrayInitializing{
public static void main(String args[]){
int b[] = new int[6];
for(int i=0;i<b.length;i++){
b[i]=i+1;
}
for(int i=0;i<b.length;i++){
System.out.println(b[i]);
}
int left=0, right=b.length-1;
for (; left<right; left++, right--) {
// exchange the first and last
int temp = b[left];
b[left] = b[right];
b[right] = temp;
}
System.out.println("after reversing the array");
for(int i=0;i<b.length;i++)

Page 22 of 24
Page 23 of 24

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

In practice most arrays are one-dimensional, and two-dimensional (rows and columns) are also quite
common. Two-dimensional arrays are used whenever the model data is best represented with rows and
columns, or has two varying aspects (eg, gender and age, weight and height, ...). It's also the idea, although
not the implementation, of graphics that specifies a two (or three) dimensional position with an x and y (and
z) coordinate.

Visualizing two-dimensional arrays


2-dimensional arrays are usually represented with a row-column "spreadsheet" style. Assume we have an
array, a, with two rows and four columns.
int[][] a = new int[2][3]; // Two rows and three columns.
Two-dimensional arrays are usually visualized as a matrix, with rows
a[0][ a[0][ a[0][ a[0][ and columns. This diagram shows the array a with its corresponding
0] 1] 2] 3] subscripts.
a[1][ a[1][ a[1][ a[1][ Style: Use constants for the array sizes
0] 1] 2] 3] It's very useful to define constants for the number of rows and columns.
static final int ROWS = 2;
static final int COLS = 3;
...
int[][] board = new int[ROWS][COLS];
Many row and column indexes (indices is the traditional English plural) have a meaning, and aren't just
simply arbitrary numbers. The following example might be used to represent the number of accidents on by
day of the month and the hour of the day.
static final int DAYS = 31;
static final int HOURS = 24;
...
int[][] accidents = new int[DAYS][HOURS];
Initial values
You can assign initial values to an array when in a manner very similar to one-dimensional arrays, but with
an extra level of braces. The dimension sizes are computed by the compiler from the number of values. This
would allocated a 3x3 board
int[][] board = new int[][] {{1,0,0},{0,1,0},{1,2,1}};
Use nested for loops to process 2-dimensional arrays
Two-dimensional arrays are almost always processed with nested for loops.
static final int ROWS = 2;
static final int COLS = 4;
...
int[][] a2 = new int[ROWS][COLS];
...
//... Print array in rectangular form
for (int i =0; i < ROWS; i++) {
for (int j = 0; j < COLS; j++) {
System.out.print(" " + a2[i][j]);
}
System.out.println("");
}
Programming problems
a. For the accidents array above write code that does the following:
i. Display the total number of accidents? Hint: Use nested loops to add all elements.

Page 23 of 24
Page 24 of 24

ii. At what hour do the most accidents occur? Hint: Use on outer loop over hours, where the
inner loop goes down the column and adds all the accidents for that hour. Keep max as you
would for a one-dimensional array.
iii. How would you declare a three-dimensional array that had an additional dimension for the
12 months?

Page 24 of 24

You might also like