0% found this document useful (0 votes)
94 views76 pages

Introduction To OOP UNIT-1 RK

The document provides an introduction to Object-Oriented Programming (OOP) and Java, covering key concepts such as classes, objects, inheritance, encapsulation, and polymorphism. It discusses the differences between procedural and object-oriented programming, the history of Java, and the role of the Java Virtual Machine (JVM). Additionally, it outlines Java's features, applications, and program structure.

Uploaded by

manasaveena.t
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
94 views76 pages

Introduction To OOP UNIT-1 RK

The document provides an introduction to Object-Oriented Programming (OOP) and Java, covering key concepts such as classes, objects, inheritance, encapsulation, and polymorphism. It discusses the differences between procedural and object-oriented programming, the history of Java, and the role of the Java Virtual Machine (JVM). Additionally, it outlines Java's features, applications, and program structure.

Uploaded by

manasaveena.t
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 76

R16

JAVA Unit-1

Introduction to OOP, procedural programming languages and object oriented


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.

Introduction to OOP – Principle of OOP


1Q: Briefly explain the basic concepts of OOPS (OR)
Explain the need for object oriented programming (OR)
What is OOP? Explain the principles of object oriented programming languages (10M)
(OR) Give the characteristics of OOPs in detail.(8M) (OR)
Compare inheritance with polymorphism (4M)
Object Oriented Programming - Def
Object Oriented Programming is a technique that builds the program using the
objects along with a set of well defined interfaces. It describes the way in which elements
within a computer program must be organized and how these elements can interact with
each other. Object oriented programming uses bottom-up approach and also manages the
increasing complexity.
The following are the basic concepts of OOPS
1. Object
2. Class
3. Data abstraction
4. Encapsulation
5. Inheritance
6. Polymorphism
Object
 An object can be defined as an instance of the class which is used to access the members
of a class.
 An object is the real world entity.

Introduction to OOP, procedural programming languages and object oriented

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.

Introduction to OOP – Principle of OOP


1Q: Briefly explain the basic concepts of OOPS (OR)
Explain the need for object oriented programming (OR)
What is OOP? Explain the principles of object oriented programming languages (10M)
(OR) Give the characteristics of OOPs in detail.(8M) (OR)
Compare inheritance with polymorphism (4M)
Object Oriented Programming - Def
Object Oriented Programming is a technique that builds the program using the
objects along with a set of well defined interfaces. It describes the way in which elements
within a computer program must be organized and how these elements can interact with
each other. Object oriented programming uses bottom-up approach and also manages the
increasing complexity.
The following are the basic concepts of OOPS
7. Object
8. Class
9. Data abstraction
10. Encapsulation
11. Inheritance
12. Polymorphism
Object
 An object can be defined as an instance of the class which is used to access the members
of a class.
 An object is the real world entity.
 An object is the representative of class.

2
R16
JAVA Unit-1

 Syntax: class-name object-name;


 Eg: Student s;
 Here, Student is the class name and “ s “ is the object name.
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.
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 – declared inside the class.
b) Instance variables – declared inside the class but outside of the methods.
c) Class variables – declared inside the class with static modifier and they reside
outside of the method.
Data abstraction (3M)
 Representing the essential features without including its background details is called
data abstraction.
 It is the mechanism that hides the implementation details and shows only the
functionality.
Encapsulation
 Encapsulation is the mechanism of binding data members and corresponding methods
into a single module or class in-order to protect them from being accessed by the
outside code.
 The data and functions in a class are called as members of the class. The data defined in
the class are called data members and the functions defined are called member
functions.
 The main idea behind the concept of encapsulation is to obtain high maintenance and to
handle the application’s code.
 It is the most striking feature of the class.

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 ( )

Circle object Box object Triangle object


area ( ) area ( ) area ( )

4
R16
JAVA Unit-1

Procedural language and object oriented language


