Introduction To OOP UNIT-1 RK
Introduction To OOP UNIT-1 RK
JAVA Unit-1
1
R16
JAVA Unit-1
language, principles of OOP, applications of OOP, history of java, java features, JVM,
program structure.
Variables, primitive data types, identifiers, literals, operators, expressions,
precedence rules and associativity, primitive type conversions and casting, flow of control.
2
R16
JAVA Unit-1
3
R16
JAVA Unit-1
Inheritance
Acquiring or getting properties from base class to the derived class is called as
inheritance.
The class which gives properties to the other classes is called base class and the class
which accepts properties from the other class is called derived class.
The main advantage of inheritance is code reusability.
The following are the types of inheritance
a) Single level inheritance
b) Multi-level inheritance
c) Multiple inheritance
d) Hybrid inheritance
e) Hierarchical inheritance
Polymorphism (4M)
Poly means many and morph means forms. So the ability to make more than one form
is called polymorphism.
It is used in inheritance programs.
It can be divided as two ways
a) Static polymorphism ( Compile-time polymorphism )
b) Dynamic polymorphism ( Run-time polymorphism )
The following diagram represents that a single function name can be used for different
purposes with different types of arguments.
Shape
area ( )
4
R16
JAVA Unit-1
5
R16
JAVA Unit-1
Applications of OOP
3Q: Discuss the applications of OOPS. (3M) (OR)
List and explain the applications of OOPs. (8M)
Mobile computing.
Real time systems.
Neural networks.
Image processing.
Artificial intelligence.
Web based applications.
Database management.
Business process re-engineering.
Enterprise resource planning.
Data warehousing and data mining.
History of java
4Q: Briefly give the history of JAVA.
Java language was introduced by James Gosling at Sun Microsystems.
Java was invented in 1991. Initially, Java language was referred as “Oak” and later
renamed as Java in 1995.
The primary motive of Java language was to prepare software that can be embedded in
different computer applications.
Gosling and others stared working on portable and cross-platform language which
results software that can be executed on different CPU’s under various environments.
This leads to the invention of Java.
In the initial stage of Java, an important factor World Wide Web (WWW) has not
taken during the implementation of Java.
But in 1993, the focus of Java is shifted to internet programming due to the occurrence
of portability problems during the creation of code for the internet.
Java can be inherited from the syntax of C and object oriented concepts are from C++.
Hence, it is easy to learn Java when one is familiar with C or C++. So, Java was
implemented for internet programming using C++ concepts.
6
R16
JAVA Unit-1
JVM
5Q: Discuss about Java Virtual Machine (JVM) (6M) (OR)
What is the role and responsibility of JVM in program execution? (6M)
Define java byte code. Why java generates byte code? (8M) (OR)
What is the significance of Java’s byte code? (3M) (OR)
What is byte code? How it will be generated? (3M) (OR)
"Java is called Machine Independent language" - Justify this statement with proper
explanation. (8M)
Java Virtual Machine (JVM) is the most important part of java technology.
JVM and Java API together, form a platform for all java programs to run.
JVM and Java API is known as Java Runtime Environment (JRE).
Java provides both compiler and a software machine called Java Virtual Machine
(JVM) for each computer machine.
The java compiler translates java source code into an intermediate code known as byte
code which executes on a special type of machine. This machine is called Java Virtual
Machine and exists only inside the computer memory.
Java interpreter reads byte code and translates into a language that the computer can
understand and it can execute the code in any system.
JVM loads the java classes, verifies the byte code, interprets and executes it.
Additionally, it provide functions like security management and garbage collection.
7
R16
JAVA Unit-1
Class Loader
It performs loading of classes and interfaces into JVM. When a program attempts to
invoke a method of certain class, then JVM checks whether that class is already loaded or
not. If not, JVM uses class loader to load the binary representation of that class.
Byte code verifier
After loading the class, byte code verifier checks whether the loaded representation
is well-formed, whether it follows the semantic requirements of java programming
language and JVM. It also checks whether the code contains proper symbol table or not. If
a problem occurs during verification, then an error is thrown.
Runtime data areas
These are special memory areas which JVM maintains to store temporarily byte
codes and other information like loaded class files, objects, parameters to methods, return
values, local variables and results etc.,
Execution engine
It is responsible for executing instructions contained in the methods of loaded
classes.
Native method interface
If any java program calls a non-java API method or platform-specific native
method then, the code of these native methods is obtained from underlying OS through the
use of native method interface.
8
R16
JAVA Unit-1
Java features
6Q: Briefly explain the features or properties of JAVA (8M) (OR)
List various types of statements and quote suitable examples for each type. (9M) (OR)
Java was used for internet applications. Why? (4M)
Support the statement “java byte code gives high performance”. (4M)
Support the statement “java is dynamic”. Discuss. (4M)
Support the statement “java is Architecture-Neutral” (4M)
Support the statement “java is robust”. Discuss. (4M)
9
R16
JAVA Unit-1
In the first stage, java compiler translates source code into byte code instructions. But
byte code instructions are not machine instructions.
So, java interpreter generates machine code in the second stage which can be directly
executed by the machine which is running the java program.
Hence, java is not only a compiled but also an interpreted language.
iii) Platform independent and portable (or) Architecture-neutral (4M)
Java supports portability. Ie java programs can be moved from only system to another,
anywhere and anytime easily.
Changes and upgrades in processors and operating system will not force any changes in
java programs.
Java programs can run on any platform.
iv) Distributed
Java is distributed language.
It not only has the ability to share data but also programs.
Java applications can open and access remote objects on internet very easily.
This enables many programmers placing at different locations to work on a single
project.
v) Robust and secure (4M)
Java provides many safeguards in order to ensure reliable code.
Java has strict compile time and run time checking for data types and it also
incorporates the concept of exception handling that captures errors and eliminates the
risk of system crash.
Hence java is said to be robust language.
For a language which is used for programming on internet, security is very important.
Java not only verifies the memory access but also ensures no viruses communicate with
an applet.
vi) Familiar, simple and small
Java is familiar language. It is modeled on C and C++ languages.
Java uses several features of C and C++ and therefore java code looks like a C++ code.
Java is simplified version of C++.
10
R16
JAVA Unit-1
Program structure
7Q: Explain the general syntax of writing an application program in Java. Also explain the
steps to run an application Java program. (OR)
How do you write a Java program? Explain compilation and execution procedure with
example. (OR)
Explain the Java program structure. (8M) (OR)
Discuss the lexical issues of Java.(6M)
A java program consists of one or more classes. Only one of these classes defines the
main( ) method. The class consists of data and methods that operate on the data of a class.
11
R16
JAVA Unit-1
Import statement
Interface statement
Class definitions
Documentation
This section consists of a set of comments about the program. This is suggested and
it is optional.
Package statement
This is the first statement in every java program, if needed. This statement tells the
compiler that the classes defined here belongs to this package. This statement is optional.
Import statement
The import statement tells the interpreter to include the classes from the package
defined. This is the next statement after the package declaration but should be written
before defining a class. There may be number of import statements. This statement is
optional. For example,
import java.io.*;
Interface statement
The interface statement defines method declaration without body for the subclasses.
This is optional. It is used in inheritance programs.
Class definition
This section consists of a number of class definitions where each class consists of
data members and methods. This is optional.
12
R16
JAVA Unit-1
13
R16
JAVA Unit-1
At this stage, java compiler translates the java program into byte code which is
understood by java interpreter.
If the program compiles correctly, a file called Filename.class is created. This is the file
containing byte code that will interpret during the execution of a program. For
example, after compilation of Simple.java program, Simple.class file is created.
Java interpreter reads byte code and translates into a language that the computer can
understand and it can execute the code with the following command.
Syntax: java Filename
Eg: java Simple
14
R16
JAVA Unit-1
Variables
9Q: What is a variable? Explain the declaration and initialization of variables.
Variable:
Variable is an identifier which is used to store the value and it can be changed
during the execution of a program.
Declaration of variables
Syntax:
datatype variable-name;
Example:
int k;
Morethan one variables of the same data type can be declared by using comma. For
example,
int a,b,c;
Initialization of variables
Initialization of variable can be defined as a process of assigning a value to the variable.
This can be done directly during the declaration of a variable or after the declaration of
variable.
Syntax:
datatype variable-name=value; (OR)
datatype variable-name;
variable-name=value;
Example:
int k=10; (OR)
int k;
k=10;
Multiple variables that are declared with similarly type can be initialized
simultaneously. This can be done by using comma operator.
Example:
int a,b,c,k=0;
15
R16
JAVA Unit-1
16
R16
JAVA Unit-1
i) Integers
The integer types are the numbers without fractional part. The following are the four
integer types:
a) byte
b) short
c) int
d) long
All these are signed, positive and negative values. Java does not support unsigned data
types.
a) byte :
It is the smallest integer type. It occupies one byte in memory.
Syntax: byte var-name;
Example: byte b;
b) short :
It occupies 2 bytes in memory.
Syntax: short var-name;
Example: short s;
c) int :
It occupies 4 bytes in memory.
Syntax: int var-name;
Example: int i;
d) long :
It occupies 8 bytes in memory.
Syntax: long var-name;
Example: long l;
ii) Floating point numbers
When we want to hold numbers containing fractional part, we use floating point
numbers. There are two types of floating points. They are
a) float
b) double
17
R16
JAVA Unit-1
a) float :
It specifies a single precision value which uses 32 bits of storage. For example, 10.25
Syntax: float var-name;
Example: float f;
b) double :
It specifies double precision value which uses 64 bits of storage. It is the good choice
when we need to maintain accuracy over many iterative calculations or manipulating
large valued numbers.
Syntax: double var-name;
Example: double d;
iii) Characters
It is used to store characters. It occupies 2 bytes in memory.
Syntax: char var-name;
Example: char ch;
iv) Boolean :
It is used for logical values. It has only one of the two possible values, true or false.
Default value is false. It uses only one byte of storage.
Syntax: boolean var-name;
Example: boolean k;
Identifiers
11Q: Briefly discuss about Java identifiers. (OR)
What are the naming conventions for java identifiers? (4M)
Identifier is the name given to the variables, class, methods, objects, packages. It is the
sequence of characters which contain alphabets, digits, underscore and dollar sign. Length
of the variable name is not limited.
The following are the rules for identifiers:
It should begin with a letter or underscore.
For example: total, _total
18
R16
JAVA Unit-1
Literals
13Q: Discuss about literals in Java.
There are five types of literals in Java.
i) Integer literals.
ii) Floating point literals.
iii) Boolean literals.
iv) Character literals.
v) String literals.
19
R16
JAVA Unit-1
i) Integer literal
Integer may be decimal, octal and hexadecimal value.
Decimal numbers have base 10 and they do not have leading zeros. For example, 1, 55.
Octal numbers have base 8 and they range from 0 to 7. They are denoted by a leading
zero. For example, 00, 05, 07.
Hexadecimal numbers have base 16 and they range from 0 to 15. The hexadecimal
numbers from 10 to 15 are represented by alphabets A to F respectively.
ii) Floating point literal
The numbers that contains a decimal value followed by a fraction component is called
floating point literal.
It can be expressed in two notations:
a) Standard notation: It represents the floating point literal in the form of whole
number component and a fractional component separated by decimal point.
For example, 10 . 75
20
R16
JAVA Unit-1
v) String literals
It consists of sequence of characters enclosed within double quotes. For example,
“JAVA”
Operators
14Q: Discuss operators in Java. (8M)
Operators are used in the expressions to perform operations on the operands. Java
provides various operators and they are classified into three types. They are,
A) Unary operators.
B) Binary operators.
C) Ternary operator.
A) Unary operators:
Unary operators perform operations on a single operand. The various types of
unary operators are as follows:
i) ++ ( Increment ) : The ++ is an operator that adds the value 1 to its operand (same as
a=a+1). It can be applied in two ways:
a) Pre-Increment – If the operand is preceded by increment operator, then it is said
to be pre-increment. For example, ++a.
b) Post-Increment – If the operand is succeeded by increment operator, then it is
said to be post-increment. For example, a++.
ii) - - ( Decrement ) : The - - is an operator that subtracts the value 1 from its operand
(same as a=a-1). It can be applied in two ways:
a) Pre-decrement – If the operand is preceded by decrement operator, then it is said
to be pre-decrement. For example, - - a.
b) Post-decrement – If the operand is succeeded by decrement operator, then it is
said to be post-decrement. For example, a- -.
21
R16
JAVA Unit-1
B) Binary operators:
Binary operators perform operations on two operands. The various types of binary
operands are as follows:
i) Arithmetic operators – The operators that can perform arithmetic operations are called
arithmetic operators.
The following are the arithmetic operators:
Operator Meaning
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulus
ii) Relational operators – The operators that can perform comparisons between two
operands are called relational operators.
The following are the relational operators:
Operator Meaning
< Less than
<= Less than or equal to
> Greater than
>= Greater than or equal to
== Equal to
!= Not equal to
iii) logical operators – The operators than can perform logical operations between two
operands are called logical operators.
The following are the logical operators:
Operator Meaning
&& Logical AND
|| Logical OR
! Logical NOT
22
R16
JAVA Unit-1
23
R16
JAVA Unit-1
24
R16
JAVA Unit-1
In the above table, the operators are listed from highest precedence to lowest precedence.
In the second column, L -> R indicates left to right associativity and R -> L indicates right
to left associativity.
25
R16
JAVA Unit-1
Type casting
Def:-
Type casting is an explicit conversion of one type of value into another type. Simply,
the data-type is stated using parenthesis before the value or expression.
Type casting in java must follow the given rules:
i) Type casting cannot be performed on Boolean variables.
ii) Type casting of integer data-type into any other data-type is possible. But, if the
casting into smaller type is performed, it results in loss of data.
iii) Type casting of floating point type into integer type is possible, but with loss of data.
iv) Type casting of char type into integer type is possible, but with loss of data.
The general form of type casting is as follows:
variable = (data-type) variable or expression;
For example, consider that there are two integer variables namely a=2, b=3. To
perform b/a, actual result is 1.5. But the java compiler gives the result of b/a as integer,
discarding the decimal values. Hence, type conversion is necessary to produce accurate
results.
int a,b;
float c;
a=2, b=3;
c = (float) b/a; // output is 1.5
26
R16
JAVA Unit-1
Flow control
17Q: Explain control structures in JAVA.
The following are the control structures in Java:
1) if (simple if)
2) if-else
3) else if Conditional or Branching statements
4) nested if
5) switch
6) while
7) do-while Looping statements
8) for
9) break
10) continue
1) if statement ( simple if )
It is used to check only one condition in a program. Ie only true condition.
Syntax:
if(condition)
statements;
If the condition is true, then the corresponding statements will be executed.
Flowchart:
condition
statements
exit
27
R16
JAVA Unit-1
Example:
if(x > y)
System.out.println(“x is big”);
2) if-else statement
It is used to check two conditions in a program.
Syntax:
if(condition)
statement1;
else
statement2;
If the condition is true, then statement1 will be executed. Otherwise, statement2 will be
executed.
Flowchart:
condition
F T
statement2 statement1
exit
Example:
if( x > y )
System.out.println("x is greater than y");
else
System.out.println("y is greater than x");
28
R16
JAVA Unit-1
3) else-if statement
It is used to check multiple conditions in a program. Three conditions are
preferable.
Syntax:
if( condition1 )
statement1;
else if( condition2 )
statement2;
else
statement3;
If the condition1 is true, then statement1 will be executed. If fails, condition2 is checked. If
it is true, then statement2 will be executed. If fails, statement3 will be executed.
Flowchart:
condition1
F T
statement1
condition2
F T
statement3 statement2
exit
29
R16
JAVA Unit-1
Example:
if ( x > y && x > z )
System.out.println("x is biggest");
else if ( y > z )
System.out.println("y is biggest");
else
System.out.println("z is biggest");
4) nested if statement
Writing an if statement within another if statement is known as nested if. It is
essential in programming since they yield a follow-up selection depending on the result of
previous selection.
Syntax:
if( condition1 )
if( condition2 )
statement1;
else if( condition3 )
statement2;
else
statement3;
First condition1 is checked. If it is true, then condition2 is checked. If both the conditions
are true, only then statement1 is executed. If the condition3 is true, then statement2 is
executed otherwise, statement3 will be executed.
Example:
if ( x > y )
if ( x > z )
System.out.println("x is biggest");
else if ( y > z )
System.out.println("y is biggest");
else
System.out.println("z is biggest");
30
R16
JAVA Unit-1
Flowchart:
condition1
condition2
F T
statement1
condition3
F T
Statement3 Statement2
exit
5) switch statement
It is called as multi-way branching statement. It is used for checking multiple
conditions or cases in a program, provides multiple alternatives and the user can select the
required option. The break statement is used for immediate exit from the switch statement.
If all the conditions are failed to execute, then default condition will be executed.
Syntax:
switch( variable )
{
case 1:
statement1;
break;
31
R16
JAVA Unit-1
case 2:
statement2;
break;
…
…
default:
statement n;
}
Flowchart:
case 2 T break
statement2
……..
default statement1
exit
32
R16
JAVA Unit-1
Example:
for( int i=1; i <= 7; i++ )
{
switch ( i )
{
case 1:
System.out.println(“Sunday”);
break;
case 2:
System.out.println(“Monday”);
break;
case 3:
System.out.println(“Tuesday”);
break;
case 4:
System.out.println(“Wednesday”);
break;
case 5:
System.out.println(“Thursday”);
break;
case 6:
System.out.println(“Friday”);
break;
case 7:
System.out.println(“Saturday”);
break;
default:
System.out.println(“wrong selection”);
}
}
33
R16
JAVA Unit-1
6) while loop
It will be executed repeatedly as long as the condition remains true. Before
executing body of the loop, the condition is checked whether it is true or not. Hence, it is
called pre-testing loop. If condition is true, then body of the loop will be executed, till the
condition becomes false. Otherwise, body of the loop is not executed.
Syntax:
while( condition )
{
// body of the loop;
}
Flowchart:
condition
F
T
exit
body of the loop
Example:
while ( i<= 10 )
{
System.out.println(+i);
i++;
}
34
R16
JAVA Unit-1
7) do-while loop
It is similar to that of while loop except that it is executed at least once. So it is called
as post-testing loop. The test of condition for repeating is done after each time boy of loop is
executed.
Syntax:
do
{
// body of loop;
} while ( condition );
Flowchart:
condition
F
T
exit
Example:
do
{
System.out.println(+i);
i++;
}while(i<=10);
35
R16
JAVA Unit-1
8) for loop
It is a flexible control structure. The length of source code can be reduced by using
“for” loop. The body of the loop is executed repeatedly till the condition is false.
Syntax:
for( initialization ; condition ; incr/decr )
{
// body of loop;
}
It contains three sections. Initialization section consists of beginning value which is assigned
to the variable. Condition section species when should be the condition gets failed. Third
section specifies increment or decrement value to the variable.
Flowchart:
initialization
condition
F
T
exit
body of the loop
incr/decr
Example:
for( int i = 1; i <= 10; i ++ )
System.out.println( +i );
36
R16
JAVA Unit-1
9) break
It is a reserve keyword. It can be used not only in switch statement but also in any
type of control structures. It is used for immediate exit from the switch statement or
iteration.
For example,
n=10;
for( int i=0; i<n; i++ )
{
b = i * i;
if( b >= n )
break;
System.out.println(+b);
}
10) continue
It is a reserve keyword. It can be used in any type of control structure. Incontrast to
the break statement, the continue statement does not exist from the loop but transfers the
control to the testing condition.
For example,
int x=0;
while( x < 15 )
{
if( (x % 2)!= 0)
continue;
System.out.println(+x);
x++;
}
37
R16
JAVA Unit-1
Classes and Objects, class declaration, creating objects, methods, constructors and
constructor overloading, Garbage collector, importance of static keyword, this keyword,
arrays, command line arguments, nested classes or inner classes.
Classes
1Q: What is class? Write the general form of a class with example.
Class
A class can be defined as a template that groups data and its associated functions.
The class contains two parts namely
a) Declaration of data members (variables).
b) Declaration of member functions.
The data members of a class explain about the state of the class and the member
functions explain about the behavior of the class.
There are three types of variables for a class. They are
a) Local variables – variables declared inside the methods.
b) Instance variables – variables declared inside the class, but outside the methods.
c) Class variables – variables declared inside the class with static keyword and they
placed outside of the method.
General form of a class
A class is declared using “class” keyword followed by name of the class.
Syntax
class class-name
{
//instance variables
datatype var;
…
//class variables
static datatype var;
datatype method1(args-list)
{
//local variables
datatype var;
…
An object is the representative of class.
1
R16
JAVA Unit-1
2
R16
JAVA Unit-1
Inheritance
Acquiring or getting properties from base class to the derived class is called as
inheritance.
The class which gives properties to the other classes is called base class and the class
which accepts properties from the other class is called derived class.
The main advantage of inheritance is code reusability.
The following are the types of inheritance
f) Single level inheritance
g) Multi-level inheritance
h) Multiple inheritance
i) Hybrid inheritance
j) Hierarchical inheritance
Polymorphism (4M)
Poly means many and morph means forms. So the ability to make more than one form
is called polymorphism.
It is used in inheritance programs.
It can be divided as two ways
c) Static polymorphism ( Compile-time polymorphism )
d) Dynamic polymorphism ( Run-time polymorphism )
The following diagram represents that a single function name can be used for different
purposes with different types of arguments.
Shape
area ( )
3
R16
JAVA Unit-1
4
R16
JAVA Unit-1
Applications of OOP
3Q: Discuss the applications of OOPS. (3M) (OR)
List and explain the applications of OOPs. (8M)
Mobile computing.
Real time systems.
Neural networks.
Image processing.
Artificial intelligence.
Web based applications.
Database management.
Business process re-engineering.
Enterprise resource planning.
Data warehousing and data mining.
History of java
4Q: Briefly give the history of JAVA.
Java language was introduced by James Gosling at Sun Microsystems.
Java was invented in 1991. Initially, Java language was referred as “Oak” and later
renamed as Java in 1995.
The primary motive of Java language was to prepare software that can be embedded in
different computer applications.
Gosling and others stared working on portable and cross-platform language which
results software that can be executed on different CPU’s under various environments.
This leads to the invention of Java.
In the initial stage of Java, an important factor World Wide Web (WWW) has not
taken during the implementation of Java.
But in 1993, the focus of Java is shifted to internet programming due to the occurrence
of portability problems during the creation of code for the internet.
Java can be inherited from the syntax of C and object oriented concepts are from C++.
Hence, it is easy to learn Java when one is familiar with C or C++. So, Java was
implemented for internet programming using C++ concepts.
5
R16
JAVA Unit-1
JVM
5Q: Discuss about Java Virtual Machine (JVM) (6M) (OR)
What is the role and responsibility of JVM in program execution? (6M)
Define java byte code. Why java generates byte code? (8M) (OR)
What is the significance of Java’s byte code? (3M) (OR)
What is byte code? How it will be generated? (3M) (OR)
"Java is called Machine Independent language" - Justify this statement with proper
explanation. (8M)
Java Virtual Machine (JVM) is the most important part of java technology.
JVM and Java API together, form a platform for all java programs to run.
JVM and Java API is known as Java Runtime Environment (JRE).
Java provides both compiler and a software machine called Java Virtual Machine
(JVM) for each computer machine.
The java compiler translates java source code into an intermediate code known as byte
code which executes on a special type of machine. This machine is called Java Virtual
Machine and exists only inside the computer memory.
Java interpreter reads byte code and translates into a language that the computer can
understand and it can execute the code in any system.
JVM loads the java classes, verifies the byte code, interprets and executes it.
Additionally, it provide functions like security management and garbage collection.
6
R16
JAVA Unit-1
Class Loader
It performs loading of classes and interfaces into JVM. When a program attempts to
invoke a method of certain class, then JVM checks whether that class is already loaded or
not. If not, JVM uses class loader to load the binary representation of that class.
Byte code verifier
After loading the class, byte code verifier checks whether the loaded representation
is well-formed, whether it follows the semantic requirements of java programming
language and JVM. It also checks whether the code contains proper symbol table or not. If
a problem occurs during verification, then an error is thrown.
Runtime data areas
These are special memory areas which JVM maintains to store temporarily byte
codes and other information like loaded class files, objects, parameters to methods, return
values, local variables and results etc.,
Execution engine
It is responsible for executing instructions contained in the methods of loaded
classes.
Native method interface
If any java program calls a non-java API method or platform-specific native
method then, the code of these native methods is obtained from underlying OS through the
use of native method interface.
7
R16
JAVA Unit-1
Java features
6Q: Briefly explain the features or properties of JAVA (8M) (OR)
List various types of statements and quote suitable examples for each type. (9M) (OR)
Java was used for internet applications. Why? (4M)
Support the statement “java byte code gives high performance”. (4M)
Support the statement “java is dynamic”. Discuss. (4M)
Support the statement “java is Architecture-Neutral” (4M)
Support the statement “java is robust”. Discuss. (4M)
8
R16
JAVA Unit-1
In the first stage, java compiler translates source code into byte code instructions. But
byte code instructions are not machine instructions.
So, java interpreter generates machine code in the second stage which can be directly
executed by the machine which is running the java program.
Hence, java is not only a compiled but also an interpreted language.
xii) Platform independent and portable (or) Architecture-neutral (4M)
Java supports portability. Ie java programs can be moved from only system to another,
anywhere and anytime easily.
Changes and upgrades in processors and operating system will not force any changes in
java programs.
Java programs can run on any platform.
xiii) Distributed
Java is distributed language.
It not only has the ability to share data but also programs.
Java applications can open and access remote objects on internet very easily.
This enables many programmers placing at different locations to work on a single
project.
xiv) Robust and secure (4M)
Java provides many safeguards in order to ensure reliable code.
Java has strict compile time and run time checking for data types and it also
incorporates the concept of exception handling that captures errors and eliminates the
risk of system crash.
Hence java is said to be robust language.
For a language which is used for programming on internet, security is very important.
Java not only verifies the memory access but also ensures no viruses communicate with
an applet.
xv) Familiar, simple and small
Java is familiar language. It is modeled on C and C++ languages.
Java uses several features of C and C++ and therefore java code looks like a C++ code.
Java is simplified version of C++.
9
R16
JAVA Unit-1
Program structure
7Q: Explain the general syntax of writing an application program in Java. Also explain the
steps to run an application Java program. (OR)
How do you write a Java program? Explain compilation and execution procedure with
example. (OR)
Explain the Java program structure. (8M) (OR)
Discuss the lexical issues of Java.(6M)
A java program consists of one or more classes. Only one of these classes defines the
main( ) method. The class consists of data and methods that operate on the data of a class.
10
R16
JAVA Unit-1
Import statement
Interface statement
Class definitions
Documentation
This section consists of a set of comments about the program. This is suggested and
it is optional.
Package statement
This is the first statement in every java program, if needed. This statement tells the
compiler that the classes defined here belongs to this package. This statement is optional.
Import statement
The import statement tells the interpreter to include the classes from the package
defined. This is the next statement after the package declaration but should be written
before defining a class. There may be number of import statements. This statement is
optional. For example,
import java.io.*;
Interface statement
The interface statement defines method declaration without body for the subclasses.
This is optional. It is used in inheritance programs.
Class definition
This section consists of a number of class definitions where each class consists of
data members and methods. This is optional.
11
R16
JAVA Unit-1
12
R16
JAVA Unit-1
At this stage, java compiler translates the java program into byte code which is
understood by java interpreter.
If the program compiles correctly, a file called Filename.class is created. This is the file
containing byte code that will interpret during the execution of a program. For
example, after compilation of Simple.java program, Simple.class file is created.
Java interpreter reads byte code and translates into a language that the computer can
understand and it can execute the code with the following command.
Syntax: java Filename
Eg: java Simple
13
R16
JAVA Unit-1
Variables
9Q: What is a variable? Explain the declaration and initialization of variables.
Variable:
Variable is an identifier which is used to store the value and it can be changed
during the execution of a program.
Declaration of variables
Syntax:
datatype variable-name;
Example:
int k;
Morethan one variables of the same data type can be declared by using comma. For
example,
int a,b,c;
Initialization of variables
Initialization of variable can be defined as a process of assigning a value to the variable.
This can be done directly during the declaration of a variable or after the declaration of
variable.
Syntax:
datatype variable-name=value; (OR)
datatype variable-name;
variable-name=value;
Example:
int k=10; (OR)
int k;
k=10;
Multiple variables that are declared with similarly type can be initialized
simultaneously. This can be done by using comma operator.
Example:
int a,b,c,k=0;
14
R16
JAVA Unit-1
15
R16
JAVA Unit-1
v) Integers
The integer types are the numbers without fractional part. The following are the four
integer types:
a) byte
b) short
c) int
d) long
All these are signed, positive and negative values. Java does not support unsigned data
types.
e) byte :
It is the smallest integer type. It occupies one byte in memory.
Syntax: byte var-name;
Example: byte b;
f) short :
It occupies 2 bytes in memory.
Syntax: short var-name;
Example: short s;
g) int :
It occupies 4 bytes in memory.
Syntax: int var-name;
Example: int i;
h) long :
It occupies 8 bytes in memory.
Syntax: long var-name;
Example: long l;
vi) Floating point numbers
When we want to hold numbers containing fractional part, we use floating point
numbers. There are two types of floating points. They are
a) float
b) double
16
R16
JAVA Unit-1
c) float :
It specifies a single precision value which uses 32 bits of storage. For example, 10.25
Syntax: float var-name;
Example: float f;
d) double :
It specifies double precision value which uses 64 bits of storage. It is the good choice
when we need to maintain accuracy over many iterative calculations or manipulating
large valued numbers.
Syntax: double var-name;
Example: double d;
vii) Characters
It is used to store characters. It occupies 2 bytes in memory.
Syntax: char var-name;
Example: char ch;
viii) Boolean :
It is used for logical values. It has only one of the two possible values, true or false.
Default value is false. It uses only one byte of storage.
Syntax: boolean var-name;
Example: boolean k;
Identifiers
11Q: Briefly discuss about Java identifiers. (OR)
What are the naming conventions for java identifiers? (4M)
Identifier is the name given to the variables, class, methods, objects, packages. It is the
sequence of characters which contain alphabets, digits, underscore and dollar sign. Length
of the variable name is not limited.
The following are the rules for identifiers:
It should begin with a letter or underscore.
For example: total, _total
17
R16
JAVA Unit-1
Literals
13Q: Discuss about literals in Java.
There are five types of literals in Java.
vi) Integer literals.
vii) Floating point literals.
viii) Boolean literals.
ix) Character literals.
x) String literals.
18
R16
JAVA Unit-1
19
R16
JAVA Unit-1
x) String literals
It consists of sequence of characters enclosed within double quotes. For example,
“JAVA”
Operators
14Q: Discuss operators in Java. (8M)
Operators are used in the expressions to perform operations on the operands. Java
provides various operators and they are classified into three types. They are,
D) Unary operators.
E) Binary operators.
F) Ternary operator.
D) Unary operators:
Unary operators perform operations on a single operand. The various types of
unary operators are as follows:
i) ++ ( Increment ) : The ++ is an operator that adds the value 1 to its operand (same as
a=a+1). It can be applied in two ways:
a) Pre-Increment – If the operand is preceded by increment operator, then it is said
to be pre-increment. For example, ++a.
b) Post-Increment – If the operand is succeeded by increment operator, then it is
said to be post-increment. For example, a++.
iii) - - ( Decrement ) : The - - is an operator that subtracts the value 1 from its
operand (same as a=a-1). It can be applied in two ways:
a) Pre-decrement – If the operand is preceded by decrement operator, then it is said
to be pre-decrement. For example, - - a.
b) Post-decrement – If the operand is succeeded by decrement operator, then it is
said to be post-decrement. For example, a- -.
20
R16
JAVA Unit-1
E) Binary operators:
Binary operators perform operations on two operands. The various types of binary
operands are as follows:
vi) Arithmetic operators – The operators that can perform arithmetic operations are
called arithmetic operators.
The following are the arithmetic operators:
Operator Meaning
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulus
vii) Relational operators – The operators that can perform comparisons between
two operands are called relational operators.
The following are the relational operators:
Operator Meaning
< Less than
<= Less than or equal to
> Greater than
>= Greater than or equal to
== Equal to
!= Not equal to
viii) logical operators – The operators than can perform logical operations between
two operands are called logical operators.
The following are the logical operators:
Operator Meaning
&& Logical AND
|| Logical OR
! Logical NOT
21
R16
JAVA Unit-1
22
R16
JAVA Unit-1
23
R16
JAVA Unit-1
In the above table, the operators are listed from highest precedence to lowest precedence.
In the second column, L -> R indicates left to right associativity and R -> L indicates right
to left associativity.
24
R16
JAVA Unit-1
Type casting
Def:-
Type casting is an explicit conversion of one type of value into another type. Simply,
the data-type is stated using parenthesis before the value or expression.
Type casting in java must follow the given rules:
v)Type casting cannot be performed on Boolean variables.
vi) Type casting of integer data-type into any other data-type is possible. But, if the
casting into smaller type is performed, it results in loss of data.
vii) Type casting of floating point type into integer type is possible, but with loss of data.
viii) Type casting of char type into integer type is possible, but with loss of data.
The general form of type casting is as follows:
variable = (data-type) variable or expression;
For example, consider that there are two integer variables namely a=2, b=3. To
perform b/a, actual result is 1.5. But the java compiler gives the result of b/a as integer,
discarding the decimal values. Hence, type conversion is necessary to produce accurate
results.
int a,b;
float c;
a=2, b=3;
c = (float) b/a; // output is 1.5
25
R16
JAVA Unit-1
Flow control
17Q: Explain control structures in JAVA.
The following are the control structures in Java:
1) if (simple if)
2) if-else
3) else if Conditional or Branching statements
4) nested if
5) switch
6) while
7) do-while Looping statements
8) for
9) break
10) continue
11) if statement ( simple if )
It is used to check only one condition in a program. Ie only true condition.
Syntax:
if(condition)
statements;
If the condition is true, then the corresponding statements will be executed.
Flowchart:
condition
statements
exit
26
R16
JAVA Unit-1
Example:
if(x > y)
System.out.println(“x is big”);
condition
F T
statement2 statement1
exit
Example:
if( x > y )
System.out.println("x is greater than y");
else
System.out.println("y is greater than x");
27
R16
JAVA Unit-1
condition1
F T
statement1
condition2
F T
statement3 statement2
exit
28
R16
JAVA Unit-1
Example:
if ( x > y && x > z )
System.out.println("x is biggest");
else if ( y > z )
System.out.println("y is biggest");
else
System.out.println("z is biggest");
14) nested if statement
Writing an if statement within another if statement is known as nested if. It is
essential in programming since they yield a follow-up selection depending on the result of
previous selection.
Syntax:
if( condition1 )
if( condition2 )
statement1;
else if( condition3 )
statement2;
else
statement3;
First condition1 is checked. If it is true, then condition2 is checked. If both the conditions
are true, only then statement1 is executed. If the condition3 is true, then statement2 is
executed otherwise, statement3 will be executed.
Example:
if ( x > y )
if ( x > z )
System.out.println("x is biggest");
else if ( y > z )
System.out.println("y is biggest");
else
System.out.println("z is biggest");
29
R16
JAVA Unit-1
Flowchart:
condition1
condition2
F T
statement1
condition3
F T
Statement3 Statement2
exit
30
R16
JAVA Unit-1
case 2:
statement2;
break;
…
…
default:
statement n;
}
Flowchart:
case 2 T break
statement2
……..
default statement1
exit
31
R16
JAVA Unit-1
Example:
for( int i=1; i <= 7; i++ )
{
switch ( i )
{
case 1:
System.out.println(“Sunday”);
break;
case 2:
System.out.println(“Monday”);
break;
case 3:
System.out.println(“Tuesday”);
break;
case 4:
System.out.println(“Wednesday”);
break;
case 5:
System.out.println(“Thursday”);
break;
case 6:
System.out.println(“Friday”);
break;
case 7:
System.out.println(“Saturday”);
break;
default:
System.out.println(“wrong selection”);
}
}
32
R16
JAVA Unit-1
Syntax:
while( condition )
{
// body of the loop;
}
Flowchart:
condition
F
T
exit
body of the loop
Example:
while ( i<= 10 )
{
System.out.println(+i);
i++;
}
33
R16
JAVA Unit-1
Syntax:
do
{
// body of loop;
} while ( condition );
Flowchart:
condition
F
T
exit
Example:
do
{
System.out.println(+i);
i++;
}while(i<=10);
34
R16
JAVA Unit-1
initialization
condition
F
T
exit
body of the loop
incr/decr
Example:
for( int i = 1; i <= 10; i ++ )
System.out.println( +i );
35
R16
JAVA Unit-1
19) break
It is a reserve keyword. It can be used not only in switch statement but also in any
type of control structures. It is used for immediate exit from the switch statement or
iteration.
For example,
n=10;
for( int i=0; i<n; i++ )
{
b = i * i;
if( b >= n )
break;
System.out.println(+b);
}
20) continue
It is a reserve keyword. It can be used in any type of control structure. Incontrast to
the break statement, the continue statement does not exist from the loop but transfers the
control to the testing condition.
For example,
int x=0;
while( x < 15 )
{
if( (x % 2)!= 0)
continue;
System.out.println(+x);
x++;
}
36
R16
JAVA Unit-1
Classes
1Q: What is class? Write the general form of a
class with example. Class
A class can be defined as a template that groups data and its associated
functions.
The class contains two parts namely
a) Declaration of data members (variables).
b) Declaration of member functions.
The data members of a class explain about the state of the class
and the member functions explain about the behavior of the class.
There are three types of variables for a class. They are
d) Local variables – variables declared inside the methods.
e) Instance variables – variables declared inside the class, but outside the
methods.
f) Class variables – variables declared inside the class with static
keyword and they placed outside of the method.
General form of a class
A class is declared using “class” keyword followed by name of the class.
Syntax
class class-name
{
//
i
n
st
a
n
c
e
v 37
a
ri
R16
JAVA Unit-1
a
b
le
s
d
a
t
a
t
y
p
e
v
a
r;
…
//cl
ass
va
ria
ble
s
sta
tic
da
tat
yp
e
va
r;
datatype method1(args-list)
{
/
/
l
o
c
a
l
v
a
r
i
a
b
l
38
e
s
R16
JAVA Unit-1
d
a
t
a
t
y
p
e
v
a
r
;
…
39