Chapter 3. Java Fundamentals and Control Structures
Chapter 3. Java Fundamentals and Control Structures
•Chapter 3
Java fundamentals and control structures
1
Object Oriented Programming Course VKU
Review
• Java was introduced by Sun Microsystems in 1995.
• Java is a programming language popularly used to build programs that can work on the Net.
• Its primary features are: it is object-oriented and a cross platform language.
• Swing, Drag and Drop, Java 2D API, Java Sound and RMI are some of the features added to the existing
version of Java.
• A Java applet is designed to work in a pre-defined “sandbox” only. This makes it safe to be used on the
Internet.
• Java bytecodes are machine language instructions understood by the Java Virtual Machine and usually
generated as a result of compiling Java language source code.
Object Oriented Programming Course VKU
Review Contd…
• Java programs can be divided into following categories-applets, applications, GUI applications,
servlets and database applications.
• Java visual development tools help the programmer to develop Java applications and applets
more quickly and efficiently.
• The JDK contains the software and tools needed to compile, debug and execute applets and
applications written in the Java language. It’s basically a set of command-line tools.
• Enhancement in Swing, AWT, a new I/O class and so on has been added in the latest version of
Java 1.4.2.
• The future will use a lot of Java related programs for consumer gadgets with embedded
technologies.
Object Oriented Programming Course VKU
Objectives
• Interpret the Java Program
• Understand the basics of Java Language
• Identify the Data Types
• Understand arrays
• Identify the Operators
• Format output using Escape Sequence
Object Oriented Programming Course VKU
The java compiler creates a file called 'First.class' that contains the byte codes
To actually run the program, a java interpreter called java is required to execute the code.
Object Oriented Programming Course VKU
class CommLineArg
{
public static void main (String [] pargs)
{
System.out.println("These are the arguments passed to the main
method.");
System.out.println(pargs [0]);
System.out.println(pargs [1]);
System.out.println(pargs [2]);
}
}
Object Oriented Programming Course VKU
Output
Object Oriented Programming Course VKU
Classes in Java
• Class declaration Syntax
class Classname
{
var_datatype variablename;
:
met_datatype methodname(parameter_list)
:
}
Object Oriented Programming Course VKU
Sample class
Object Oriented Programming Course VKU
Data Types
byte Array
char
boolean Class
short Interface
int
long
float
double
Object Oriented Programming Course VKU
Type Casting
• Example
float c = 34.89675f;
int b = (int)c + 10;
Object Oriented Programming Course VKU
Variables
• Syntax
datatype identifier [=value][, identifier[=value]...];
Object Oriented Programming Course VKU
Example
class DynVar
{
public static void main(String [] args)
{
double len = 5.0, wide = 7.0;
double num = Math.sqrt(len * len + wide * wide);
System.out.println("Value of num after dynamic initialization is " + num);
}
}
Output
Object Oriented Programming Course VKU
Example
class ScopeVar
{
public static void main(String [] args)
{
int num = 10;
if ( num == 10)
{
// num is available in inner scope
int num1 = num * num;
System.out.println("Value of num and num1 are " + num + " " + num1);
}
//num1 = 10; ERROR ! num1 is not known
System.out.println("Value of num is " + num);
}
} Output
Object Oriented Programming Course VKU
Array Declarations
class ArrDemo
{
public static void main(String [] arg)
{
double nums[] = {10.1, 11.3, 12.5,13.7, 14.9};
System.out.println(" The value at location 3 is : " + nums[3]);
}
}
Output
Object Oriented Programming Course VKU
Operators
• Arithmetic Operators
• Bitwise Operators
• Relational Operators
• Logical Operators
• Conditional Operators
• Assignment operators
Object Oriented Programming Course VKU
Arithmetic Operators
• Operands of the arithmetic operators must be of numeric type.
• Boolean operands cannot be used, but character operands are
allowed.
• These operators are used in mathematical expressions.
Object Oriented Programming Course VKU
Example
class ArithmeticOp
{
public static void main ( String [] arg)
{ Output
int num = 5, num1 = 12, num2 = 20, result;
result = num + num1;
System.out.println("Sum of num and num1 is : (num + num1) " + result);
result = num % num1;
System.out.println("Modulus of num and num1 is : (num % num1) " + result);
result *= num2;
System.out.println("Product of result and num2 is : (result *= num2) " + result);
System.out.println("Value of num before the operation is : " + num);
num ++;
System.out.println("Value of num after ++ operation is : " + num);
double num3 = 25.75, num4 = 14.25, res;
res = num3 - num4;
System.out.println("num3 – num4 is : " +res);
res -= 2.50;
System.out.println("res -= 2.50 " + res);
System.out.println("Value of res before -- operation is : "+ res);
res--;
System.out.println("Value of res after -- operation is : " + res);
}
}
Object Oriented Programming Course VKU
Bitwise Operators
• A bitwise operator allows manipulation of individual bits in an
integral primitive data type.
• These operators act upon the individual bits of their operands.
• Bitwise operators perform Boolean algebra on the corresponding
bits in the two arguments to produce the result.
Object Oriented Programming Course VKU
Relational Operators
• Relational operators test the relation between two operands.
• The result of an expression in which relational operators are used, is
boolean (either true or false).
• Relational operators are used in control structures.
Object Oriented Programming Course VKU
Example
class RelOp
{
public static void main(String [] args)
{
float num = 10.0F;
double num1 = 10.0;
if (num == num1)
System.out.println ("num is equal to num1");
else
System.out.println ("num is not equal to num1");
} Output
}
Object Oriented Programming Course VKU
Logical Operators
• Logical operators work with boolean operands.
• Some operators are
• &&
• ||
• ^
• !
Object Oriented Programming Course VKU
Conditional Operators
Assignment Operators
Operator Precedence
• Parentheses: ( ) and [ ]
• Unary Operators: +, -, ++, --, ~, !
• Arithmetic and Shift operators: *, /, %, +, -, >>, <<
• Relational Operators: >, >=, <, <=, ==, !=
• Logical and Bitwise Operators: &, ^, |, &&, ||,
• Conditional and Assignment Operators: ?=, =, *=, /=, +=, -=
• Parentheses are used to change the order in which an expression is evaluated.
Any part of an expression enclosed in parentheses is evaluated first.
Object Oriented Programming Course VKU
Control Flow
• All application development environments provide a decision making process
called control flow statements that direct the application execution.
• Flow control enables a developer to create an application that can examine the
existing conditions, and decide a suitable course of action.
• Loops or iteration are an important programming construct that can be used to
repeatedly execute a set of actions.
• Jump statements allow the program to execute in a non-linear fashion.
Object Oriented Programming Course VKU
• Decision-making
• if-else statement
• switch-case statement
• Loops
• while loop
• do-while loop
• for loop
Object Oriented Programming Course VKU
if-else statement
• The if-else statement tests the result of a condition, and performs appropriate actions
based on the result.
• It can be used to route program execution through two different paths.
• The format of an if-else statement is very simple and is given below:
if (condition)
{
action1;
}
else
{
action2;
}
Object Oriented Programming Course VKU
Example
class CheckNum
{
public static void main(String [] args)
{
int num = 10;
if (num % 2 == 0)
System.out.println(num + " is an even number");
else
System.out.println(num + " is an odd number");
}
} Output
Object Oriented Programming Course VKU
Example
class SwitchDemo
{ case 5:
public static void main(String[] args)
str = "Friday";
{ break;
int day =
case 6:4;
String str; str = "Saturday";
switch (day) break;
{ default:
case 0:str = "Invalid day";
} str = "Sunday";
break;
System.out.println(str);
} case 1:
} Output str = "Monday";
break;
case 2:
str = "Tuesday";
break;
case 3:
str = "Wednesday";
break;
case 4:
str = "Thursday";
break;
Object Oriented Programming Course VKU
while Loop
• while loops are used for situations when a loop has to be executed as long as
certain condition is True.
• The number of times a loop is to be executed is not pre-determined, but
depends on the condition.
• The syntax is:
while (condition)
{
action statements;
.
.
.}
Object Oriented Programming Course VKU
Example
class FactDemo
{
public static void main(String [] args)
{
int num = 5, fact = 1;
while (num >= 1)
{
fact *= num;
num--;
} Output
System.out.println("The factorial of 5 is : " + fact);
}
}
Object Oriented Programming Course VKU
do – while Loop
• The do-while loop executes certain statements till the specified condition is
True.
• These loops are similar to the while loops, except that a do-while loop
executes at least once, even if the specified condition is False. The syntax is:
do
{
action statements;
.
.
} while (condition);
Object Oriented Programming Course VKU
Example
class DoWhileDemo
{
public static void main(String [] args)
{
int count = 1, sum = 0;
do
{
sum += count;
count++;
}while (count <= 100);
System.out.println("The sum of first 100 numbers is : " + sum);
}
}
Output
The sum of first 100 numbers is : 5050
Object Oriented Programming Course VKU
for Loop
• All loops have some common features: a counter variable that is initialized before the loop begins, a
condition that tests the counter variable and a statement that modifies the value of the counter variable.
• The for loop provides a compact format for incorporating these features.
Syntax:
for (initialization statements; condition; increment / decrement statements)
{
action statements;
.
.
}
Object Oriented Programming Course VKU
Example
class ForDemo
{
public static void main(String [] args)
{
int count = 1, sum = 0;
for (count = 1; count <= 10; count += 2)
{
sum += count;
}
System.out.println("The sum of first 5 odd numbers is : " + sum);
}
}
Output
The sum of first 5 odd numbers is : 25
Object Oriented Programming Course VKU
Jump Statements
• Three jump statements are:
• break
• continue
• return
• The three uses of break statements are:
• It terminates a statement sequence in a switch statement.
• It can be used to exit a loop.
• It is another form of goto.
Object Oriented Programming Course VKU
Summary
• A Java program consists of a set of classes. A program may contain comments. The compiler ignores
this commented lines.
• The Java program must have a main() method from where it begins its execution.
• Classes define a template for units that store data and code related to an entity.
• Variables defined in a class are called the instance variables.
• There are two types of casting:widening and narrowing casting.
• Variables are basic unit of storage.
• Each variable has a scope and lifetime.
• Arrays are used to store several items of same data type in consecutive memory locations.
Object Oriented Programming Course VKU
Summary Contd…
• Java provides different types of operators. They include:
• Arithmetic
• Bitwise
• Relational
• Logical
• Conditional
• Assignment
• Java supports the following programming constructs:
• if-else
• switch
• for
• while
• do-while
• The three jump statements-break,continue and return helps to transfer control to another part
of the program.