2Q: Discuss about Procedural languages Vs OOP (OR)
Differentiate between procedure oriented and object oriented programming (8M) (OR)
List the major differences between C and JAVA (OR)
Differentiate between structured programming and object oriented programming. (OR)
What are the problems with procedure languages? How object oriented languages
overcome the problems of procedural languages? (10M) (OR)
What are the drawbacks of procedural languages? Explain the need of object oriented
programming. (10M) (OR)
What is procedural language? Differentiate between procedural language and OOP.(8M)

Procedure oriented programming Object oriented programming


1. C is structured programming language. 1. JAVA is object oriented programming
language.
2. It supports top-down approach. 2. It supports bottom-up approach.
3. In this, set of functions/procedures are 3. In this, objects are used.
used to perform a task.
4. In this, data and functions are considered 4. In this, data and functions are
as different entities. encapsulated into a single entity called class.
5. It does not support features such as 5. It supports features such as inheritance,
inheritance, encapsulation and encapsulation and polymorphism.
polymorphism.
6. It is not user friendly. 6. It is user friendly.
7. Complexity in this is more. 7. Complexity in this is less.
8. It supports pointers. 8. It does not support pointers.
9. In this, header files are included. 9. In this, packages are imported.

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.

Source code Java compiler Byte code

 Java interpreter reads byte code and translates into a language that the computer can
understand and it can execute the code in any system.

Byte code Java interpreter Machine language

 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

 The following is the internal architecture of JVM

Class files Class loader Java API

Byte code verifier

Runtime data areas

Execution Native method Underlying


engine interface OS

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)

The following are the features of JAVA.


i. Object oriented
ii. Compiled and interpreted
iii. Platform independent and portable
iv. Distributed
v. Robust and secure
vi. Familiar, simple and small
vii. Multi-threaded and interactive
viii. Dynamic and extensible
ix. High performance
i) Object oriented
 Almost everything in JAVA is in terms of object.
 Complete program code and data placed within objects and classes.
 Java is said to be a true object oriented language.
 It comes with an extensive set of classes, packages which we can use in the programs by
inheritance.
 In Java, the object model is not only very simple but also very easy to extend.
ii) Compiled and interpreted
 Generally, a computer language will be either compiled or interpreted.
 But Java combines both these approaches.

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

 Java is not only small but also a simple language.


 Java does not use pointer, goto statement, operator overloading, multiple inheritance
etc.,
vii) Multithreaded and interactive
 Java supports multithreading ie., it is not necessary for an application to finish one task
before starting another. In this way, several tasks can handle simultaneously.
 The java run-time comes with tools which supports multiprocessor synchronization and
construct interactive systems running smoothly.
viii) Dynamic and extensible (4M)
 Java is a dynamic language which is capable of dynamically linking new class libraries,
methods and objects.
 Java also supports extensibility. It support functions written in other languages like C
and C++.
 This makes the programmers to use the efficient functions available in these languages.
ix) High performance (4M)
 Because of using intermediate byte code, java performance is excellent for an
interpreted language.
 In order to reduce overhead during runtime, java architecture is designed carefully.
 Multithreading improves overall execution speed of java programs.

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

Syntax: Documentation section


Package statement

Import statement

Interface statement

Class definitions

Main method class definition


{
main( ) method definition
}

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

Main method class


This is an essential section of a java program. Every java program must have a class
definition that defines the main( ) method. This is essential because main( ) is the starting
point for running java programs. The program terminates on reaching the end of the
main( ) method.
Example program
 JAVA program is typed in text editor (notepad) and make corrections if necessary.
 The program name is same as the class name and stores with extension .java in the
secondary storage device.
Syntax: Filename.java
Eg: Simple.java
 The starting letter of the class name will be the capital and same as program name. It is
the conventional rule in java.
For example,
class Simple
{
public static void main ( String args [ ] )
{
System.out.println(“Simple java program”);
}
}
 public is an access specifier, which defines who can access this method. Public means
that this method will be accessible by any class.
 static is a keyword which identifies the class related thing. This means the given method
or variable is not instance related but class related. It can be accessed without creating
the instance of a class.
 void is used to define the Return Type of the method. It defines what the method can
