Académique Documents
Professionnel Documents
Culture Documents
com
UNIT 1
INTRODUCTION TO JAVA
1.1 Basics
Java is both a programming language and a platform
Fig: Through the JVM, the same application is capable of running on multiple platforms
latest IEEE Final year projects for B.E (CSE/ISE) sudents by Mr. Ashok Kumar K
Contact 9742013378 or 9742024066 for registering your name or visit www.vtuprojects.com
www.vtuprojects.com
UNIT 1
INTRODUCTION TO JAVA
Java as a Platform
A platform is the hardware or software environment in which a program runs. The Java platform is a
software-only platform that runs on top of other hardware-based platforms like Windows, Mac, etc.
The java platform has two components:
Observations
Upon installing Java in any machine, you should be getting these two entities
Java Development Kit (JDK)
Java Runtime Environment (JRE)
Java Development Kit (JDK)
JDK is a bundle of ready-made software components that provide many useful
capabilities. It is grouped into libraries of related classes and interfaces; these libraries
are known as packages. It constitutes the Java API component in the Java Platform.
Java Runtime Environment (JRE)
JRE is an implementation of Java Virtual Machine which actually runs the program.
Typically, each JDK contains one (or more) JRE's along with the various development
tools like the Java source compilers, bundling and deployment tools, debuggers,
development libraries, etc.
of
Java
at
its
official
website
This site provides java distribution for Windows, Mac OS, Linux, and Solaris. Download and
install latest version of Java on whichever the platform you are comfortable with.
Installation procedure is pretty simple. Hopefully you don't encounter any blockage here.
Give a try!
After installing Java in your machine, please set the JAVA_HOME, PATH and
CLASSPATH environment variables.
latest IEEE Final year projects for B.E (CSE/ISE) sudents by Mr. Ashok Kumar K
Contact 9742013378 or 9742024066 for registering your name or visit www.vtuprojects.com
www.vtuprojects.com
UNIT 1
INTRODUCTION TO JAVA
The JAVA_HOME is the variable that your operating system uses to locate the
installation path of java.
The PATH is the variable that your operating system uses to locate needed
executables from the command line or Terminal window.
The CLASSPATH variable is one way to tell applications, including the JDK tools, where to
look for user classes.
Object oriented
Java is purely an Object Oriented Programming language i.e., all the code of the Java language is
written into the classes and objects.
Distributed
Java is designed as distributed language because, for creating applications on network it has the
ability to share the data and programs over the LAN (local area network). Java apps can open the
remote objects on internet as easily they can do in local systems.
Multithreaded
A Java program can be divided into multiple threads assigning different tasks for different threads
and have all the threads executing in parallel. Example for multithreaded application is a browser
(multiple tabs can be opened; here each tab is a thread).
Dynamic
The Java Virtual Machine (JVM) maintains a lot of runtime information about the program and the
objects in the program. Libraries are dynamically linked during runtime. So, even if you make
dynamic changes to pieces of code, the program is not affected.
Architecture neutral
This means that the programs written on one platform can run on any other platform without having
to rewrite or recompile them. In other words, it follows 'Write-once-run-anywhere' approach.
Java programs are compiled into bytecode format which does not depend on any machine
architecture but can be easily translated into a specific machine by a Java Virtual Machine (JVM) for
that machine.
Portable
A C/C++ program may run slightly differently on different hardware platforms depending on how
these platforms implement arithmetic operations.
In Java, it has been simplified. Unlike C/C++, in Java the size of the primitive data types are machine
independent. For example, an int in Java is always a 32-bit integer, and float is always a 32-bit IEEE
754 floating point number. These consistencies make Java programs portable among different
platforms such as Windows, UNIX and Mac.
High performance
Java programs are compiled to portable intermediate form known as bytecodes, rather than to native
machine level instructions and JVM executes the bytecodes on any machine on which it is installed.
This architecture means that Java programs are faster than programs/scripts written in purely
interpreted languages but slower than C and C++ programs that compiled to native machine
languages.
latest IEEE Final year projects for B.E (CSE/ISE) sudents by Mr. Ashok Kumar K
Contact 9742013378 or 9742024066 for registering your name or visit www.vtuprojects.com
www.vtuprojects.com
UNIT 1
INTRODUCTION TO JAVA
Robust
A Program or an application is said to be robust (reliable) when it is able to give some response in
any kind of context. Javas features help to make the programs robust. Some of those features are:
type checking, exception handling, etc
Secured
Java provides data security through encapsulation. When we transfer the code from one machine to
another, the JVM first check the code to check if it is affected by virus/threats or not. If the code is
affected then it will never execute that code in that machine. Also we can write applets in Java
which provides security. An applet is a small program which can be downloaded from a server using
a browser. There is no need to worry about applets accessing the system resources which may
compromise security.
Class
A class is a blueprint or prototype from which objects are created. It's just a template for an object. It
describes an object. For Example, a class just describes how a Dog looks like. (Say, a dog has 4
legs, it barks, it eats etc.), but an Object refers to a real Dog.
Inheritance
Generally, a process by which a child class acquires the state and behavior of its parent class is
referred to as Inheritance. For example, Hyundai is a parent class whose properties are inherited by
the classes named iTen, iTwenty, Verna, Getz etc.
Inheritance can also be referred to the concept of Generalization, which is the process of extracting
common characteristics (states and behavior) from two or more classes, and combining them into a
generalized super class.
Polymorphism
The word "Polymorphism" refers to the ability to take more than one form. In terms of programming,
the polymorphism refers to the process in which a member function of a class behaves differently for
different inputs. For example, a function move() in the game of chess behaves differently for different
pawns (for instance, it allows only sideways movement for camel and straight movement for
elephant).
Encapsulation
Encapsulation refers to the process of binding the data members and the functions (that accesses
these data) together. A class is an example for encapsulation. Through encapsulation a class can
hide the internal details of how an object does something. Encapsulation helps to change the internal
implementation of the object without affecting the overall functionality of the system. Encapsulation
provides abstraction (Information hiding).
Interface
An interface is a description of the actions that an object can do. For example when you flip a light
switch, the light goes on, you don't care how, just that it does. In Object Oriented Programming, an
Interface is a description of all functions that an object must have. For example, anything that "ACTS
LIKE" a light, should have a turn_on() method and a turn_off() method. So these two functions will be
included within an interface. The purpose of interfaces is to allow the computer to enforce these
properties and to know that an object of TYPE T must have functions called X,Y,Z, etc.
latest IEEE Final year projects for B.E (CSE/ISE) sudents by Mr. Ashok Kumar K
Contact 9742013378 or 9742024066 for registering your name or visit www.vtuprojects.com
www.vtuprojects.com
UNIT 1
INTRODUCTION TO JAVA
Package
A package is a namespace that organizes a set of related classes and interfaces. Conceptually you
can think of packages as being similar to different folders on your computer. You arrange all audio
songs under a specific directory, and all video songs under another directory, etc. Because software
written in the Java programming language can be composed of hundreds or thousands of individual
classes, it makes sense to keep things organized by placing related classes and interfaces into
packages.
Steps
Step1: Open a text editor (notepad, edit plus, etc) and write the source code.
class Hello {
public static void main (String arg[]) {
System.out.println("Hello World. Welcome to the world of Java.");
}
}
Step 2: Save this file as Hello.java in your local hard disk (where ever you wish)
latest IEEE Final year projects for B.E (CSE/ISE) sudents by Mr. Ashok Kumar K
Contact 9742013378 or 9742024066 for registering your name or visit www.vtuprojects.com
www.vtuprojects.com
UNIT 1
INTRODUCTION TO JAVA
Step 3: Open a command window and change the directory to the one where you just saved your
Hello.java source file.
Step 4: Compile the source file using java compiler. i.e, by issuing a command as follows:
javac Hello.java
If there are any compilation errors in your program, this command will not successfully executes,
instead it will throw an error saying what went wrong. If your program is completely error free, the
compilation process will be successful. You can observe that, the output of the compilation process is
a .class file which is called the java "byte code".
Step 5: Execute the .class file by giving it as an input to JVM through following command.
java Hello
latest IEEE Final year projects for B.E (CSE/ISE) sudents by Mr. Ashok Kumar K
Contact 9742013378 or 9742024066 for registering your name or visit www.vtuprojects.com
www.vtuprojects.com
UNIT 1
INTRODUCTION TO JAVA
The program executes and the output can be seen in the console. Yes, you are done with your first
Java program successfully. Congrats :)
Observations
class Hello {
public static void main (String arg[]) {
System.out.println("Hello World. Welcome to the world of Java.");
}
}
latest IEEE Final year projects for B.E (CSE/ISE) sudents by Mr. Ashok Kumar K
Contact 9742013378 or 9742024066 for registering your name or visit www.vtuprojects.com
www.vtuprojects.com
UNIT 1
INTRODUCTION TO JAVA
The keyword 'void' indicates that a function returns nothing. In Java, you can't
return anything from the main function, so always the main function will be
having a return type of void.
The Keyword 'main' is the name of the function and at this point of time you
can think this as the entry point for a Java application.
String arg[] within the main function parenthesis is used to hold command line
arguments provided during the program execution. Let's see an example
program at later point of time.
Comments in Java are of two types: Single line comments and Multiline comments.
Single line comment starts with // followed by the comment string.
Multi line comment starts with /* followed by the comment string and ends with
*/
There can be more than one class within a single .java file. The class that encloses
the main function can be called as Main Class.
A java source file should be having the same name as the class name which
contains the main function. You can't choose the name of your wish like in C/C++.
This is to help the JVM to search for the main function.
In a single .java file where there are more than one classes, only one class can be
marked as 'public' and this class should be the main class. All the other classes
should either be marked as private or default. It enables a more efficient lookup of
source (.java) and compiled (.class) files during compilation (import directives) and
a more efficient class loading during execution.
latest IEEE Final year projects for B.E (CSE/ISE) sudents by Mr. Ashok Kumar K
Contact 9742013378 or 9742024066 for registering your name or visit www.vtuprojects.com
www.vtuprojects.com
UNIT 1
INTRODUCTION TO JAVA
Practice Programs
a.
b.
c.
d.
e.
f.
g.
h.
i.
j.
k.
latest IEEE Final year projects for B.E (CSE/ISE) sudents by Mr. Ashok Kumar K
Contact 9742013378 or 9742024066 for registering your name or visit www.vtuprojects.com
www.vtuprojects.com
UNIT 1
INTRODUCTION TO JAVA
}
class Bank {
int num_of_customers = 0;
String status = "CLOSED";
latest IEEE Final year projects for B.E (CSE/ISE) sudents by Mr. Ashok Kumar K
Contact 9742013378 or 9742024066 for registering your name or visit www.vtuprojects.com
10
www.vtuprojects.com
UNIT 1
INTRODUCTION TO JAVA
11
www.vtuprojects.com
UNIT 1
INTRODUCTION TO JAVA
}
}
latest IEEE Final year projects for B.E (CSE/ISE) sudents by Mr. Ashok Kumar K
Contact 9742013378 or 9742024066 for registering your name or visit www.vtuprojects.com
12
www.vtuprojects.com
UNIT 1
INTRODUCTION TO JAVA
latest IEEE Final year projects for B.E (CSE/ISE) sudents by Mr. Ashok Kumar K
Contact 9742013378 or 9742024066 for registering your name or visit www.vtuprojects.com
13
www.vtuprojects.com
UNIT 1
INTRODUCTION TO JAVA
Write a method named lastDigit that returns the last digit of an integer. For example,
lastDigit(3572) should return 2. It should work for negative numbers as well. For example,
lastDigit(-947) should return 7.
class Seven {
public static void main (String arg[]) {
int n = -7676;
int ld = lastDigit(n);
System.out.println("Last Digit in "+n+" is .... "+ld);
n = 3489;
ld = lastDigit(n);
System.out.println("Last Digit in "+n+" is .... "+ld);
latest IEEE Final year projects for B.E (CSE/ISE) sudents by Mr. Ashok Kumar K
Contact 9742013378 or 9742024066 for registering your name or visit www.vtuprojects.com
14
www.vtuprojects.com
UNIT 1
INTRODUCTION TO JAVA
Write a method named firstDigit that returns the first digit of an integer. For example,
firstDigit(3572) should return 3. It should work for negative numbers as well. For example,
firstDigit(-947) should return 9.
class Eight {
public static void main (String arg[]) {
int n = -7676;
int ld = firstDigit(n);
System.out.println("First Digit in "+n+" is .... "+ld);
n = 3489;
ld = firstDigit(n);
System.out.println("First Digit in "+n+" is .... "+ld);
latest IEEE Final year projects for B.E (CSE/ISE) sudents by Mr. Ashok Kumar K
Contact 9742013378 or 9742024066 for registering your name or visit www.vtuprojects.com
15
www.vtuprojects.com
UNIT 1
INTRODUCTION TO JAVA
Write a recursive function in java to print all natural numbers from 1 up to (n-1)
public class Nine {
public static void main(String args[]) {
int n = 10;
series(n);
}
latest IEEE Final year projects for B.E (CSE/ISE) sudents by Mr. Ashok Kumar K
Contact 9742013378 or 9742024066 for registering your name or visit www.vtuprojects.com
16
www.vtuprojects.com
UNIT 1
INTRODUCTION TO JAVA
Write a program to calculate the average among the elements {4,5,7,8}, using for each in
java. How for each is different from for loop?
public class Twelve
{
public static void main(String args[])
{
int arr[] = {4,5,7,8};
int sum = 0;
for (int ele : arr) {
latest IEEE Final year projects for B.E (CSE/ISE) sudents by Mr. Ashok Kumar K
Contact 9742013378 or 9742024066 for registering your name or visit www.vtuprojects.com
17
www.vtuprojects.com
UNIT 1
INTRODUCTION TO JAVA
Local Variables
Any method in java will store its temporary state in a local variable. A variable which can be
accessed only within its defining block can be called as a local variable for that block. It can't
be accessed anywhere else outside this block. There is no special keyword to designate a
variable as local. A variable by default becomes local if it's been defined within any block
(open brace and closing brace)
Parameters
Parameters are the input variables for a method within a class.
latest IEEE Final year projects for B.E (CSE/ISE) sudents by Mr. Ashok Kumar K
Contact 9742013378 or 9742024066 for registering your name or visit www.vtuprojects.com
18
www.vtuprojects.com
UNIT 1
INTRODUCTION TO JAVA
byte: The byte data type can be useful for saving memory in large arrays, where the
memory savings actually matters
short: 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: 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: 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. As with the
recommendations for byte and short, use a float (instead of double) if you need to save
memory in large arrays of floating point numbers.
double: The double data type is a double-precision 64-bit IEEE 754 floating point. 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.
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).
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.
latest IEEE Final year projects for B.E (CSE/ISE) sudents by Mr. Ashok Kumar K
Contact 9742013378 or 9742024066 for registering your name or visit www.vtuprojects.com
19
www.vtuprojects.com
UNIT 1
INTRODUCTION TO JAVA
Data type
Size
Possible values
byte
8 bits (1 byte)
-128 to +127
short
16 bits (2 bytes)
int
32 bits (4 bytes)
-2147483648 to +2147483647
long
64 bits (8 bytes)
-9223372036854775808 to
+9223372036854775807
float
36 bits (4 bytes)
1.40129846432481707e-45 to
3.40282346638528860e+38
double
64 bits (8 bytes)
4.94065645841246544e-324d to
1.79769313486231570e+308d
char
16 bits (2 bytes)
0 to 65,535
boolean
1 bit
true or false
-32768 to +32767
Array: An array is a special kind of object that contains collection of similar type of
elements. The java array enables the user to store the values of the same type in
contiguous memory allocations. The elements in an array are identified by an integer
index which initially starts from 0 and ends with one less than number of elements
available in the array. All elements of an array must contain the same type of value i.e.
if an array is a type of integer then all the elements must be of integer type. It is a
reference data type because the class named as Array implicitly extends
java.lang.Object.
latest IEEE Final year projects for B.E (CSE/ISE) sudents by Mr. Ashok Kumar K
Contact 9742013378 or 9742024066 for registering your name or visit www.vtuprojects.com
20
www.vtuprojects.com
UNIT 1
INTRODUCTION TO JAVA
There are two different ways of declaring an array as shown below:
datatype[] arr_name = new datatype[arraysize];
Ex: int[] arr = new int[50];
datatype[] arr_name = {element 1, element 2, ................. , element n}
Ex: int[] arr = {5, 10, 15, 20, 25};
Class: The name of a class is treated as a type in a java program, so that you can
declare a variable of an object-type, and a method which can be called using that
object- type variable. Whenever a variable is created, a reference to an object is
also created using the name of a class for its type i.e. that variable can contain
either null or a reference to an object of that class. It is not allowed to contain any
other kind of values. Such type is called reference types in Java. The object
becomes an instance when the memory is allocated to that object using new
keyword.
Ex:
class Box {
int h, w, l;
double getArea() {
}
void setValues (int h, int w, int l) {
}
}
Box b = new Box(); // here b is an object/instance, Box is a class type
Interface: The name of an interface can be used to specify the type of a reference.
A value is not allowed to be assigned to a variable declared using an interface type
until the object implements the specified interface. Hold on here, you will learn
more about interfaces in later chapters.
Default Value
byte
short
int
long
0L
float
0.0f
double
0.0d
char
'\u0000'
null
boolean
false
latest IEEE Final year projects for B.E (CSE/ISE) sudents by Mr. Ashok Kumar K
Contact 9742013378 or 9742024066 for registering your name or visit www.vtuprojects.com
21
www.vtuprojects.com
UNIT 1
INTRODUCTION TO JAVA
1.5.4 Literals
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;
Integer Literal:
An integer literal is of type long if it ends with the letter L or l; otherwise it is of type int.
Please use the upper case letter L because the lower case letter l is hard to distinguish from
the digit 1.
Following example shows the syntax for creating the literals in binary and hexadecimal
number system.
// The number 26, in decimalint decVal = 26;
// The number 26, in hexadecimal
int hexVal = 0x1a;
// The number 26, in binary
int binVal = 0b11010;
Floating-point Literal:
A floating-point literal is of type float if it ends with the letter F or f; otherwise its type is
double and it can optionally end with the letter D or d. 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).
Examples:
double d1 = 123.4;
// same value as d1, but in scientific notation
double d2 = 1.234e2;
float f1 = 123.4f;
latest IEEE Final year projects for B.E (CSE/ISE) sudents by Mr. Ashok Kumar K
Contact 9742013378 or 9742024066 for registering your name or visit www.vtuprojects.com
22
www.vtuprojects.com
UNIT 1
INTRODUCTION TO JAVA
There is 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. null is often used in programs as a
marker to indicate that some object is unavailable.
Finally, there is another 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.
long getArea() {
return l*w*h;
}
latest IEEE Final year projects for B.E (CSE/ISE) sudents by Mr. Ashok Kumar K
Contact 9742013378 or 9742024066 for registering your name or visit www.vtuprojects.com
23
www.vtuprojects.com
UNIT 1
INTRODUCTION TO JAVA
The object creation statement above have three parts:
Declaration: LHS of the above statement constitutes the declaration. It is associated with
variable name and object type.
Instantiation: It is the new keyword in java that creates the object
Initialization: The new operator is followed by a call to a constructor, which initializes the
new object.
Destroying Objects
Java provides a wonderful concept of Garbage Collection which performs automatic
memory management, so you don't need to delete the object that you've created. JVM does
it for you automatically through Garbage Collection. We will see the concept of Garbage
Collection in deep at later chapters.
latest IEEE Final year projects for B.E (CSE/ISE) sudents by Mr. Ashok Kumar K
Contact 9742013378 or 9742024066 for registering your name or visit www.vtuprojects.com
24
www.vtuprojects.com
UNIT 1
INTRODUCTION TO JAVA
public
public classes, methods, and fields can be accessed from everywhere. The only constraint is that a
file with Java source code can only contain one public class which should be a main class.
protected
protected methods and fields can only be accessed within the same class to which the methods and
fields belong, also within its subclasses but not from anywhere else. You use the protected access
level when it is appropriate for a class's subclasses to have access to the method or field, but not for
unrelated classes.
private
private methods and fields can only be accessed within the same class to which the methods and
fields belong. private methods and fields are not visible within subclasses and are not inherited by
subclasses. So, the private access specifier is opposite to the public access specifier. It is mostly
used for encapsulation
default
If you do not set access to specific level, then such a class, method, or field will be accessible from
inside the same package to which the class, method, or field belongs, but not from outside this
package.
Postfix Operators
exp++, exp-Unary Operators
++expr, --expr, +expr, -expr, ~, !
Multiplicative Operators
*, /, %
Additive Operators
+, Shift Operators
<<, >>, >>>
latest IEEE Final year projects for B.E (CSE/ISE) sudents by Mr. Ashok Kumar K
Contact 9742013378 or 9742024066 for registering your name or visit www.vtuprojects.com
25
www.vtuprojects.com
UNIT 1
INTRODUCTION TO JAVA
Relational Operators
<, >, <=, >=, instanceof
Equality Operators
==, !=
Bitwise Operators
Bitwise AND (&)
Bitwise EXCLUSIVE OR (^)
Bitwise OR (|)
Logical Operators
Logical AND (&&)
Logical OR (||)
Ternary Operators
?:
Assignment Operators
=, +=, -=, *=, /=, %=, &=, ^=, |=, <<=, >>=, >>>=
Shift Operators
The signed left shift operator "<<" shifts a bit pattern to the left, and
The signed right shift operator ">>" shifts a bit pattern to the right.
The bit pattern is given by the left-hand operand, and the number of positions to shift by the
right-hand operand.
The unsigned right shift operator ">>>" shifts a zero into the leftmost position, while
the leftmost position after ">>" depends on sign extension.
Example:
public class Example
{
public static void main(String[] args)
{
int num1 = -5;
num1 = num1 >> 2;
System.out.println(num1);
int num2 = 5;
num2 = num2 >>> 2;
System.out.println(num2);
int num3 = 5;
num3 = num3 << 2;
System.out.println(num3);
}
}
latest IEEE Final year projects for B.E (CSE/ISE) sudents by Mr. Ashok Kumar K
Contact 9742013378 or 9742024066 for registering your name or visit www.vtuprojects.com
26
www.vtuprojects.com
UNIT 1
INTRODUCTION TO JAVA
Bitwise Operators
Ternary Operator
The ternary operator (also known as the conditional operator) can be used as an alternative
to the Java if/then/else syntax, but it goes beyond that, and can even be used on the right
hand side of Java statements.
latest IEEE Final year projects for B.E (CSE/ISE) sudents by Mr. Ashok Kumar K
Contact 9742013378 or 9742024066 for registering your name or visit www.vtuprojects.com
27
www.vtuprojects.com
UNIT 1
INTRODUCTION TO JAVA
Syntax
(condition) ? (truth block) : (false block) ;
The condition gets evaluated first. If the condition evaluates to true, the truth block gets
executed and returns, else the false block gets executed and returns.
Example
public class Example
{
public static void main(String[] args)
{
int a = 10;
int b = 20;
int min = (a < b) ? a: b;
}
Logical Operators
public class Example
{
public static void main(String args[])
{
boolean a = true;
boolean b = false;
latest IEEE Final year projects for B.E (CSE/ISE) sudents by Mr. Ashok Kumar K
Contact 9742013378 or 9742024066 for registering your name or visit www.vtuprojects.com
28
www.vtuprojects.com
UNIT 1
INTRODUCTION TO JAVA
1.6.2 Expressions
An expression is a construct made up of variables, operators, and method invocations, which are
constructed according to the syntax of the language, which evaluates to a single value. Some
examples of expressions are illustrated in bold below:
int cadence = 0;
anArray[0] = 100;
System.out.println("Element 1 at index 0: " + anArray[0]);
int result = 1 + 2; // result is now 3
if (value1 == value2)
System.out.println("value1 == value2");
The data type of the value returned by an expression depends on the elements used in the
expression. The expression cadence=0 returns an int because the assignment operator returns a
value of the same data type as its left-hand operand; in this case, cadence is an int. As you can see
from the other expressions, an expression can return other types of values as well, such
as boolean or String.
The Java programming language allows you to construct compound expressions from various
smaller expressions as long as the data type required by one part of the expression matches the data
type of the other. Here's an example of a compound expression:
1*2*3
In this particular example, the order in which the expression is evaluated is unimportant because the
result of multiplication is independent of order; the outcome is always the same, no matter in which
order you apply the multiplications. However, this is not true of all expressions. For example, the
following expression gives different results, depending on whether you perform the addition or the
division operation first:
x + y / 100
// ambiguous
You can specify exactly how an expression will be evaluated using balanced parenthesis: ( and ).
For example, to make the previous expression unambiguous, you could write the following:
(x + y) / 100 // unambiguous, recommended
If you don't explicitly indicate the order for the operations to be performed, the order is determined by
the precedence assigned to the operators in use within the expression. Operators that have a higher
precedence get evaluated first. For example, the division operator has a higher precedence than
does the addition operator. Therefore, the following two statements are equivalent:
x + y / 100
x + (y / 100) // unambiguous, recommended
When writing compound expressions, be explicit and indicate with parentheses which operators
should be evaluated first. This practice makes code easier to read and to maintain.
latest IEEE Final year projects for B.E (CSE/ISE) sudents by Mr. Ashok Kumar K
Contact 9742013378 or 9742024066 for registering your name or visit www.vtuprojects.com
29
www.vtuprojects.com
UNIT 1
INTRODUCTION TO JAVA
If
if-else
switch
Iteration statements
while
do-while
for
Jump statements
break
continue
return
30
www.vtuprojects.com
UNIT 1
INTRODUCTION TO JAVA
Syntax:
if (<conditional expression>) {
<statements>
} else {
<statements>
}
Example:
public class Example {
When the switch statement executes, it compares the value of the controlling
expression to the values of each case label.
The program will select the value of the case label that equals the value of the
controlling expression and branch down that path to the end of the code block.
latest IEEE Final year projects for B.E (CSE/ISE) sudents by Mr. Ashok Kumar K
Contact 9742013378 or 9742024066 for registering your name or visit www.vtuprojects.com
31
www.vtuprojects.com
UNIT 1
INTRODUCTION TO JAVA
If none of the case label values match, then none of the codes within the switch
statement code block will be executed. Java includes a default label to use in
cases where there are no matches.
We can have a nested switch within a case block of an outer switch.
Syntax:
switch (<non-long integral expression>) {
case label1: <statement1> ; break;
case label2: <statement2> ; break;
32
www.vtuprojects.com
UNIT 1
INTRODUCTION TO JAVA
latest IEEE Final year projects for B.E (CSE/ISE) sudents by Mr. Ashok Kumar K
Contact 9742013378 or 9742024066 for registering your name or visit www.vtuprojects.com
33
www.vtuprojects.com
UNIT 1
INTRODUCTION TO JAVA
Example:
public class Example {
public static void main(String[] args) {
System.out.println("Printing Numbers from 1 to 10");
for (int count = 1; count <= 10; count++) {
System.out.println(count);
}
}
}
34
www.vtuprojects.com
UNIT 1
INTRODUCTION TO JAVA
Example:
public class Example {
public static void main(String[] args) {
System.out.println("Odd Numbers");
for (int i = 1; i <= 10; ++i) {
if (i % 2 == 0)
continue;
// Rest of loop body skipped when i is even
System.out.println(i + "\t");
}
}
}
return (a + b);
latest IEEE Final year projects for B.E (CSE/ISE) sudents by Mr. Ashok Kumar K
Contact 9742013378 or 9742024066 for registering your name or visit www.vtuprojects.com
35