You are on page 1of 11

JAVA UNIT-1 JAVA UNIT-1

UNIT - I It ties the data more closely to the functions that operate on it.

Fundamentals of Object Oriented Programming

What is procedure oriented programming (POP)?


In procedural programming programs are divided into a number of segments known as subprograms.
It focuses on functions apart from the data. The sub programs can access to the same global data, here
also the data is not fully protected.
The control of programs is transferred using unsafe goto statement.
These languages are used for developing medium size applications.
OOP allows us to decompose the problem into number of entities called Objects.
Data of object can be accessed only by the methods associated with that object.
It follows Bottom-Up approach in program development.
What are the advantages of OOP ?
OOP offers several benefits to both the program designer and the user. The principal advantages are:
Using inheritance we can extend the program very easily and can eliminate the duplication of code.
OO systems can be easily upgraded from small to large systems.
It is easy to partition the work in a project based on objects.
What are the limitations of POP? The concept of data hiding helps the programmer to develop secure programs.
Large size programs are divided into smaller programs known as functions. These functions can call Software complexity can be easily managed
one another. Hence security is not provided. Explain the applications OOP
Importance is not given to security of data but on doing things(functions).
Real time systems
Data passes globally one function to another.
Simulation and modeling
Most functions have access to global data.
OO database
Extension of the program was very difficult; the data structure is access by no of functions.
Hypertext, hypermedia and expert-text
Once we modify the structure of the data we need to modify all the functions who accessing the data
AI and expert systems
structure.
Neural networks and parallel programming
Explain object oriented paradigm? Decision support and office automation systems
It is an approach that provides a way of modularizing program by creating partitioned memory area for CAM/CAD systems
both data and functions that can be used as template for creating copies of such modules on demand. Explain the basic concepts of Object - Oriented Programming?
OOP treats data as critical element in the program development and does not allow it to flow freely
OOP is programming model that uses “objects “ and their interaction to design applications and computer
around the system.
programs. The basic concepts of Oops language is:
Class:
A class is a template definition of the methods and variables for a particular kind of object. In other
1 2
JAVA UNIT-1 JAVA UNIT-1

words, class is the blue print (logical representation) from which an individual objects is created.
Object:
An Object is a real time entity. It is also known as instance of a class.
An object will have some properties and it can perform some actions. Object contains variables and
methods.
The objects which exhibit similar properties and actions are grouped under one class.

Polymorphism:
The word polymorphism came from two Greek words „poly‟ means „many‟ and
„morphos‟ means „forms‟. Polymorphism represents the ability to assume several different forms. The
ability to define more than one function with the same name is called Polymorphism.
Dynamic Binding:
It is also known as dynamic dispatch, it is the process of linking function call to a specific function
definition at run-time.
Dynamic binding is also known as late binding.
Encapsulation:
Wrapping up of data (variables) and methods into single unit is called Encapsulation. Encapsulation can
be described as a protective mechanism that prevents the code and data being accessed by other code
defined outside the class.
Abstraction:
Providing the essential features without its inner details is called abstraction (or) hiding internal
implementation is called Abstraction.
We can enhance the internal implementation without effecting outside world. Abstraction provides
security.
Inheritance: Message Passing:
OOPS includes objects which communicate with each other.
Acquiring the properties from one class to another class is called inheritance (or) producing new class
Objects communicate with one another by sending and receiving information much the same ay as
from already existing class is called inheritance.
people pass messages to one another.
Reusability of code is main advantage of inheritance.
The relation between the two class is known as “is a” relation.

Delegation:

Function
Function
When objects of
3 4
JAVA UNIT-1 JAVA UNIT-1

one class is used as data member in another class, such composition of objects is known as delegation. Java designed as pure object-oriented language. We require minimum one class to develop a program.
Such a relation between two classes is known as “ has a” relation. The object model in Java is simple and easy to extend.
Robust:
Explain Differences between POP and OOP: The ability to create robust programs was given a high priority in the design of Java.
Procedure Oriented Programming Object Oriented Programming Java is a strictly typed language; it checks your code at compile time also at run time.