return. Void means the method will not return any value.
 main is the name of the method. This method name is searched by JVM as a starting
point for a program.
 For compilation, give the following command
Syntax: javac Filename.java
Eg: javac Simple.java

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

8Q: Explain about Installation of JDK 1.6


JDK means Java Development Kit. JDK is a collection of classes, java compiler and
java virtual machine interpreter.
Installation of JDK 1.6
 Run the installation process by double clicking on jdk 1.6.exe
 A window is displayed showing the license. Click on Accept. A custom setup dialog is
shown.
 Click on Next to install the JDK. This will display JRE custom setup dialog.
 Click on Next to install JRE. (Java Runtime Environment)
 After the completion of the installation, click on Finish button.
Configuration of JDK 1.6
 Right click on MyComputer icon. This will display a context menu.
 Select properties from the context menu. This will show environment variables window.
 Select PATH from the user variables section and click on Edit if PATH is user variable
already. Otherwise, click on New to enter new user.
 A window shown empty fields for variable name and variable value. Type PATH in
variable name and C:\ProgramFiles\jdk1.6\bin;
 Click on OK.
Testing the installation
 Open the command prompt.
 Type javac and then press enter to test whether java software is available or not.

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

Dynamic initialization of variable


 In Java, it is possible to initialize the variables dynamically. Instead of using two step
process i.e. declaring variable first and then initializing. We can combine these two
steps into one.
 The following is the example for dynamic initialization of variables:
//program to read two integers and print sum
class Sum
{
public static void main(String [ ] args)
{
int a,b,sum;
a=Integer.parseInt(args[0]);
b=Integer.parseInt(args[1]);
sum=a+b;
System.out.println("sum of a and b="+sum);
}
}
javac Sum.java (for compilation)
java Sum 10 20 (for execution)
 In the above example, the variables “a” and “b” are initialized dynamically. After
compilation and execution, value of sum is 30.

Primitive data types


10Q: List the primitive data types of Java. Explain each of them in detail. (8M)
Java supports eight types of primitive data types which are grouped into four types
as shown below:
i) Integers
ii) Floating point numbers
iii) Characters
iv) Boolean

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

 It should not begin with a digit.


For example: 007 is invalid
 It is case sensitive.
For example: TOTAL is not same as total
 It should not be a reserve keyword
For example: int int; is invalid.
int k; is valid.
 It should not contain any spaces. Use underscore symbol to join two words.
For example: int total amount; is invalid.
int total_amout; is valid.
12Q: List out different keywords in Java (OR) Java Buzzwords (8M)
abstract default Do case import
continue goto if enum static
for package private try void
new synchronized this final class
switch boolean break char finally
assert instanceof public interface native
double return throws float while
implements transient catch short long
protected byte extends strictfp volatile
throw else int const super

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

whole number decimal point fractional part


b) Scientific notation: It consists of a standard floating point number followed by
suffix. Suffix specifies a power of 10 by which the number should be multiplied. The
exponent is denoted by either E or e followed by negative or positive decimal
number. For example, 7.324E32, 3e+1000. In java, the default float literal is double.
iii) Boolean literal
 Boolean literal can take only two logical values “true” or “false”. Both of them cannot
be converted to numerical representation. Default value is “false”.
iv) Character literals
 In java, character literals are indices into the Unicode character set. These literals are
represented within single quotes.
 They use \ (slash) for entering the ASCII characters which cannot be entered directly
such as newline character ‘\n’ and tab character ‘\t’.
 They allow us to enter value of character in both octal and hexadecimal notation. For
example, octal notation is ‘\141’ and hexadecimal notation is ‘\u0061’.

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

iv) Assignment operators - An assignment operator can be defines as an operator which


assigns a value to the variable or operand. The syntax is
variable-name=value;
k=10;
v) Bitwise operators – Bitwise operators can manipulate the set of bits associated with the
operands. These can be applied to integer and character type values and cannot be applied
to floating point and Boolean type values.
Operator Meaning
& Bitwise AND
| Bitwise OR
^ Bitwise exclusive OR
~ One’s complement
<< Left shift
>> Right shift

