Unit 1
Unit 1
Unit 1
CHAPTER 1 10 Marks
Basic Syntactical Concepts in Java
• Java is a high-level, general-purpose, and pure object-oriented programming
language. Java applications are typically compiled to bytecode (class file) that can run
on any Java virtual machine (JVM).
• Java was developed by James Gosling at Sun Microsystems of USA in 1991. The
language was initially called Oak. Java was invented for the development of software
for consumer electronic devices like TVs, toasters, etc. The main aim had to make java
simple, portable and reliable.
• Java supports "Write Once, Run Anywhere" (WORA). It means Java can be developed
on any device, compiled into a standard bytecode and be expected to run on any
device with a Java virtual machine (JVM).
1) Stand-alone applications are programs written in Java to carry out certain tasks
on a stand-alone local computer. Executing a stand-alone Java programs involves
two steps:
i. Compiling source code into bytecode program using javac compiler
ii. Executing the bytecode program using java interpreter.
2) Applets are small Java programs developed for Internet applications. An applet
located on a server can be downloaded via Internet and executed on a local
computer using Java capable browser.
Java Editions
Sun has three editions of Java for a given platform or version (the current platform is
Java 2). The editions for the current platform are:
1. J2ME (Micro Edition):
It is used to create programs that run on small handheld devices, such as phones,
PDAs (personal digital assistants), and appliances.
2. J2SE (Standard Edition):
It is used primarily to create programs for desktop computers or for any computer
too large for J2ME and too small for J2EE.
3. J2EE (Enterprise Edition):
It is used to create very large programs that run on servers managing heavy traffic
and complicated transactions. These programs are the backbone of many online
services, such as banking, e-commerce, and B2B (business-to-business) trading
systems.
1
Java Programming(I Scheme 22412)
2) Platform Independent
• Bytecode and JVM (Java Virtual Machine) makes Java as platform Independent
language.
• Java supports ‘Write Once Run Everywhere’ (WORA) strategy.
• Java programs are portable across operating systems and hardware environments. Java
programs can be easily moved from one computer system to another, anywhere
and anytime. Because of this Java is more popular language for programming on
Internet which interconnects different kind of systems worldwide.
3) Portable
• Java programs are portable across operating systems and hardware environments.
• Java programs can be easily moved from one computer system to another,
anywhere and anytime.
• Java certifies portability in two ways:
1) Java compiler generates the Bytecode and that can be executed on any
machine.
2) Size of primitive data types are machine independent.
4) Object- oriented
• Java is truly object-oriented language.
2
Java Programming(I Scheme 22412)
• Almost everything in Java is an Object. All program code and data exist in objects
and classes.
• Java also has basic OOP properties such as encapsulation, polymorphism, data
abstraction, inheritance etc.
• Java comes with an extensive set of classes, organized in packages.
• The object model in Java is simple and easy to extend.
6) Distributed
• Java is designed for the distributed environment of the Internet/LAN, because it
handles TCP/IP protocols.
• Java is called as Distributed language for creating applications on networks.
• It has the ability to share both data and programs. Java applications can open and
access remote objects on Internet easily.
9) High Performance
• Java performance is very high, mainly due to the use of intermediate bytecode.
• Multithreading enhances the overall execution speed of Java programs.
10) Dynamic and Extensible
• Java is a dynamic language. Java dynamically links new class libraries, methods
and objects.
3
Java Programming(I Scheme 22412)
• Java programs support functions written in other languages such as C and C++.
These functions are known as native methods. Native methods linked dynamically
at runtime.
Bytecode:
• To solve both the security and the portability problems the output of a Java
compiler is not executable code. Rather, it is bytecode.
• Java compiler convert the source code into Intermediate code is called as
bytecode. This machine is called the Java Virtual Machine and it exits only inside
the computer memory.
• Bytecode is a highly optimized set of instructions designed to be executed by the
Java run-time system, which is called the Java Virtual Machine (JVM). Java Virtual
machine exists only inside the computer memory.
• Java program is executed by the JVM also helps to make it secure.
• The use of bytecode enables the JVM to execute programs much faster.
Java Environment:
• Java environment includes a number of development tools, classes and methods.
• The development tools are part of the system known as Java Development Kit (JDK)
and the classes and methods are part of the Java Standard Library (JSL).
• Java Standard Library (JSL) is also known as the Application Programming Interface
(API).
4
Java Programming(I Scheme 22412)
• For example: For compiling and running the program we have to use following
commands:
a) javac (Java compiler)
✓ Java compiler converts the source code or program in bytecode. That is java
compiler convert “.java” file in “.class” file.
✓ To compile the program, execute the compiler, javac, specifying the name of the
source file on the command line
✓ Syntax: C:\javac filename.java
✓ Example :If my filename is abc.java then the syntax will be
C:\javac abc.java
b) java (Java Interpreter)
✓ To actually run the program, you must use the Java application launcher, called
java.
✓ Java interpreter converts bytecode into machine code and executes the
program to produce result.
✓ Syntax: C:\java filename
✓ Example: If my filename is abc.java then the syntax will be
5
Java Programming(I Scheme 22412)
C:\java abc
❖ A First Simple Program
class Sample
{
public static void main(String args[ ])
{
System.out.println ("Welcome to Java");
}
}
The file must be equivalent to the class name containing the main method i.e.
“Sample.java”.
• Class Declaration:
The first line Class Sample , declares a class, which is an object-oriented construct.
Sample is a Java identifier that specifies the name of the class to be defined.
• Opening and Closing Brace:
Every class definition in Java begins with an opening brace “{“ and ends with a
matching closing brace “}”. A class definition in Java does not end with a semicolon.
• The main line:
The third line
public static void main(String args[ ])
defines a method named main. Every Java application program must include the
main() method. This is the starting point for the interpreter to begin the execution of the
program. A Java application can have any number of classes but only one of them
must include a main method to initiate the execution. Java applets will not use the
main method at all.
The keyword public is an access specifier that declares the
public main() method as unprotected and therefore making it accessible
to all other classes.
The keyword static declares this method as one that belongs to
entire class and not a part of any objects. The main() must be
static
declared as static since the interpreter uses this method before
any objects are created.
The type modifier void states that the main() method does not
void
return any value.
String args[ ] declares a parameter named args, which contains
String args[ ]
an array of objects of the class type String
• The output line:
System.out.println (“welcome to Java”);
The println method is a member of the out object, which is a static data member of
System class. This line prints the string
Welcome to Java.
6
Java Programming(I Scheme 22412)
❖ Creating Objects:
• Objects are the variables of class. It is a basic unit of Object Oriented
programming and represents the real life entities. Object is the instance of the
class.
• In Java, the new keyword is used to create new objects.
7
Java Programming(I Scheme 22412)
or
className objectName = new className(Parameters);
• Example:
Student s1; // Declaration
s1=new Student(); //Instantiation/Initialization
Or
Student s1=new Student(); // Declaration & Instantiation/Initialization
Here, Student ( ) specifies the default constructor of the class
• The new operator dynamically allocates the memory for the object. That is, it
allocates the memory at run time.
Action Result
Declare Student s1; Null
Student
Fig :Declaring and creating object object
• For example: the instance variables and methods of the class ‘Student’ can be
accessed as,
s1.rollno=10;
s1.name=”xyz”;
8
Java Programming(I Scheme 22412)
s1.display();
• Example Program:
class Student
{
int rollno;
String name;
void display()
{
System.out.println(“Roll no=”+rollno);
System.out.println(“Name=”+name);
}
}
Class Demo
{
public static void main(String args[])
{
Student s=new Student ();
s1.rollno=10;
s.name=”xyz”;
s.display();
}
}
9
Java Programming(I Scheme 22412)
2) Identifies :
• Identifiers are programmer designed tokens.
• They are used for naming classes, methods, variable objects, labels,
packages and interfaces in a program.
• Java identifiers follow the following rules.
1) They can have alphabets, digits & underscore & dollar sign characters.
2) They must not begin with a digit.
3) Upper case & lower case letters are distinct.
4) They can be of any length.
3) Literal :
• Literals in Java are a sequence of character (digits, letters and other
character) that represent constant values to be stored in variables.
• Types of literals:
i. Integer literals
ii. Floating point literals
iii. Character literals
iv. String literals
v. Boolean literals
4) Operators :
An operator is a symbol that takes one or more argyments and operates on
them to produce a result.
5) Separators :
• Separators are symbols used to indicate where groups of code are divided
and arranged.
Parentheses ( ) Used to enclosed parameters in method definition.
Braces { } 1. Define a block of code for classes methods and
local scope.
2. Automatically initialize values to array.
Brackets [ ] Used to declare array types.
Semicolon ; Used to separate statement.
Comma , Used to separate identifiers in a variable deceleration.
Constants:
✓ Constant is an entity that does not change during the program execution. Constant
means fixed value.
✓ In Java, there are two types of constant as follows:
1. Numeric Constants
• Integer constant
• Real constant
2. Character Constants
10
Java Programming(I Scheme 22412)
• Character constant
• String constant
Integer constant:
✓ An integer constant refers to a series of digits. There are three types of integers:
decimal integer, octal integer, and hexadecimal integer.
1) Decimal Integer: Decimal Integer consists of a set of digits from 0 to 9. Embedded
spaces, commas and characters are not allowed in between digits.
For example: 123
-321
654321
2) Octal Integer: It consists of a set of digits from 0 to 7 with a leading 0.
For example: 011
0425
3) Hexadecimal Integer: A series of digits preceded by 0x or 0X is considered as
hexadecimal integers. They may also include alphabets from A to F or from a to f.
For example: 0x7
0XA
Real constant:
✓ It allows fractional data and it is also called as floating point constant. It is used for
percentage, height, temperature and so on.
✓ For example: 0.0234
0.777
-1.23
✓ A real number may also be expressed in exponential notation (scientific notation).
The general form is
mantissa e exponent
Character Constant
✓ It allows single character within pair of single quote.
✓ For example: ‘A‘ ‘7‘ ‘+’
String Constant
✓ String constant is series of characters within pair of double quotes.
✓ For example: “WELCOME” “1997” “Hello Java”
11
Java Programming(I Scheme 22412)
‘\t’ Tab
‘\n’ New line
‘\\’ Backslash
‘\’’ Single quote
‘\”\ Double quote
Variables:
• The variable is the basic unit of storage. A variable is an identifier that denotes a
storage location used to store a data value.
• A variable is an entity that may change during program execution. A variable can
be used to store a value of any data type.
❖ Rules for variable name:
Variable names may consist of alphabets, digits, underscore and dollar character.
1) They must not begin with a digit.
2) Uppercase and lowercase are distinct. This means that the variable total is not
same as Total or TOTAL.
3) It should not be a keyword.
4) White space is not allowed.
5) Variable names can be of any length.
❖ Declaration of variables:
✓ A variable must be declared before it is used in the program.
✓ Variable declaration does three things:
1) It tells the compiler what the variable name is.
2) It specifies what type of data the variable will hold.
3) The place of declaration decides the scope of the variable.
✓ Syntax: type variable1, variable2, ……….., variablen;
✓ Examples:
int a, b, c; // declares three ints, a, b, and c.
int d = 3, e, f = 5; // declares three more ints, initializing d and f.
byte z = 22; // initializes z.
double pi = 3.14159; // declares an approximation of pi.
char x = 'x'; // the variable x has the value 'x'.
❖ Types of variable:
There are three types of variables in Java.
1) Local Variables: These are declared and used inside methods.
2) Instance Variables: These are declared inside a class but outside any method.
Each object has its own copy of instance variables. So, these variables are created
when objects are instantiated.
3) Static / Class Variables: These are global to the class and doesn’t belong to any
particular object. There is one copy of each static variable is created per class when
the class is loaded.
12
Java Programming(I Scheme 22412)
13
Java Programming(I Scheme 22412)
Data Types:
• A data type is a scheme for representing values.
• The data type defines the type of data that a variable holds.
• There are two types of data types
1. Primitive data type
2. Non-primitive data type
• Java defines eight primitive types of data: byte, short, int, long, char, float,
double, and boolean.
Primitive Non-Primitive
(Intrinsic) (Derived)
1) Integer types:
✓ Integer data type can hold the whole numbers, such as 123, -98, and 3456.
✓ In Java, there are four types of integer as follows:
• byte
• short
• int
• long
✓ We can make integer long by adding ‘l’ or ‘L‘ at the end of the number. For
example: 123L or 123l.
✓ The number can be positive number or negative number.
✓ Byte and short data types are used to save space in large arrays
14
Java Programming(I Scheme 22412)
3) Character type:
✓ To store character constant, Java provides a character data type called char.
✓ It uses 16-bit Unicode (0 to 65535).
✓ It can hold only a single character. Its default value is null character
✓ Size of char type is 2 bytes.
4) Boolean type:
✓ Boolean type is used when we want to test a particular condition during the
execution of the program.
✓ Boolean type can take only two values: true or false.
✓ This data type is used for simple flags that track true/false conditions.
✓ Default value is false.
✓ Uses only 1bit of storage.
Scope of Variable:
• Java allows variables to be declared within any block. A block defines a scope.
• The area of the program where the variable is accessible (i.e., usable) is
called its scope.
• Variables declared inside a scope are not visible (that is, accessible) to code that is
defined outside that scope.
• Thus, when you declare a variable within a scope, you are localizing that variable
and protecting it from unauthorized access and modification.
• There are three kinds of variables in Java:
1) Local variables
2) Instance variables
3) Class/static variables
• Local variables:
✓ Variables defined inside methods, constructors or blocks are called local
variables.
✓ The variable will be declared and initialized within the method and the variable
will be destroyed when the method has completed.
✓ Access modifiers cannot be used for local variables.
• Instance variables:
✓ Instance variables are variables within a class but outside any method.
15
Java Programming(I Scheme 22412)
• Class/static variables :
✓ Static variables declared within a class, outside any method are referred to as
class variables.
• For example:
class Demo
{
int x; //instance variable
static int y; //class variable or staic variable
void get(int z) //z is local variable
{
x=z;
}
}
Symbolic Constant
• We have already known certain universal constants. For example, value of Pi (π) in
3.14, value of gravitational constant if 9.81 etc.
• If we want to define the constant in Java one type modifier is used called final.
‘final’ is the keyword used to define the symbolic constant in a Java
program.
• It takes the following form:
final data_type symbolic_name = value;
16
Java Programming(I Scheme 22412)
• The value assigned to the symbolic name is constant and cannot be changed in
any case in the program. At the time of declaration, it is necessary to assign the
value to the variable.
• For example: final double PI = 3.145;
final float GVT= 9.81f;
final int max = 1000;
• We can use the symbolic constants in program in any expression but cannot
modify their value.
• Symbolic names take the same form as variable names. But, they are usually
written in CAPITALS to distinguish them from normal variable names. This is not a
rule.
• They cannot be declared inside a method. They should be used only as class data
members in the beginning of the class.
//Program on Symbolic Constants
class Area1
{ public static void main(String args[]) Output:
{
Area of circle=94.985
final float PI=3.14f;
float r=5.5f;
float area=PI*r*r;
System.out.println ("Area of circle="+area);
}
}
Type Casting:
• Although the automatic type conversions are helpful, they will not fulfill all our
needs. We often face the situation where there is need to store the value of one
type into variable of another type. In such situations, it is necessary to cast or
temporary convert the variable of one type into another type. It is performed by type
casting.
• Casting into a smaller type may result in the loss of data.
• Widening: In automatic type conversion always lower type is converted to higher
type. This type of conversion is called as widening the conversion.
• Narrowing: If we want to convert higher type to lower type then type casting is
necessary. For that purpose the type casting operator is used. This type of
conversion is called as narrowing the conversion.
• It takes the following form.
(target type) Variablename;
Here, target type specifies the desired type to convert the specified value.
For example, if we want to convert int to byte or long ,then
int val = 163;
byte b = (byte) val;
• Without type casting it is not possible to assign higher data value to lower one.
17
Java Programming(I Scheme 22412)
• For example:
int array[ ]=new int[5];
• Here, array1 is the name of array, which allocates memory for 5 int type elements.
• We can initialize array by using index. such as,
array[0]=100;
array[1]=200;
array[2]=300;
array[3]=400;
array[4]=500;
String:
• Strings are a sequence of characters. In the Java programming language, strings
are objects.
• The Java platform provides the String class to create and manipulate strings.
• Syntax:
String variablename=”value”; or
String variablename=new String(“value”);
• For Example:
String name=”xyz”;
String city=new String(“Solapur”);
• Java supports a rich set of operators which are used in a program, to manipulate
the data and variables. Operators in Java are classified into number of categories:
1) Arithmetic Operators 5) Logical Operators
2) Assignment Operators 6) Conditional Operators
3) Increment / Decrement Operators 7) Special Operators
4) Relational Operators
1) Arithmetic Operators
• These include all the operators which are used to perform basic arithmetic
operations. These are listed and explained in the following table.
Operator Meaning
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulo Division
• These can operate on any built-in numeric data types of java. We cannot use these
operators on boolean type.
• The modulus operator, %, returns the remainder of a division operation.
• When all the operands in an arithmetic expression are integer then it is called as
integer expression. They always return integer value.
For example: x = 10 and y = 3
Then, x + y = 13
x–y=7
x * y = 30
x / y = 3 (decimal part is truncated)
x % y = 1 (remainder of the division)
• When an arithmetic expression involves only real operands is called as real
arithmetic.
• When one of the operands is real and the other is integer, the operation is called as
mixed-mode expression.
• If any one of the operands is floating point, then the operation will generate the
floating point result.
• Thus, 25 / 10.0 will generate result 2.5
// Program on Arithmetic operators
class Arithmetic Output:
{ public static void main(String args[]) a=20
{ int a=20,b=6; b=6
a+b=26
System.out.println ("a="+a);
a-b=14
System.out.println ("b="+b); a*b=120
System.out.println ("a+b="+(a+b)); a/b=3.3333333
System.out.println ("a-b="+(a-b)); a%b=2
System.out.println ("a*b="+(a*b));
19
Java Programming(I Scheme 22412)
System.out.println ("a/b="+((float)a/b));
System.out.println ("a%b="+(a%b));
}
}
2) Relational Operators
• When we want to compare values of two variables for various means, relational
operators are used. After comparing these values we may take several decisions in
the program.
• Java supports six different relational operators. These are listed and
explained in the following table.
Operator Meaning
< Less than
> Greater than
<= Less than or equal to
>= Greater than or equal to
== Equal to
!= Not equal to
• Relational operators can be called as comparison operators.
• For example, we want to find the largest of two integers, we can use ‘>’ operators
to perform comparison.
• The expressions such as, x > 12 or x < y contains the relational operator. So,
they can be termed as relational expression.
• The value of relational expression can be either true or false.
• For example,
if x = 10 and y = 15 then, x < y is true while x > 20 is false
20
Java Programming(I Scheme 22412)
3) Logical Operators
• There are only three logical operators which are related with the logical decisions.
These are listed in the following table
Operator Meaning
&& Logical AND
|| Logical OR
! Logical NOT
• First two operators are used to combine the conditions i.e. to form a compound
conditional expression. Third operator is used to inverse the condition.
• Example of && (Logical AND)
✓ For example,
x > y && k !=12
✓ This is termed as the logical expression or a compound relational
expression. Whole expression also returns the boolean value. That is, the
above expression will return true when the both the conditions (x > y) and (k
!= 12) are true. If any one of these conditions is false the expression will
return false.
• Example of || (Logical OR)
✓ For example,
m == 99 || j <= 10
✓ This logical expression involves the logical OR operator. The expression will
return true only when any one of the conditions (m==99 and j<=10) is true. If
both conditions are false, the whole expression will also return false. That is,
in order to evaluate the expression to true, any one of the condition must be
true.
• Example of ! (Logical NOT)
✓ This is the only unary logical operator and generally used to negate the
condition.
✓ The result of the expression will be inverted. That is, true will become false
and false will become true.
✓ For example, x = 36 then
! (x>40) will return true
! (x==36) will return false
}
}
4) Assignment operators
• Assignment operators are used to assign the value of an expression to
the variable. The general assignment operator is ‘=’. This is used to
assign the value given to its right side to the variable written on left
side.
• Other assignment operators are also known as shorthand assignment
operators.
• These shorthand assignment operators can be used to combine an
arithmetic operation with an assignment.
Operator Example Equivalent Statement
+= x +=10 x=x+10
-= x -=10 x=x-10
*= x *=10 x=x*10
/= x /=10 x=x/10
%= x %=10 x=x%10
d =a++; a = 12
System.out.println("\na = " + a); d = 11
System.out.println("d = " + d);
b = 19
e = 19
e =--b;
System.out.println("\nb = " + b); b = 18
System.out.println("e = " + e); f = 19
f =b--;
System.out.println("\nb = " + b);
System.out.println("f = " + f);
}
}
6) Conditional Operator
• The only ternary operator (operator having three operands) is defined in Java
called as conditional operator.
• The pair ? : is termed as conditional operator. This is used to construct the
conditional expression of the following form:
expression1 ? expression2 : expression3
23
Java Programming(I Scheme 22412)
• When the condition written is true then the expression1 is evaluated else
expression2 is executed. Means, any one of the expression1 and 2 is executed in
any case. It can also be called as if then- else operator.
• For example,
x = 45;
y = 22;
x = (y>25) ? y : 50;
After completion of third statement execution, value of x will become 50. Because,
the condition y>25 is false so first expression will not be executed. Only second
expression is evaluated. That is, 50 will be assigned to variable x.
7) Bitwise Operators
• In order to manipulate the data at the bit level, the bitwise operators are provided in
Java. These operators are used for testing the bits as well as shifting them to left or
right etc.
• Table shows the bitwise operators and their meaning.
• These can be applied to integer types only. That is, they cannot be used along with
float or double value.
• All these operators except one’s complement operator are binary operato rs.
• Shift operators shift the binary equivalent bits of the operand to respective left or
right position.
• >>> operator is one of the special type of bitwise operator which is generally used
for the negative values which will be shifted to right by filling the zeroes to leftmost
positions.
24
Java Programming(I Scheme 22412)
For Example:
A B A&B A|B A^B ~A
0 0 0 0 0 1
0 1 0 1 1 1
1 0 0 1 1 0
1 1 1 1 0 0
class Bitwise
{
public static void main(String args[])
{
int a = 4, b,c=20,d;
b = a << 2; Output
System.out.println("Original value of a: " + a); Original value of a: 4
System.out.println("after shifting 2 bits at left=" + b); after shifting 2 bits at left=16
Original value of c: 20
d = c >> 2; after shifting 2 bits at right=5
System.out.println("Original value of c: " + c);
System.out.println("after shifting 2 bits at right=" + d);
}
}
8) Special Operators
• Java supports two special operators.
1) instanceof operator 2) Member selection operator or dot operator (.)
• Instanceof operator:
- An instanceof is the keyword called as an object reference binary operator.
This operator allows us to determine whether the object belong to particular
class or not.
- Syntax: objectname instanceof classname;
- For example: apple instanceof Fruit
Returns true if the ‘apple’ is the object of class ‘Fruit’. Otherwise it will return
false.
• Member selection operator
- This is also called as dot operator (.).
- It is used to access the instance variable and methods of the class using
objects.
- For example: company. salary (); //reference to method salary
company. empID=101; //reference to variable empID
25
Java Programming(I Scheme 22412)
Math Functions:
• The java.lang.Math class contains methods for performing basic numeric
operations such as the logarithm, square root, and trigonometric functions.
• These function should be used as
Math.function_name()
• For example: double x=Math.sqrt(81);
Functions Meaning
min(a,b) Returns minimum of a and b.
max(a,b) Returns maximum of a and b
sqrt(x) Returns square root of x.
pow(x,y) Returns x raised to y (xy)
exp(x) Returns e raised to y (ey)
round(x) Returns the integer closest to the argument x.
abs(a) Returns the absolute value of a .
• Here, a and b may be int,long, float or double. x and y are double type parameters.
Associativity.
• When an expression has two operators with the same precedence, the expression is
evaluated according to its associativity.
• For example
1) x = y = z = 10 is treated as x = (y = (z = 10)), leaving all three variables with the
value 10, since the = operator has right-to-left associativity .
2) 70 / 2 / 3 is treated as (70 / 2) / 3 since the / operator has left-to-right associativity.
26
Java Programming(I Scheme 22412)
• Following table shows that arithmetic operators are having highest operator
precedence than relational operators.
27
Java Programming(I Scheme 22412)
✓ If the condition given is true then the statements inside the if-block are executed
otherwise statement inside else-block are executed. That is, any one of the
statements is executed depending upon the status of the condition (i.e. true or
false). After all the statements written after the blocks are executed though the
condition is true or false.
{
if(x > z)
System.out.print(x+" is largest");
else
System.out.print(z+" is largest");
}
else
{
if(y > z)
System.out.print(y+" is largest");
else
System.out.print(z+" is largest");
}
}
}
The conditions are evaluated from top of the ladder to the bottom.
class Largest
{
public static void main(String args[])
{
int x = 10, y = 15, z = 12;
if(x > y && x > z)
System.out.println(x+" is largest");
else if((y > x && y > z) Output:
System.out.println(y+" is largest"); 15 is largest
else if(z > x && z > y)
System.out.println(z+" is largest");
else
System.out.println(“All numbers are equal");
}
29
Java Programming(I Scheme 22412)
✓ Switch is the multi-way selection statement. It tests the value of the variable (or
expression) against the list of case values and when match is found, a block of
statements associated with that case are executed.
✓ It is applicable when it is impossible to write the ‘if’ statement many times in the
programs. It is used to create the menu driven program to select from the multiple
choices.
✓ The expression is either an integer or character variable or an expression which is
evaluated to an integer value.
✓ value-1, value-2… are constants, which are also known as case labels. A colon (:)
is given after each case label. When the switch is executed, the value of the
variable is successively compared with the values value-1, value-2….
✓ If the case is found whose value matches with the variable then the statements in
front of respective case are executed.
✓ The ‘break’ statement is written at the end of each case statement to signal the end
of particular case. It causes the exit from the switch statement. It also transfers the
program control out of the switch block to execute the statement-x.
✓ The ‘default’ is executed when there is no match found in the cases.
Program on switch-case
class SwitchCase
{
public static void main(String args[])
{
int ch=3;
switch(ch)
{ case 1:System.out.println("One");
Output:
break;
Three
case 2:System.out.println("Two");
break;
case 3:System.out.println("Three");
break;
case 4:System.out.println("Four");
30
Java Programming(I Scheme 22412)
break;
default:System.out.println("Invalid");
break;
}
}
}
• The ‘while’ is an entry controlled loop structure. That is, before the program control
enters the loop, the loop condition is checked. It can also be called as pre-test loop
• If the condition given is evaluated to true then the body of the loop is executed until
the condition satisfies to true. When the condition becomes false, the loop is
terminated. Then statements written after the loop are executed. If condition
doesn’t become true any time then loop will go into infinite iteration execution.
31
Java Programming(I Scheme 22412)
2. Value of the control variable is tested using the test condition. The test condition is
a relational expression, e.g.: i<10, which determine when the loop will exit. If the
condition is true the body of the loop is executed else loop is terminated
3. After the body of the loop is executed the control transfers back to for statement
and the control variable is incremented using statement such as i= i+1
33
Java Programming(I Scheme 22412)
Jump statements
Sometimes while executing the loop it is necessary to skip some part of the loop or exit
from the loop. For this jump statements are used. There are two jump statements
related to loop structures.
1. break statement.
2. continue statement.
1) Break statement:
✓ The break statement has two uses:
1. It terminates a statement sequence in a switch statement.
2. It can be used to exit a loop
✓ When a break statement is encountered inside a loop, the loop is terminated and
program control resumes at the next statement following the loop.
✓ Generally, the ‘break’ statement is associated with an ‘if’ statement. That is, when
the condition is satisfied, the jump will occur.
✓ When used inside a set of nested loops, the break statement will only break out of
the innermost loop.
✓ For example: Using break to exit a loop.
class BreakLoop Output:
{ i: 0
public static void main(String args[]) i: 1
{ i: 2
for(int i=0; i<10; i++)
{
if(i == 3)
break; // terminate loop if i is 3
System.out.println ("i: " + i);
}
}
}
2) Continue Statement:
✓ When we want to continue the next iteration of the loop by skipping some part
inside it, the ‘continue’ statement can be used.
✓ It is also associated with the condition.
✓ General form of the ‘continue’ is:
continue;
✓ When the ‘continue’ is encountered in the loop the program control skips all the
further statements after that in the loop and proceed to execute the next iteration.
{
Output:
if (i == 3) i: 0
continue; //skips further statements if i=3 i: 1
//& continues to next iteration i: 2
System.out.println (“i =”+ i); i: 4
} i: 5
i: 6
}
i: 7
} i: 8
i: 9
35
Java Programming(I Scheme 22412)
Sr.
Java C++
No.
C++ is an extension of C with object
Java is a true and complete object
1 oriented behavior. C++ is not a complete
oriented language.
object oriented language as that of Java.
Java does not provide template
2 C++ offers Template classes.
classes.
C++ achieves multiple inheritance by
Java supports multiple inheritance
3 permitting classes to inherit from multiple
using interface.
classes.
4 Java does not support pointers. C++ supports pointers.
Java does not provide global
5 Global variables can be declared in C++.
variables.
In Java, destruction of objects is In C++, destruction of objects is performed
6
performed in finalize () method. by destructor function.
7 Java doesn’t provide header files. C++ has header files.
Java does not support operator
8 C++ support operator overloading.
overloading.
9 Java provides a true boolean type. C++ does not provide a boolean type.
The char type in Java is a 16-bit type The char type in C++ is an 8-bit type that
10
and uses the Unicode character set maps to the ASCII
36
Java Programming(I Scheme 22412)
if(num%2==0)
System.out.println(num+” is even number”) ;
else
System.out.println(num+” is odd number”) ;
}
}
To print even numbers between 1 and 20
import java.util.*;
class Even
{
public static void main(String args[])
{
for(int i=1;i<=20;i++)
{
if(num%2==0)
System.out.println(num+” is even number”) ;
else
System.out.println(num+” is odd number”) ;
}
}
}
37
Java Programming(I Scheme 22412)
for(i=2;i<num;i++)
{
if(num%i==0)
break;
}
if(i==num)
System.out.println("Prime number");
else
System.out.println("Prime number");
for(num=2;num<=20;num++)
{
for(i=2;i<num;i++)
{
if(num%i==0)
break;
}
if(i==num)
System.out.println(num);
}
}
}
38
Java Programming(I Scheme 22412)
while(num>0)
{
rem=num%10;
sum=sum+rem;
num=num/10;
}
System.out.println("Sum of digits="+sum);
}
}
To print number in reverse order
import java.util.*;
class Reverse
{
public static void main(String args[])
{
int num,rem,rev=0;
Scanner sc=new Scanner(System.in);
System.out.println("Enter number=");
num=sc.nextInt();
while(num>0)
{
rem=num%10;
rev=rem+rev*10
num=num/10;
}
System.out.println("Reverse num="+rev);
}
}
Num=123 num=12 num=1
rem 123%10=3 rem 12%10=2 rem 1%10=1
rev 3+0*10=3 rev 2+3*10=32 rev 1+32*10=321
num 123/10=12 num 12/10=1 num 1/10=0
39
Java Programming(I Scheme 22412)
System.out.print(n1+"\t"+n2);
for(int i=1;i<=10;i++)
{
n3=n1+n2;
System.out.print("\t"+n3);
n1=n2;
n2=n3;
}
}
}
Questions on Chapter-1
1. Why Java is known as Platform-independent language?
2. Explain why Java is called as true object oriented language.
3. Why Java is popular on Internet?
4. Explain the various features of the java programming language.
5. What do you mean by BYTECODE? What is JVM?
6. What are the different data types in JAVA? Explain each of them with example.
7. Write a program to generate Fibonacci series.
8. Write a program to calculate factorial of a given number.
9. Write a program to print even numbers between 1 and 20.
10. Write a program to check given number is even or odd.
11. Write a program to check given number is prime or not.
12. Write a program to print sum of digits.(if num=123 then sum=6)
13. Write a program to print reverse of a number(if num=123 then reverse=321)
14. Explain Symbolic Constants in Java.
15. Explain typecasting with suitable example.
40