1.Main program is divided into small object Java eliminates manually disallocati0n of dynamically allocated memory i.e. deallocation is completely
1.Main program is divided into small parts
depending on the problem automatic.
depending on the functions Java provides object-oriented exception handling. In a well-written Java program, all run-time errors can
and should be managed by your program.
2. 2. Functions get more importance than 2. Data gets more importance than functions
Multithreaded:
data in Program Java supports multithreaded programming, which allows you to write programs that do many things
in program. simultaneously.
3. Most of the functions use global data. 3. Each object controls its own data This feature greatly improves the interactive performance of graphical and game applications.
4.Same data may be transfer from one 4.Data does not possible transfer from one
function to another object to another Platform independent and Architecture-Neutral:
5. There is no perfect way for data hiding 5. Data hiding possible in OOP which prevent illegal Java programs can be easily moved from one computer to another , anywhere and anytime.
access of function from outside of it. This is one of The Java Virtual Machine (JVM) made the java language platform independent and architecture neutral.
the best advantages of OOP also. Interpreted and High Performance:
6. More data or functions can not be added 6. More data or functions can be added with Program Java enables the creation of cross-platform programs by compiling into an intermediate representation

easily very easily called Java bytecode.

. The Java bytecode was carefully designed so that it would be easy to translate directly into native

7. Top down process is followed for 7. Bottom up process is followed for program design. machine code for very high performance by using a just-in-time compiler.

program design. Portable:


8. Example: C++, Java. Java ensures portability in two ways. First java compiler generates bytecode instructions that can be
8. Example: Pascal, Fortran implemented on any machine. Secondly the size of the primitive data types are machine – independent.
Distributed:
Explain java features? Java is designed for the distributed environment of the Internet, because it handles TCP/IP protocols.
The development team of java wanted the language to be portable, reliable and distributed but also simple. Java included features for intraaddress-space messaging. This allowed objects on two different
Apart from above the java has the following features. computers to execute procedures remotely.

Simple: Dynamic:
Java inherits the C/C++ syntax and many of the object-oriented features of C++. Also, some of the more Java programs carry with them substantial amounts of run-time type information that is used to verify
confusing concepts from C++ are eliminated from Java and resolve accesses to objects at run time. This makes it possible to dynamically link code in a safe and

Object-Oriented: expedient manner.


5 6
JAVA UNIT-1 JAVA UNIT-1

Security: Application Programming Interface (API) :


Java systems not only verify all memory access but also ensure that no viruses are communicated with an The java Standard library includes hundreds of classes and methods grouped into several functional
applet the absence of pointers in java ensures that programs cannot gain access to memory locations. packages. The most commonly used packages are
Overview of Java language java.lang, java.util, java.io, java.net, java.awt, java. Applet.
Differentiate between C and JAVA?
JAVA is Object-Oriented while C is procedural. Explain java Runtime Environment?
Java is an Interpreted language while C is a compiled language. The java runtime environment (JRE) facilitates the execution of programs developed in java. It basically
C is a low-level language while JAVA is a high-level language. consists of the following:
C uses the top-down approach while JAVA uses the bottom-Up approach. Java virtual machine:
JAVA cannot support pointers while C requires explicit handling of pointers. It is the program that interprets the intermediate byte code and generates desired output.
JAVA supports Method Overloading while C does not support overloading at all. Runtime class Libraries:
Unlike C, JAVA does not support Preprocessors. Set of class libraries that are required for execution of java program.
Exception Handling is strong in JAVA where as in C language very difficult to handle run time errors.
User interface toolkits:
Explain java environment?
This includes different input methods for the users to interact with the application program.
Java environment includes a large number of development tools and hundreds of classes and methods.
Deployment technologies:
The development tools are the part of the system known as Java Development Kit (JDK) and the classes
JRE comprises the following key deployment technologies
and methods are the part of Java Standard Library (JSL) also known as the application Programming
Java plugins, Java web start
Interface (API).
Explain Java program structure ?
Java Development Kit (JDK):
To write java program, we first define classes and then put them together. A jav program may contain one
The Java Development Kit comes with a collection of tools are used for developing and running java
or more sections.
programs. They include
Java applet
Java c
Java
Java h
Java p
Java doc
Java db
the source code is compiled using the java compiler “JAVAC” and executed by using java
interpreter “java”. The java debugger” jdb” is used to find errors if any. A compiled java program can be
converted into a source code with the help of java disassembler (java p). Documentation Section:
The documentation comprises a set of comment lines giving the name of the program, the author and