v) Special operators - The special operators of java are


 Instanceof operator – It can be defined as an object reference operator which returns
true when the left hand side value is an instance of the class which is given on the right
hand side. Simply, this operator is used to find that object in left hand side belongs to
specified class or not.
For example: student instanceof BTech
If student belongs to that class BTech, then it returns true otherwise returns false.
 Dot operator – It can be defined as an operator which accesses the instance methods
and data of a class. The dot operator can be represented as “ . “
For example: Student s;
s.getdata( );
C) Ternary operator
It performs operation on three operands. It is also called as conditional operator.
The following is the syntax:
condition ? expr1 : expr2;
eg: a > b ? a : b;
It means, if the condition is true then “ a “ is big. Otherwise “ b “ is big.

23
R16
JAVA Unit-1

Expressions – precedence rules and associativity


15Q: What is an expression? Explain about precedence rules and associativity. (8M) (OR)
Write the table that shows the precedence of operators in java. (3M)
Expression
An expression can be defined as combination of operators, variables and constants.
For example, c=a+b;
c=5;
Precedence and associativity
 If an expression contains two operands with different precedence, then the order of
their evaluation is determined using precedence rules.
 If an expression contains two operands with same precedence, then their order of
evaluation is determined using associativity rules.
 There are two types of associativity rules names left associativity and right associativity.
 The left associativity determines the operators to be evaluated from left to right.
 The right associativity determines the operators to be evaluated from right to left.
 Precedence and associativity override each other using parenthesis.
 The below tables explains the associativity of the operators:
Operators Associativity
. , [ ], ( ), i++, i- - L -> R
++i, - - i, ~ , ! R -> L
new, (type) R -> L
*,/,% L -> R
+,- L -> R
<< , >> L -> R
< , > , < = , > =, instanceof Non associative
= = , != L -> R
& L -> R
^ L -> R
| L -> R
&& L -> R
|| L -> R
?: R -> L

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.

Primitive Type Conversion and Casting


16Q: Explain Primitive type conversion and casting with examples. (8M) (OR)
Describe about type conversion. Also explain how casting is used to perform type
conversion between incompatible types.
Type conversion
Def:-
Type conversion refers to the conversion of data from one data type into another
data type.
 It is one of the most important aspects of java programming.
 Consider an example for type conversion,
int x;
float y;
x=5;
y=x; // integer value 5 is assigned to float. Output is 5.00
 If compatible types are assigned to variables, the right-hand side expression is assigned
directly to the left hand side expression.
 But it is not possible to convert all data types since java support strict type checking.
 Similarly, all implicit type conversions are not supported.
 An automatic type conversion can be done only if the following conditions are satisfied:
i) The data type of the variable and value must be compatible.
ii) The data type of left-hand side must be large in size compared to the right-hand side.
 The int data-type can hold byte, short values since it is higher than these types, whereas
long values cannot be assigned to int.
 The integer types and floating point types are compatible with each other.
 Numeric types cannot be compatible with Boolean or char. Similarly, char and Boolean
are also compatible.

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 1 T statement1 break

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:

body of the loop

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

 Syntax: class-name object-name;


 Eg: Student s;
 Here, Student is the class name and “ s “ is the object name.
Class
 A class can be defined as a template that groups data and its associated functions.
 The class contains two parts namely,
c) Declaration of data members.
d) 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 – declared inside the class.
e) Instance variables – declared inside the class but outside of the methods.
f) Class variables – declared inside the class with static modifier and they reside
outside of the method.
Data abstraction (3M)
 Representing the essential features without including its background details is called
data abstraction.
 It is the mechanism that hides the implementation details and shows only the
functionality.
Encapsulation
 Encapsulation is the mechanism of binding data members and corresponding methods
into a single module or class in-order to protect them from being accessed by the
outside code.
 The data and functions in a class are called as members of the class. The data defined in
the class are called data members and the functions defined are called member
functions.
 The main idea behind the concept of encapsulation is to obtain high maintenance and to