7 8
JAVA UNIT-1 JAVA UNIT-1

other details, which the programmer would like to refer at a later stage.
Java Java
Java supports three types of comments single line comments ( // ), multi-line comments (/*… */), Byte Code
Program Compiler
documentation comments (/** ... */).
Package Statements: The best-known language today that uses the bytecode is java, LISP , ICON, Prolog.
The first statement allowed in java file is a package statement, this statement declares a package name
and informs the compiler that the classes defined here belong to this package. What is Java Virtual Machine:
package pack name;
Java Virtual Machine (JVM) is the heart of entire Java program execution process. First of all, the .java
The package statement is optional, that is our classes do not have to be a part of a package.
program is converted into a .class file consisting of byte code instructions by the java compiler at the
Import statement: time of compilation.
The next statement after a package statement may be a number of import statements. This is similar to The JVM exists only inside the computer memory, it is a simulated computer with in the computer
the #include statement in C.
import java. lang. *; import java. awt. * ;
This statement instructs the interpreter to load the classes contained in the packages mentioned.
Interface statement:
An interface is like a class but includes a group of method declarations. This is also an optional statement
and is used only when we wish to implement the multiple inheritance feature in the program. Interface is
new concept in the java.
Class Definition:
A java program may contain multiple class definitions. Classes are the primary essential elements of a
java program. The no of classes used depends on the complexity of the problem.
Main method class:
Since every java stand alone program requires a main method as its starting point. This class is defined
Explain Java Tokens?
the essential part of a java program.
A simple java program may contain only this part. The main method creates objects of various classes A token is the smallest element of a program that is meaningful to the compiler. These tokens define the

and establishes communications between them. structure of the Java language. The compiler recognizes them for building up expressions and statements.
Java tokens can be broken into five categories:
What is byte code?
Identifiers
Bytecode is a highly optimized set of instructions designed to be executed by the Java run-time system,
keywords
which is called the Java Virtual Machine (JVM). That is, in its standard form, the JVM is an interpreter
literals
for bytecode.
operators
Bytecode is the result of compiling source code written in a language that supports this approach.
separators
Keywords:
It is a special type of reserved word for a specific purpose in the program development.

9 10
JAVA UNIT-1 JAVA UNIT-1

There are 50 keywords currently defined in the Java language. All the keywords must be written in lower Logical Operators
case Assignment Operators
Ex: abstract, byte, class extends, private , protected , case , switch, if , else Misc Operators
Identifiers: Separators:
Identifiers are the names given by the programmer to variables, methods, and classes to identify them to Separators are used to inform the Java compiler of how things are grouped in the code. For example,
the compiler items in a list are separated by commas much like lists of items in a sentence. The most commonly used
The can have letters, numbers, or the underscore (_) and dollar-sign ($) characters separator in Java is the semicolon.
Must not begin with a number.
Upper case and Lower-case letters are distinct. Symbol Name
They can be of any length. ; Semicolon
, Comma
Valid Invalid {} Braces
HelloWorld Hello World (uses a space) () Parentheses
Hi_JAVA Hi JAVA! (uses a space and punctuation mark) [] Brackets

value3 3value (begins with a number) . Period

Tall short (this is a Java keyword)


$age #age (does not begin with any other symbol except _ $) Explain how to implement java program?
(OR)
Literals: Explain the steps involved in developing a java program?
Literals in java are sequence of characters that represents constant values to be stored in variables. Java
Implementation of a java application program involves a series of steps they include: edit, compile, and run
language specifies five major types of literals:
a Java program.
Integer Literals. (10,20)
Editing a Program
Floating point literals.(10.234)
Any text editor may be used to edit a program by typing the program and making corrections as needed.
Character literals.(„J‟)
Compiling a Program
String literals. (“java”)
The Java source programs have to compile it into the Java bytecode, the intermediate code understood by
Boolean literals. (true, false)
the Java Virtual Machine (JVM).
Operators: The Java SDK compiler is named javac. At the Windows command prompt
Operator is a special symbol that takes one or more arguments and operates on them to produce a result. HelloWorld.java file would be compiled by typing the following command: javac HelloWorld.java
Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the Running a Java Application Program
following groups: In order to run a java program (or execute) a program on any computer, the programs .class file must be
Arithmetic Operators loaded into the computer's memory, where it is then interpreted by the Java Virtual Machine (JVM). To
Relational Operators run a Java program on Windows command prompt, type java HelloWorld
Bitwise Operators on the command line. This command loads the JVM, which will then load and interpret the application's

11 12
JAVA UNIT-1 JAVA UNIT-1

bytecode (HelloWorld.class). Floating literals


Explain different types of java statements: Character literals

A statement is an executable combination of tokens ending with a semicolon( : ). Mark. Statements are String literal

usually executed in sequence in the order in which they apper.. java implements several types of Boolean literals

statements they are: Integer literals:

Declaration statement: An integer constant refers to a sequence of digits. Java supports three types of integer literals.

The statement that declares a variable of a particular type. In Java, a variable must be declared anywhere Decimal (Base 10)

before it can be used in a program. Floating-point numbers represent decimal values with a fractional component. They can be expressed in

type Variable Name; either standard or scientific notation.

Ex: int sno; Floating-point literals in Java default to double precision...

double sal; Assignment statement: double d1 = 123.4;

The statement that stores (assigns) a value in a variable. An assignment statement uses the equal sign (=) double d2 = 1.234e2; // same value as d1, but in scientific notation float f1 = 123.4f;

as an assignment operator. Like other statements, an assignment statement ends with a semicolon: Character constants:

variable Name = Value; greeting = "Hello World"; A single character constant contains a single character enclosed with in a pair of single quote marks. Java

num1 = 50; // (a) Assign 50 to num1 num2 = supports Unicode character set.

10 + 15; // (b) Assign 25 to num2 String Literals:

num1 = num2; // (c) Copy num2's value (25) into num1 A string constant is a sequence of characters enclosed between double quotes. The characters may be

Control flow statements: alphabets, digits, special characters and blank spaces.

Regulate the order in which statements get executed. We can write statements using if, switch, loops. “Hello World” “two\nines”

Jump Statements: Java string is that they must begin and end on the same line.

Jump statements pass control to the beginning or end of the current block, or to a labelled statement. The Boolean Literals:

labels must be in the same block. java supports four types of jump statements: Constants which stores either true or false.

Blocks The values of true and false do not convert into any numerical representation. The

break true literal in Java does not equal 1, nor does the false literal equal 0.

continue Write about Escape Sequence characters?


return Java supports some special backslash characters constants that are used in output methods. Although they
throw consist of two characters they treat as one character, these character combinations are known as escape
A block is a group of zero or more statements between balanced braces and can be used anywhere a sequences.
single statement is allowed. Escape Sequence Description
Constants, variables, and Data types \‟ Single quote

Write all about constants? \” Double quote


\\ Backslash
Constants in java refer to fixed values that do not change during the execution of a program.java supports
\r Carriage return
five types of constants:
\n New line (also known as line feed)
Integer literals
13 14
JAVA UNIT-1 JAVA UNIT-1

\f Form feed byte 1 -128 to 127


\t Tab short 2 -32768 To 32767
\b Backspace int 4 -2147483648 To 2147483647
long 8 -9223372036854775808 To 9223372036854775807

We can make integers long by appending the letter L or l at the end of the number Ex:
Explain java Data Types? 123L or 123 l
Data types specify the size and type of values that can be stored. java language is rich in its data types. Floating point types:
Java supports two types of data types This type holds numbers containing fractional parts such as 27.68 and -1.342. java supports two types of
Primitive data types floating-point storage float (single precision), double (double precision)
Reference data types

Java defines eight primitive types of data: byte, short, int, long, char, float, double, and Boolean. The
simple types are defined to have an explicit range and mathematical behavior. These can be put in four
groups:
Integers This group includes byte, short, int, and long, which are for whole valued signed numbers.
Floating-point numbers This group includes float and double, which represent numbers with fractional By default, all floating-point numbers are double precision numbers. To make them single precision

precision. numbers append f or F


Characters This group includes char, which represents symbols in a character set, like letters and Ex:

numbers. Type Size (bytes) Range


Boolean This group includes Boolean, which is a special type for representing true/false values. Float 4 3.4 e -38 To 1.7 e+38
Integer types: Double 8 3.4e-38 To 1.7 e+308
Integer types can hold whole numbers such as 123, -90, 5678. The size of the values that can be stored Character type:
depends on the integer type we choose. Java supports four types of integers, they are byte, short, int, In order to store character constants in memory, java provides a character data type called “char”. Java
long. supports Unicode format of characters i.e. it can support 65536 no of characters. It occupies 2 bytes of
memory.

Type Size (bytes) Range


char 2 Unicode format
Boolean type:
Boolean type is used when we want to test a particular condition during the execution of the program.
There are only two possible values that a Boolean type can take: “true” or “false”. All relational and
logical operators will return booleans.
Type Size (bytes) Range
15 16
JAVA UNIT-1 JAVA UNIT-1

Type Size (bits) Range Data Type Default Value (for fields)
boolean 1 true or false byte 0
short 0

Write all about variables? int 0

A variable is an identifier that denotes a storage location used to store a data value. A variable is defined long 0L

by the combination of an identifier, a type, and an optional initializer. In addition, all variables have a float 0.0f

scope, which defines their visibility, and a lifetime. double 0.0d

Declaring a Variable char '\u0000'

In Java, all variables must be declared before they can be used. The basic form of a variable declaration String (or any object) null boolean false

is shown here: The compiler never assigns a default value to an uninitialized local variable.

type identifier [ = value] [, identifier [= value] ...]; Explain Type Casting:


To declare more than one variable of the specified type, use a comma-separated list Ex: Converting one type of data into another must follow the rules of casting. If a conversion results in the
int m1, m2, m3; loss of precision, as in an int value converted to a short, then the compiler will issue an error message
Initializing Variables unless an explicit cast is made.
You can initialize the variable by specifying an equal sign (assignment operator) and a value. The Java supports two types of castings – primitive data type casting and reference type casting. Reference
initialization expression must result in a value of the same (or compatible) type as that specified for the type casting is nothing but assigning one Java object to another object. In java conversion takes place in
variable. two ways
byte z = 22; // initializes z. Implicit casting
double pi = 3.14159; // declares an approximation of pi. char x = Explicit casting
'x'; // the variable x has the value 'x'. Implicit casting (widening conversion)
Dynamic Initialization A data type of lower size (occupying less memory) is assigned to a data type of higher size. This is done
Java allows variables to be initialized dynamically, using any expression valid at the time the variable is implicitly by the JVM. The lower size is widened to higher size. This is also named as automatic type
declared. conversion.
double a = 3.0, b = 4.0; Examples:
double c = Math.sqrt(a * a + b * b); // c is dynamically initialized int x = 10; // occupies 4 bytes

Explain scope and lifetime of a variable? double y = x; // occupies 8 bytes

A scope determines what objects are visible to other parts of your program. It also determines the System.out.println(y); // prints 10.0

lifetime of those objects. In the above code 4 bytes integer value is assigned to 8 bytes double value.

Variables are created when their scope is entered, and destroyed when their scope is left. Explicit casting (narrowing conversion)

When you declare a variable within a scope, you are localizing that variable and protecting it from A data type of higher size (occupying more memory) cannot be assigned to a data type of lower size.

unauthorized access and/or modification. The scope rules provide the foundation for encapsulation. This is not done implicitly by the JVM and requires explicit casting; a casting operation to be performed
by the programmer. The higher size is narrowed to lower size.
What is a default value of a variable?
Syn: type variable1 = (type) variable2
It's not always necessary to assign a value when a field is declared. Fields that are declared but not
double x = 10.5;
initialized will be set to a reasonable default by the compiler.
17 18
JAVA UNIT-1 JAVA UNIT-1

int y = (int) x; Multiplication *


A boolean value cannot be assigned to any other data type. Except boolean, all the remaining 7 data types Division /
can be assigned to one another either implicitly or explicitly; but boolean cannot. modulo division %
class cast_ex{ These can operate on any built-in numeric data type of java. We cannot use these operators on Boolean
public static void main (String args[ ] ){ float x =254.01f; data types. All these are binary operators.
byte b;
b = (byte) x ; /*type conversion*/ System.out.println( " 'value of b ' "+b); Relational operators
}} Relational operators generate a Boolean result and binary operators. They evaluate the relationship between
Operators and Expressions the values of the operands. The relational operators are

Explain all about operators? < Less than,


> Greater than,
Operator is special symbol which performs a specific operation the operands. An operator takes one or
<= Less than or equal to
more arguments and produces a new value. All operators produce a value from their operands. In
>= Greater than or equal to
addition, an operator can change the value of an operand. This is called a side effect. Operators can be
== Equivalent
categorised into two ways
!= Not equivalent
Based on no of operands
A simple relational expression contains only one relational operator and is of the following form:
Based on type of operation
Ex:
Based on no of operands that an operator requires to perform its operation the operators are Three types
Unary operators Op1 Relational Operator Op2
Binary operators
a > b
Ternary operators
Logical Operators:
Based on type of operation that an operator performs the operators are
The logical operators are used to form compound conditions by combining two or more relations. The
Arithmetic Operators.
logical expressions also give a value of true or false according to the truth table.java supports three types
Relational Operators.
of logical operators:
Logical Operators.
&& Logical AND
Assignment Operators.
|| Logical OR
Increment, Decrement Operators.
! Logical NOT
Conditional Operators.
Truth Table:
Bitwise Operators.
A B A || B A && B !A
Special Operators.
false false false false true
Arithmetic Operators:
true false true false false
Arithmetic operators are used to construct mathematical expressions as in algebra.
false true true false true
Java provides all the basic arithmetic operators.
true true true true false
Addition +
Subtraction -
19 20
JAVA UNIT-1 JAVA UNIT-1
Bitwise operators evaluated either from left to right or from right to left depending on the level.
The bitwise operators allow you to manipulate individual bits in an integral primitive data type. Java the
following bit wise operators :
Bitwise AND operator ( & )
Bitwise OR operator ( | )
Bitwise EXCLUSIVE OR, or XOR ( ^ ) Bitwise NOT
(~)
Assignment Operator
The assignment operator is the single equal sign, =. The assignment operator works in Java much as it does
in any other computer language. It has this general form:

var = expression;

Increment and Decrement Operator:


The increment operator (++) increases its operand by one. The decrement operator (--) decreases its
operand by one. These are unary operators.
x = 42;
y = ++x;
x = 42;
y = x++;
Conditional Operator:
Java includes a special ternary (three-way) operator that can replace certain types of if-else statements.
The? has this general form:

exp1 ? exp2 : exp3

Here, exp1 can be any expression that evaluates to a Boolean value. If exp1 is true, then exp2 is
evaluated; otherwise, exp3 is evaluated.
Shift operators
The shift operators also manipulates bits. They can be used solely with primitive, integral types.
left-shift operator (<<) right-shift operator (>>)

SPECIAL OPERATORS
Java supports some special operations of interest such as instance of operator and member selection
operator( . ) and comma operator.
What is an Operator Precedence and Associativity?
Each operator in java has a precedence associated with it. This precedence is used to determine how an
expression involving more than one operator is evaluated. The operators of the same precedence are
21 22

You might also like