handle the application’s code.
 It is the most striking feature of the class.

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 ( )

Circle object Box object Triangle object


area ( ) area ( ) area ( )

3
R16
JAVA Unit-1

Procedural language and object oriented language


2Q: Discuss about Procedural languages Vs OOP (OR)
Differentiate between procedure oriented and object oriented programming (8M) (OR)
List the major differences between C and JAVA (OR)
Differentiate between structured programming and object oriented programming. (OR)
What are the problems with procedure languages? How object oriented languages
overcome the problems of procedural languages? (10M) (OR)
What are the drawbacks of procedural languages? Explain the need of object oriented
programming. (10M) (OR)
What is procedural language? Differentiate between procedural language and OOP.(8M)

Procedure oriented programming Object oriented programming


10. C is structured programming language. 10. JAVA is object oriented programming
language.
11. It supports top-down approach. 11. It supports bottom-up approach.
12.In this, set of functions/procedures are 12. In this, objects are used.
used to perform a task.
13. In this, data and functions are 13. In this, data and functions are
considered as different entities. encapsulated into a single entity called class.
14. It does not support features such as 14. It supports features such as
inheritance, encapsulation and inheritance, encapsulation and
polymorphism. polymorphism.
15. It is not user friendly.
16. Complexity in this is more. 15. It is user friendly.
17. It supports pointers. 16. Complexity in this is less.
18. In this, header files are included. 17. It does not support pointers.
18. In this, packages are imported.

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.

Source code Java compiler Byte code

 Java interpreter reads byte code and translates into a language that the computer can
understand and it can execute the code in any system.

Byte code Java interpreter Machine language

 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

 The following is the internal architecture of JVM

Class files Class loader Java API

Byte code verifier

Runtime data areas

Execution Native method Underlying


engine interface OS

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)

The following are the features of JAVA.


x. Object oriented
xi. Compiled and interpreted
xii. Platform independent and portable
xiii. Distributed
xiv. Robust and secure
xv. Familiar, simple and small
xvi. Multi-threaded and interactive
xvii. Dynamic and extensible
xviii. High performance
x) Object oriented
 Almost everything in JAVA is in terms of object.
 Complete program code and data placed within objects and classes.
 Java is said to be a true object oriented language.
 It comes with an extensive set of classes, packages which we can use in the programs by
inheritance.
 In Java, the object model is not only very simple but also very easy to extend.
xi) Compiled and interpreted
 Generally, a computer language will be either compiled or interpreted.
 But Java combines both these approaches.

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

 Java is not only small but also a simple language.


 Java does not use pointer, goto statement, operator overloading, multiple inheritance
etc.,
xvi) Multithreaded and interactive
 Java supports multithreading ie., it is not necessary for an application to finish one task
before starting another. In this way, several tasks can handle simultaneously.
 The java run-time comes with tools which supports multiprocessor synchronization and
construct interactive systems running smoothly.
xvii) Dynamic and extensible (4M)
 Java is a dynamic language which is capable of dynamically linking new class libraries,
methods and objects.
 Java also supports extensibility. It support functions written in other languages like C
and C++.
 This makes the programmers to use the efficient functions available in these languages.
xviii) High performance (4M)
 Because of using intermediate byte code, java performance is excellent for an
interpreted language.
 In order to reduce overhead during runtime, java architecture is designed carefully.
 Multithreading improves overall execution speed of java programs.

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

Syntax: Documentation section


Package statement

Import statement

Interface statement

Class definitions

Main method class definition


{
main( ) method definition
}

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

Main method class


This is an essential section of a java program. Every java program must have a class
definition that defines the main( ) method. This is essential because main( ) is the starting
point for running java programs. The program terminates on reaching the end of the
main( ) method.
Example program
 JAVA program is typed in text editor (notepad) and make corrections if necessary.
 The program name is same as the class name and stores with extension .java in the
secondary storage device.
Syntax: Filename.java
Eg: Simple.java
 The starting letter of the class name will be the capital and same as program name. It is
the conventional rule in java.
For example,
class Simple
{
public static void main ( String args [ ] )
{
System.out.println(“Simple java program”);
}
}
 public is an access specifier, which defines who can access this method. Public means
that this method will be accessible by any class.
 static is a keyword which identifies the class related thing. This means the given method
or variable is not instance related but class related. It can be accessed without creating
the instance of a class.
 void is used to define the Return Type of the method. It defines what the method can
return. Void means the method will not return any value.
 main is the name of the method. This method name is searched by JVM as a starting
point for a program.
 For compilation, give the following command
Syntax: javac Filename.java
Eg: javac Simple.java

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

8Q: Explain about Installation of JDK 1.6


JDK means Java Development Kit. JDK is a collection of classes, java compiler and
java virtual machine interpreter.
Installation of JDK 1.6
 Run the installation process by double clicking on jdk 1.6.exe
 A window is displayed showing the license. Click on Accept. A custom setup dialog is
shown.
 Click on Next to install the JDK. This will display JRE custom setup dialog.
 Click on Next to install JRE. (Java Runtime Environment)
 After the completion of the installation, click on Finish button.
Configuration of JDK 1.6
 Right click on MyComputer icon. This will display a context menu.
 Select properties from the context menu. This will show environment variables window.
 Select PATH from the user variables section and click on Edit if PATH is user variable
already. Otherwise, click on New to enter new user.
 A window shown empty fields for variable name and variable value. Type PATH in
variable name and C:\ProgramFiles\jdk1.6\bin;
 Click on OK.
Testing the installation
 Open the command prompt.
 Type javac and then press enter to test whether java software is available or not.

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

Dynamic initialization of variable


 In Java, it is possible to initialize the variables dynamically. Instead of using two step
process i.e. declaring variable first and then initializing. We can combine these two
steps into one.
 The following is the example for dynamic initialization of variables:
//program to read two integers and print sum
class Sum
{
public static void main(String [ ] args)
{
int a,b,sum;
a=Integer.parseInt(args[0]);
b=Integer.parseInt(args[1]);
sum=a+b;
System.out.println("sum of a and b="+sum);
}
}
javac Sum.java (for compilation)
java Sum 10 20 (for execution)
 In the above example, the variables “a” and “b” are initialized dynamically. After
compilation and execution, value of sum is 30.

Primitive data types


10Q: List the primitive data types of Java. Explain each of them in detail. (8M)
Java supports eight types of primitive data types which are grouped into four types
as shown below:
v) Integers
vi) Floating point numbers
vii) Characters
viii) Boolean

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

 It should not begin with a digit.


For example: 007 is invalid
 It is case sensitive.
For example: TOTAL is not same as total
 It should not be a reserve keyword
For example: int int; is invalid.
int k; is valid.
 It should not contain any spaces. Use underscore symbol to join two words.
For example: int total amount; is invalid.
int total_amout; is valid.
12Q: List out different keywords in Java (OR) Java Buzzwords (8M)
abstract default Do case import
continue goto if enum static
for package private try void
new synchronized this final class
switch boolean break char finally
assert instanceof public interface native
double return throws float while
implements transient catch short long
protected byte extends strictfp volatile
throw else int const super

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

vi) 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.
vii) 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

whole number decimal point fractional part


b) Scientific notation: It consists of a standard floating point number followed by
suffix. Suffix specifies a power of 10 by which the number should be multiplied. The
exponent is denoted by either E or e followed by negative or positive decimal
number. For example, 7.324E32, 3e+1000. In java, the default float literal is double.
viii) Boolean literal
 Boolean literal can take only two logical values “true” or “false”. Both of them cannot
be converted to numerical representation. Default value is “false”.
ix) Character literals
 In java, character literals are indices into the Unicode character set. These literals are
represented within single quotes.
 They use \ (slash) for entering the ASCII characters which cannot be entered directly
such as newline character ‘\n’ and tab character ‘\t’.
 They allow us to enter value of character in both octal and hexadecimal notation. For
example, octal notation is ‘\141’ and hexadecimal notation is ‘\u0061’.

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

ix) Assignment operators - An assignment operator can be defines as an operator which


assigns a value to the variable or operand. The syntax is
variable-name=value;
k=10;
x) Bitwise operators – Bitwise operators can manipulate the set of bits associated with the
operands. These can be applied to integer and character type values and cannot be applied
to floating point and Boolean type values.
Operator Meaning
& Bitwise AND
| Bitwise OR
^ Bitwise exclusive OR
~ One’s complement
<< Left shift
>> Right shift

vi) Special operators - The special operators of java are


 Instanceof operator – It can be defined as an object reference operator which returns
true when the left hand side value is an instance of the class which is given on the right
hand side. Simply, this operator is used to find that object in left hand side belongs to
specified class or not.
For example: student instanceof BTech
If student belongs to that class BTech, then it returns true otherwise returns false.
 Dot operator – It can be defined as an operator which accesses the instance methods
and data of a class. The dot operator can be represented as “ . “
For example: Student s;
s.getdata( );
F) Ternary operator
It performs operation on three operands. It is also called as conditional operator.
The following is the syntax:
condition ? expr1 : expr2;
eg: a > b ? a : b;
It means, if the condition is true then “ a “ is big. Otherwise “ b “ is big.

22
R16
JAVA Unit-1

Expressions – precedence rules and associativity


15Q: What is an expression? Explain about precedence rules and associativity. (8M) (OR)
Write the table that shows the precedence of operators in java. (3M)
Expression
An expression can be defined as combination of operators, variables and constants.
For example, c=a+b;
c=5;
Precedence and associativity
 If an expression contains two operands with different precedence, then the order of
their evaluation is determined using precedence rules.
 If an expression contains two operands with same precedence, then their order of
evaluation is determined using associativity rules.
 There are two types of associativity rules names left associativity and right associativity.
 The left associativity determines the operators to be evaluated from left to right.
 The right associativity determines the operators to be evaluated from right to left.
 Precedence and associativity override each other using parenthesis.
 The below tables explains the associativity of the operators:
Operators Associativity
. , [ ], ( ), i++, i- - L -> R
++i, - - i, ~ , ! R -> L
new, (type) R -> L
*,/,% L -> R
+,- L -> R
<< , >> L -> R
< , > , < = , > =, instanceof Non associative
= = , != L -> R
& L -> R
^ L -> R
| L -> R
&& L -> R
|| L -> R
?: R -> L

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.

Primitive Type Conversion and Casting


16Q: Explain Primitive type conversion and casting with examples. (8M) (OR)
Describe about type conversion. Also explain how casting is used to perform type
conversion between incompatible types.
Type conversion
Def:-
Type conversion refers to the conversion of data from one data type into another
data type.
 It is one of the most important aspects of java programming.
 Consider an example for type conversion,
int x;
float y;
x=5;
y=x; // integer value 5 is assigned to float. Output is 5.00
 If compatible types are assigned to variables, the right-hand side expression is assigned
directly to the left hand side expression.
 But it is not possible to convert all data types since java support strict type checking.
 Similarly, all implicit type conversions are not supported.
 An automatic type conversion can be done only if the following conditions are satisfied:
iii) The data type of the variable and value must be compatible.
iv) The data type of left-hand side must be large in size compared to the right-hand side.
 The int data-type can hold byte, short values since it is higher than these types, whereas
long values cannot be assigned to int.
 The integer types and floating point types are compatible with each other.
 Numeric types cannot be compatible with Boolean or char. Similarly, char and Boolean
are also compatible.

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”);

12) 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");

27
R16
JAVA Unit-1

13) 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

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

15) 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;

30
R16
JAVA Unit-1

case 2:
statement2;
break;


default:
statement n;
}

Flowchart:

case 1 T statement1 break

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

16) 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++;
}

33
R16
JAVA Unit-1

17) 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:

body of the loop

condition

F
T
exit

Example:
do
{
System.out.println(+i);
i++;
}while(i<=10);

34
R16
JAVA Unit-1

18) 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 );

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 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
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

You might also like