You are on page 1of 40

Java Programming

UNIT-1
Introduction to OOPs & Introduction to Java

Topics covered in this unit


• Introduction to OOP:
– Procedural programming language and Object oriented language
– principles of OOP
– applications of OOP
• Introduction to Java :
– history of java
– java features
– JVM
• Language Fundamentals:
– program structure
– Variables
– primitive data types
– identifiers, literals.
– operators, expressions, precedence rules and associativity.
– primitive type conversion and casting.
– flow of control.
Introduction to OOPs
• Object Oriented Programming is most useful paradigm, based on the concept of objects .
• It addresses the problems known as software crisis, raised in 1970.
• The term software crisis describes software failure in terms of exceeding software budget.
• Software was not meeting clients’ requirements, due to bugs in the software.
• A new alternative paradigm is introduced Object Oriented Programming.
• OOP paradigm is modeled around the real world.
• Our real world is full of objects.
• Each object has a well-defined identity, attributes, and behavior.
• In OOPs, software objects are resembled to real world objects and exhibit the same behavior in
programming.
• The features of object-oriented programming also map closely to the real-world features like
inheritance, encapsulation, and polymorphism.
• Some of the Object-Oriented Paradigm are:
– Emphasis is on data rather than procedure.
– Programs are divided into objects.
– Data Structures are designed such that they
– Characterize the objects.
– Methods that operate on the data of an object are tied together in the data structure.
– Data is hidden and cannot be accessed by external functions.
– Objects may communicate with each other through methods.

Need of object-oriented programming


• There are some limitations in earlier programming approaches.
• To overcome these limitations, a new programming approach was required.
• In procedural languages, a very large problem is divided into functions and modules, to reduce
the complexity.
• In 1970, Procedural programming leads to software crisis.
• Analysis of Software crisis is as below:
– 38% of projects were paid but not delivered, due to complexity of software
development.
– 30% of projects are delivered, but not used, due to that the projects were not met the
requirements of users.
– 16% of projects were abandoned, due to lack of maintenance.
• The reasons to the software crisis are:
– The functions have unrestricted access to global data, leads to data hurting.
– They provide poor mapping to the real world.
– It is very difficult to create a new user defined data types called extendibility.
• In the physical world, we deal with objects like person, car, account etc.,
• These objects have attributes and behavior.
• Attributes define the data for an object.
– Ex: name, roll no, course, marks are attributes for student object.
– Color, brand name, engine power, number of seats etc. are attributes for a car object.
– This collection of attributes will have specific values called state.
• The response of an object when subjected to simulation is called behavior.
– The object of account, having behavior like deposite(), withdraw(), show_balance() etc.,
– The bike object has behavior like start(), stop(), change_gear(), accelerate(),
apply_breaks() etc.,
– We can say that behavior is synonym to functions or methods.
Object Oriented programming and an example:
Natural way of solving a problem: (Sending Flowers to a Friend )
 Ravi wants to send flowers to the friend Mahesh, who is in Chennai.
 Now Ravi consulted an agent and booked an order to send flowers to Mahesh.
 Now agent forwards the order to the Florist available at Chennai.
 Florist purchases flowers for the Whole seller, and prepared the bouquet with the help of flower
arranger.
 Now the delivery person delivers the bouquet to the friend.
The above task can be explained as a community of agents (Objects) helping to perform a task.
An object-oriented program is structured as a community of interacting agents, called objects.
 Each object has a role to play.
 Each object provides a service, or performs an action, that is used by other members of the
community.
 Object-oriented programming organizes a program around its data (that is, objects) and a set of
well-defined interfaces to that data.
 An object-oriented program can be characterized as data controlling access to code by switching
the controlling entity to data.

Procedural programming language and Object oriented language


Program in C(procedural) Vs Program in java (Object oriented )

Functions are called directly <---------------> Methods are called through objects

Advantages & disadvantages of OOP

• Advantages of OOPs
– Code reuse & recycling.
– Improved software-development productivity ( Faster in time and Lower in cost of
development )
– Improved software maintainability.
– Higher-quality software.
– Data abstraction is possible through Encapsulation
– Data access is restricted providing better data security.
– Class hierarchies are helpful in the design process allowing increased extensibility.
• Disadvantages of OOPs
– Steep learning curve
– The benefits of OOP may be realized after a long period.
– Requires intensive testing procedures.
– Could produce slower programs
Applications of OOPs
• Real-time systems
– A real-time system is one that must process information and produce a response with-in a
specified time, else risk severe consequences, including failure.
• Simulation and modeling
– Simulation and modeling is a process of creating and analyzing a digital prototype of a
physical model to predict its performance in the real world.
• Object-oriented databases
– OODB are databases stores objects in databases rather than data such as integers, strings
and real numbers. This type of databases also integrates the oops concepts like
encapsulation, polymorphism and inheritance.
• Hypertext, hypermedia and ExperText
– HyperText is the grouping of information in the forms of nodes, and these nodes are
connected through links.
– Hypermedia is extension of Hypertext and multimedia.
– ExperText is a system which combines a hypertext and expert system.
• AI and expert systems
– Artificial Intelligence is Intelligence exhibited by machines or software, like human mind.
– An Expert System is a computer system that emulates the decision making ability of human
expert.
• Neural networks and parallel programming
– Neural networks have the ability to adapt to changing input, so that the network produces
the best possible result without the need to redesign the output criteria.
– Parallel programming is processing of programming instructions by dividing them among
multiple processors with the objective of running a program in less time.
• Decision support systems
– A decision support system is a computer program application that analyzes business data
and presents it so that users can make business decisions more easily.
• CAD/CAM/CIM systems.
– Computer Aided Design is the use of computer programs to create 2D or 3D graphical
representations of physical objects.
– Computer Aided Manufacturing is the use of computer software to control machine tools
and related machinery in manufacturing workspaces.
– Computer Integrated Manufacturing is the manufacturing approach of using computers to
control the entire production process. This integration allows individual processes to
exchange information with each other and initiate actions.
Principles of object-oriented languages
• OOPs languages have principles map very closely to the real world.
– Objects.
– Classes.
– Abstraction.
– Inheritance.
– Encapsulation.
– Polymorphism.
– Dynamic binding
– Message passing
a) Object:
• Object is the basic unit of object oriented programming.
• Every object has an identity, attributes, behavior and state.
• Definition: An object may be a tangible or non-tangible thing which is clearly identified as a
separate entity with a well-defined roll in the problem domain. Ex :
– Tangible things like printer, book, car etc.,
– Roles like employee, faculty, manager etc.,
– Incidents like take-off, over-flow etc.,
– Interaction like sale, contact, agreement etc.,
– Specifications like shape, color, circuit, building etc.,
• The nature is composed with various objects and everything in the real world is an object.
• Similar objects are grouped and categorized.
• Each category of objects may be sub-categorized based on special properties and behavior.
• Each object has responsibility to react for a particular type of functionality.
Objects and its features:
• An object is runtime entity which performs some operations in the object oriented programs.
(Ex : a car, book, student, account etc., )
• All the software objects are similar to real world objects.
• An object is instance of a class.
• Every object occupies some space of memory to store the values of the properties ( attributes).
• The collection of properties and its values at a point of time is known as state. That means every
object maintains its state for its entire lifetime.
• State of the object varies time to time according to the operations performed on it.
• The actions of an object depends upon the member functions defined with in its class

Examples of objects : Car, Bicycle, Dog


b) Class:

• A class defines the features of an object.


• A class is a user-defined data type, which represents a group of similar objects, having identical
properties, common behavior and sharing relationship.
• The class defines the nature and methods common to the objects which are similar.
• The objects are instances of the class.

In object-oriented terms, we say that your bicycle is an instance of the class of objects known as
bicycles. A class is the blueprint from which individual objects are created. Java classes contain fields and
methods. A field is like a C++ data member, and a method is like a C++ member function. In Java, each
class will be in its own .java file.
Bundling code into a single unit provides a number of benefits:
• Modularity: The source code for an object can be written and maintained independently of the
source code for other objects.
• Information-hiding: The details of its internal implementation remain hidden from the outside
world.
• Code re-use: We can reuse the code to create specialized classes using inheritance.
• Pluggability and debugging ease: you can simply plug in a different object as its replacement.

c) Abstraction:
• Abstraction (from the Latin abs, meaning away from and trahere, meaning to draw)
• It is the process of simplification, by taking away non-essential characteristics from something in
order to reduce it to a set of essential characteristics.
• It allows only essential features to expose to user, and hides internal complexity.
• So each object exhibits abstraction for easier operations to user, and abstraction deals with the
outside view of an object (interface).
• Abstraction hides the irrelevant details in code. All you need to know is a public set of functions.
d) Encapsulation :
• Encapsulation is a concept that binds together the data of an object, and functions that manipulate
the data in to a single unit or single component.
• Encapsulation provides more security to the data with data hiding, from outside interference and
misuse.
• It is a specialized case of ‘Abstraction’, such that it is a mechanism to hide irrelevant details of one
object from another, while exposing only the relevant details that the other object might need.
• It helps the concept of ‘modularity’ in applications. If encapsulation principle is followed correctly,
there should be low dependency b/w different software modules.

Abstraction Vs Encapsulation
e) Inheritance:
• Most important aspect of oops is code reusability.
• Inheritance is the process of forming a new class from an existing class.
• The existing class called as base class, new class is formed called as derived class.
• Two types of paradigms
– Object Oriented Programming.
– Object Based Programming ( No inheritance)
• Java is object oriented language, and it does not support Multiple Inheritance.

An example of Inheritance

f) Polymorphism:
• The ability to use an operator or function in different ways is called polymorphism
• Poly refers to many.
• A single function or an operator, functioning in many ways different upon the usage is called
polymorphism. Examples:
– Method Overloading
– Method Overriding
– Operator Overloading
– Generic functions (Templates)
– Generic classes (Template classes )
• C++ allows operator overloading, Templates also.
• Java does not support operator overloading
• Generics are also supported by java from the version 1.5 onwards only.
g) Dynamic Method binding
• Binding is what happens when a method invocation is bound to an implementation
– Involves lookup of the method in the class, or one or its parents
– Both method names and parameters are checked
• Binding can happen at two different times
– Compile time - static binding ( or ) Early binding
– Run time - dynamic binding ( or ) Late binding
• Dynamic binding is also known as late binding.
• The implementation code of a method is not known till it is get executed.
• Java always supports to dynamic binding by default.
h) Message Passing
• Message passing is the vital activity for executing an object oriented program.
• Action is initiated in OOP by the transmission of a message to an agent (an object) responsible
for the action.
– The message encodes the request for an action and is accompanied by any additional
information (arguments) needed to carry out the request.
• Collection of objects which interacts each other with passing messages from one object to
another object which leads the flow of execution in oops project.
• The receiver is the object to whom the message is sent. If the receiver accepts the message, it
accepts the responsibility to carry out the indicated action.

Introduction to Java
• Java is a general-purpose computer programming language.
• It has the features like concurrent, class-based, object-oriented, and specifically designed to
have as few implementation dependencies as possible.
• It is intended to let application developers "write once, run anywhere" (WORA).
• It means that compiled Java code can run on all platforms that support Java without the need
for recompilation.
• Java is a widely used programming language expressly designed for use in the distributed
environment of the internet.
• It is the most popular programming language for Android smart phone applications and is
among the most favored for edge device and internet of things development.
C++ Language Vs Java Language:

History of Java
• In 1990, James Gosling and his team was given the task of creating programs to control
consumer electronics.
• They used C++ as its model, stripping away all the difficult features of C++, and named "Oak ".
• "Oak " was also called "Green Project ", is a control system would enable the user to manipulate
a list of devices, including TVs, VCRs, lights, and telephones etc.,
• By the time Sun Micro systems discovered that the name "Oak" was already claimed and they
changed the name to " Java" .
• Java was a platform-neutral language, which meant that programs developed with Java could
run on any computer system with no changes.
• In 1993, "Java" came up with the concept of "Web applets", small programs that could be
included in Web pages, transformed the text-based Internet into a graphics-rich environment.
• A complete Web browser (called HotJava ) was also created that demonstrated the power of
Java language. Netscape Navigator Web browser added support for Java.
• In 1995, "Java" is announced as a new language was quickly embraced as a powerful tool for
developing Internet applications.

Java Versions History:


JDK – JRE – JVM
• JDK - Java Development Kit is the core component of Java Environment and provides all the
tools, executables and binaries required to compile, debug and execute a Java Program.
• JVM – Java Virtual Machine is responsible to converting Byte code to the machine specific code.
JVM is also platform dependent and provides core java functions like memory management,
garbage collection, security etc.
• JRE – Java Runtime Environment is the implementation of JVM, it provides platform to execute
java programs. JRE consists of JVM and java binaries and other classes to execute any program
successfully.

Java Virtual machine Architecture:

• JVM is a program which is written by the Java Soft People. In JVM, class loader subsystem does the
following task (work):
– It loads the dot class (.class) file from the hard disk into the memory of the computer.
– It verifies the byte code instructions. Then it will allot the memory required by the java
program.
• The memory allots by the class loader subsystem is divided into Five parts, called Run Time Data
Areas.
• They are…
– 1. Method Area
– 2. Heap Memory
– 3. Java Stacks
– 4. PC Registers
– 5. Native Method Stacks
• Method Area: Class code, method code and static variable are stored in method area.
• Heap Memory: Object are created in the heap memory, here we can create any no. of objects. Heap
memory is a huge memory block in JVM.
• Java Stacks: These are the memory areas where java methods are executed.java stacks are divided
into frames and on each frame a separate method is executed.
• PC registers (Program Counters): These registers store the memory address of the next machine
code instructions to be executed by the microprocessors.
• Native Method Area: These are the memory areas where native methods (C, C++ functions and
programs) are executed. Native method interface is a program that copies native method libraries
Like C, C++ Header files into the JVM

Java Features
• 1. Simple to learn
• 2. Object Oriented
• 3. Distributed
• 4. Robust - (Strong )
• 5. Secured
• 6. Architecture Neutral
• 7. Portable
• 8. Interpreted
• 9. High Performance
• 10. Multithreaded
• 11. Dynamic

1. Simple to learn
• Java is resemblance with C & C++
• No operator overloading
• No multiple inheritance
• All methods are virtual functions by default.
• No pointers
• Q : Why pointers are eliminated in java?
– Pointers leads to confusion for a programmer
– Pointer easily crash the program
– Pointers are security threat for data
2. Object Oriented
• Java supports programming with classes, objects.
• It also supports other oops concepts like polymorphism, inheritance, encapsulation etc.,
• Objects are communicated through messages.
• Abstract classes and interfaces provide abstraction.
3. Distributed
• The .class files of java can be easily transferred to remote machine.
• Support for TCP, UDP, and basic Socket communication.
• A variety of high-level abstractions for network communication and distributed processing are
available.
• Ex : applets, servlets, aglets, remote method invocation (RMI), EJB, JDBC.
4. Robust - (Strong )
• It means, Java programs written in java will crash less often.
• JVM first checks the reliability of the code before execution.
• Java has the strong memory allocation and automatic garbage collection mechanism, to avoid
memory failures.
• Java don't crash easily like C, because java has got excellent inbuilt exception handling features.
• Not like C, arrays are handled without memory leaks.
• Strict Run-time checking and no pointers.
• Java is Strongly typed language.
5. Secured
• Java allows all the programs to run inside the JVM (‘sandbox’) only and prevents many activities
from non-trusted resources including reading or writing to the local.
• No pointers, because pointers lead to hack easily.
• Bytecode, which are tested by the JVM at the time of program execution for viruses and other
malicious programs.
• Security problems like eavesdropping, tampering etc., are minimized on internet.

6. Architecture Neutral ( platform independent)


• Java uses Two stage translation for execution of java program.
• Java source file is compiled by javac compiler into .class which contains intermediate bytecode.
• JVM interpreter translates this bytecode into native machine code to execute on remote
machine.
• So, Java program developed on any platform is converted to platform independent bytecode,
and that bytecode can be executed on any platform which contains a preinstalled JVM.
• This concept is known as “Write once and run anywhere”

How Java is platform independent?


7. Portable
• Java is the most portable language, which can be executed almost all popular platforms in the
world.
• The variety of platforms are :
– Windows,
– Mac OS,
– UNIX/Linux like HP-Unix, Sun Solaris, Red hat Linux, Ubuntu, Cent OS, etc.
– iSeries (AS/400 )
– Mobile platforms like Android and J2ME.
– Embedded Systems.
8. Interpreted
• To translate the byte code into native machine code, java uses interpreter.
• Interpreter provides dynamic nature of execution with runtime checking.
• But Interpreters are slow when compared with compilers.
• To make fast execution, Java uses Just-in-Time compilers, which provides high performance.
9. High Performance
• The mechanisms are used by Java for high performance :
– Just-in-time compilers for parallel translation.
– Adaptive optimization, means dynamic recompilation of portions of a program based on
the current execution profile.
– Efficient memory management through garbage collector.
– Java 5.0+ to address up to 32 GB of heap with 32-bit references, leads to handle large
memory space at run time.
10. Multithreaded
• Thread is basically a lightweight sub-process, a smallest unit of processing.
• Multithreading in java is a process of executing multiple threads simultaneously.
• Multithreading is used to achieve multitasking.
• It doesn't block the user because threads are independent and you can perform multiple
operations at same time.
• Uses the processor’s resources most efficiently.
11. Dynamic
• Java was designed to adapt to an evolving environment.
• Java loads the byte code dynamically at runtime and executes.
• Java API is part of JRE and these libraries are dynamically linked at runtime while executing on
the target platform.
• Java classes carry run-time type information, that uses to dynamically linking of objects at run
time.
• All Latest versions of Java Editions has backward compatibility with old versions.

Program Structure
• A Java Program source file having extension of .java, consists of a collection of classes.
• A class is a template containing methods and variables.
• Comments are added to the sorce , to improve readability.
First Java Program

Executing Java Program


• Entering the source code: text editor like notepad or any IDE
• Saving the source code:
– Select File | Save As from the notepad menu.
– In the ‘File name’ field, type “Example.java” within the double quotes
– In the ‘Save as type’ field select All Files (*.*).
– Click enter to save the file.
• Compiling & running the source
– type cmd at the run prompt
– move to the folder that contains the saved Example.java file
– compile the program using javac,
– C:\javaeg\>javac Example.java
– Compilation creates a file called Example.class
– This class contains bytecode which is interpreted by JVM.
– To execute the program type the following command at the dos prompt:
• C:\javaeg\>java Example
– The output of the program is shown below:
• This is a simple Java program
Variables
• The variable is the basic unit of storage in a Java program.
• A variable is defined by the combination of an identifier, a type, and an optional initializer.
• All variables have a scope, which defines their visibility, and a lifetime.
• In Java, all variables must be declared before they can be used. The basic form of a variable
declaration is shown here:
type identifier [ = value][, identifier [= value] ...];
• The type is one of Java‘s atomic types, or the name of a class or interface.
• Examples :
– int a, b, c; // declares three ints, a, b, and c.
– int d = 3, e, f = 5; // declares three more ints
– byte z = 22; // initializes z.
– double pi = 3.14159; // declares an approximation of pi.
– char x = 'x'; // the variable x has the value 'x'.

Variable Types in Java

• In Java there are four types of variables:


• Instance data members
– An Instance data members is a variable that belongs to an object, which is declared in
class definition. Instance data members are accessed through objects only.
• Class ( static ) data members
– A class ( static ) field is a variable that belongs to a class. A static field has the same
value for all objects that access it. It can also accessed through class name.
• Local variables
– A local variable is a variable declared inside a method. A local variable is only accessible
inside the method that declared it. Its life time is also limited to on method call.
• Parameters
– A parameter is a variable that is passed to a method when the method is called.
Parameters are also only accessible inside the method that declares them in method
definition, although a value is assigned to them when the method is called.

Tokens in Java
• A token is an atomic unit in the program for compilation.
• Types of tokens:
– Reserved Keywords: names already in the programming language
– Identifiers: names the programmer chooses
– Separators (also known as punctuators): punctuation characters and paired-delimiters
and white spaces
– Operators: symbols that operate on arguments and produce results
– Literals ( constants)
• Numeric: int and double
• Logical: boolean
• Textual: char and String
• Reference: null
– Comments
• Line
• Block
a) Keywords in Java

Categories of keywords
• Keywords for primitive data types
– byte, short, int, long, float, double, char, boolean
• Keywords for flow control
– if, else, switch, case, default, while, do, for, break, continue, return
• Keywords for exception handling
– try, catch, finally, throw, throws, assert(for debugging purpose,1.4v)
• Keywords for modifiers
– public, private, protected, static, final, abstract, synchronized, native, transient, volatile,
strictfp(1.2v)
• class related Keywords
– class, package, import, extends, implements, interface
• object related Keywords
– new, instanceof, super, this
• void return type Keyword if a method doesn’t return anything compulsory we should declare
that method with void return type.
• unused Keywords
– goto(usage is considered as harmful), const(alternately use final)
• reserved literals
– true, false, null

b) Identifiers

• Variable names, method names, constants, array names, class names, interface names etc., are
Identifiers.
• Rules for identifiers :
– Can start with a letter(alphabet), underscore(_), or any currency symbol like dollar
sign($), pound (£).
– are case sensitive and have no maximum length.
– Second letter onwards we can use digits.
– Should not be keywords or reserve words
– No spaces are allowed.
• Ex: valid invalid
username identi+fier
user_name 6userName
_sys_var1 #sys_var1
$change change&

Java Naming Conventions

• Package Names:
– only in lower case and words are seperated by dot(.)
Ex : java.lang, java.awt.event, banking.objects; com.aditya.cse;
• Classes and Interfaces:
– Each word first letter is in Upper case.
Ex: IndexOutOfBoundsException, SavingAccount, CollegeBookStore,StringStack
• Methods:
– Each word first letter is uppercase except first word, and followed by paranthesis ()
Ex : getUserName(), setAccountBalance()
• Variables:
– Each word first letter is uppercase except first word
Ex : bookName, studentRollNumber,
• Constants:
– All words are in uppercase and seperated by underscore.
Ex : MAX_VALUE, HEAD_COUNT, MAXIMUM_SIZE

Data types in Java


Primitive Data Types

c) Literals in Java
• Literal : Any constant value which can be assigned to the variable is called as literal/constant.
• Integral literals
– Decimal literals (Base 10) Ex : int x = 101;
– Octal literals (Base 8) Ex : int x = 0146;
– Hexa-decimal literals (Base 16) Ex : int x = 0X123F
– Binary literals (Base 2) Ex : int x = 0b1111;
• Floating-Point literals
– Decimal notation Ex: double d = 123.456;
– Exponent notation Ex : double d = 1.234e+3;
• Char literal
– Single quote Ex : char ch = 'a';
– Char literal as Integral literal Ex : char ch = 062;
– Unicode Representation Ex : char ch = '\u0061';
– Escape Sequence Ex : char ch = '\n';
• String literal Ex : String s = "Hello";
• Boolean literal Ex : boolean b = true;
d) Operators
Def : Operator in java is a symbol that is used to perform operations on the operands.
For example: +, -, *, / etc.

Categories of operators

• Arithmetic operators
• Relational operators
– Ordering operators
– Equality operators
• Logical operators
• Bitwise operators
– Bitwise logical operators
– Bitwise shift operators
• Ternary operator
• Special operators
• Assignment operators
Arithmetic Operators
– Additive : + -
– Unary : + -
– Multiplicative : * / %
– Increment/ decrement :
• prefix : ++a -- a
• postfix : a++ a--
– Compound assignment :
• += -= *= /= %=

Program on Simple arithmetic operators

Program on Increment and decrement operators :


Relational Operators

Program on relational operators :

Logical Operators (boolean)


• Logical AND &&
• Logical OR ||
• Logical NOT !

Truth Table :
Program to explain logical operators :

Bitwise operators:
a) Bitwise Logical Operators
• AND &
• OR |
• XOR ^
• NOT ~

Truth table:

b) Bitwise Shift Operators:


• Shift Left << Moves the bit pattern to left
and Fill the vacant bits with Zeros
• Shift Right >> Moves the bit pattern to right
Fill the vacant bits with ‘0’ for +ve numbers and with ‘1’ for –ve numbers
• Shift Right >>> Fill always with Zeros
(Zero filled right shift)
Program on Bitwise Shift operators:

Ternary Operator ? :

String Concatenation operator: ( + )

• The + operator is used to concatenate two or more strings.

Eg: String myname = “Hari kishan”


String str = “My name is” + myname + “.”;
Results the string “My name is Hari kishan.”
• For string concatenation the Java compiler converts an operand to a String whenever the other
operand of the + is a String object.
Operator Precedence
• Java treats operators with different importance, known as precedence.
• There are in all 15 levels of precedence.
• In general, the unary operators have a higher precedence over the binary operators.
• Parentheses can always be used to improve clarity in the expression.

Associativity of Operators
• For two operators of equal precedence a second rule, ―associa vity applies.
• Associativity is
• ― le to right (le operator first)
• ― right to le (right operator first)

Operator precedence level Associativity

Type conversion:

Converting one data type variable into another data type is called type conversion.
Type conversion is two types:
a) Implicit type conversion
b) Explicit type conversion ( casting ) using casting operator “(type)” to perform type casting

Data types:
 There are two types of data types.
 Primitive data types or Fundamental data types.
• These data types will represent single entity (or value).
• Ex : int, char, byte,…….
• Referenced Data types or Advanced Data types.
• These Data types represent several values.
• Ex: arrays, classes, enums,…
Note: We can convert a primitive type to another primitive type and a Referenced type to another
Referenced type, but to convert Primitive type to Referenced type and Referenced type to Primitive
type Wrapper classes are used.
Expression:
Expression is combination of operands and operators, arranged in a meaningful way. We can evaluate
the expression into a single value.

Implicit (automatic) Conversion


In the case of the implicit conversion type conversion is automatically performed by java when
the types of compatible. For example, the int can be assigned to long. The byte cane assigned to short.
However, all the types not are compatible, thus all the type conversions are implicitly allowed. For
example, double is not compatible with byte.
Conditions for automatic conversion:
1. the two types must be compatible
2. the destination type must be larger than the source type
When automatic type conversion takes place the widening conversion (the narrower data type is
converted into widened data type) takes place. For example,

Example:

int a; //needs 32 bits

byte b=45; //needs the 8 bits

a=b; // here 8 bits data is placed in 32 bit storage. Thus widening takes place.

Explicit Conversion
Conversion of wider data type into narrower data type is not automatic. We require support of
casting operator, also known as explicit type conversion.
Example 1:
int n=65;
char ch=(char)n;
 here ch will contain A
Example 2:
double d=12.890;
int x=(int)d;
 here x will contain 12
Narrowing is unsafe because there will be loss of data or precision or accuracy. So narrowing is
not done by compiler automatically. The programmer has to use cast operator explicitly.
Fortunately, it is still possible obtain the conversion between the incompatible types. This is
called explicit type conversion. Java provides an special keyword "cast" to facilitate explicit conversion.
For example, sometimes we want to assign int to byte, this will not be performed. Converting higher
data type into lower data type is called narrowing.
Example:
int a=1234;
byte b=(byte) a;
The above code converts the int to byte. If the integer value is larger than the byte, then it will be
reduced to modulo byte's range.
A different type of conversion will occur when a floating-point value is assigned to an integer
type: truncation. As you know, integers do not have fractional components. Thus, when a floating-point
value is assigned to an integer type, the fractional component is lost.
Example:
double x = 1.23;
int y = (int) x;
if the value 1.23 is assigned to an integer, the resulting value will simply be 1. The 0.23 will have
been truncated.
Automatic Type Promotion in Expressions
The expression contains the three things: operator, operand and literals (constant). In an
expression, sometimes the sub expression value exceeds the either operand.
For example, examine the following expression:
byte a = 40;
byte b = 50;
byte c = 100;
int d = a * b / c;
The result of the intermediate term a * b easily exceeds the range of either of its byte operands.
To handle this kind of problem, Java automatically promotes each byte, short, or char operand to int
when evaluating an expression. This means that the subexpression a * b is performed using integers—
not bytes. Thus, 2,000, the result of the intermediate expression, 50 * 40, is legal even though a and b
are both specified as type byte.
As useful as the automatic promotions are, they can cause confusing compile-time errors. For
example, this seemingly correct code causes a problem:
byte b = 50;
b = b * 2; // Error! Cannot assign an int to a byte!
The code is attempting to store 50 * 2, a perfectly valid byte value, back into a byte variable.
However, because the operands were automatically promoted to int when the expression was
evaluated, the result has also been promoted to int. Thus, the result of the expression is now of type int,
which cannot be assigned to a byte without the use of a cast.
In cases where you understand the consequences of overflow, you should use an explicit cast, such as
byte b = 50;
b = (byte)(b * 2);
which yields the correct value of 100.
The Type Promotion Rules
Java defines several type promotion rules that apply to expressions. They are as follows:
• First, all byte, short, and char values are promoted to int.
• if one operand is a long, the whole expression is promoted to long.
• If one operand is a float, the entire expression is promoted to float.
• If any of the operands is double, the result is double.

Flow of Control:
In Java, program is a set of statements and which are executed sequentially in order in which
they appear. In that statements, some calculation have need of executing with some conditions and for
that we have to provide control to that statements. In other words, Control statements are used to
provide the flow of execution with condition.

In java program, control structure is can divide in three parts:


• Selection statements
o Simple if
o If – else
o If-else-if (ladder if)
o Nested if
o Switch
• Iteration statements
o While
o Do-while
o For
o Enhanced for
• Jumps in statements
o Break
o Labeled break
o Continue
o Labeled continue
o Return

Selection Statements:
Selection statement is also called as Decision making statement because it provides the decision
making capabilities to select among two are more execution paths.
Example Program for if-else:

Switch:
In Java, switch statement check the value of given variable or statement against a list of case
values and when the match is found a statement-block of that case is executed. Switch statement is also
called as multi-way decision statement.
Rules :
 The variable used in a switch statement can only be integers, convertable integers (byte, short,
char), strings and enums.
 You can have any number of case statements within a switch. Each case is followed by the value
(constant or literal) to be compared to and a colon.
 When the variable being switched on is equal to a case, the statements following that case will
execute until a break statement is reached.
 When a break statement is reached, the switch terminates, and the flow of control jumps to the
next line following the switch statement.
 Not every case needs to contain a break. If no break appears, the flow of control will fall
through to subsequent cases until a break is reached.
 A switch statement can have an optional default case, which must appear at the end of the
switch. The default case can be used for performing a task when none of the cases is true. No
break is needed in the default case.

Program to demonstrate Switch statement :


Loop Control Statements

A loop statement allows us to execute a statement or group of statements multiple times based on
checking the result of a condition.

Program to demonstrate do-while:

For Loop:
Important things about for loop:
• We can say, for loop is well structured while loop.
• The initialization of the loop controlling variables can be done in side the for loop.
• Out of three statements, first statement is initialization statement, second one is loop
testing condition, third one is increment/decrement statement.
• We can also run the loop infinitely, just by leaving all the three parts empty.

For each version (Enhanced for) of the for loop:


The general form of the for loop will be as follow:

for(<data_type> <variable > : <collection_name>)


{
//body of the loop
}

Program using enhanced for loop:

The Jump Statements:

Break statement:
The break statement in Java programming language has the following two usages −

 When the break statement is encountered inside a loop, the current iteration is terminated
without executing the following statements after break statements.
 Same time, the loop is immediately terminated and the program control resumes at the next
statement following the loop.

 It can be used to terminate a case in the switch statement (covered in the next chapter).

Break statement is two types: a) break, b) labeled break.

Normal break statement:


In loops, we can terminate the loop , from the current loop, using break.

Example:
Output:

In the above program, it displays the row numbers, which contain the search key. Break statement
terminates inner for loop, when it found search key in the each row.

Labeled break Statement:

In nested loops, we can terminate outer loop , from inner loop, using labeled break.

Now see the same example with labeled break:

Output:

In the above program, it displays the first row number, which contain the search key. Break statement
terminates outer for loop, when it found search key in the array at first time.

Continue Statement:
The continue keyword can be used in any of the loop control structures. It causes the loop to
immediately jump to the next iteration of the loop.
 In a for loop, the continue keyword causes control to immediately jump to the update
statement.
 In a while loop or do/while loop, control immediately jumps to the Boolean expression.

Example:

Output:
Labeled continue statement:

Output:
List of questions asked in previous question papers:

PART-A

1) Support the statement “java byte code gives high performance”.


2) Support the statement “java is dynamic”. Discuss.
3) Support the statement “java is Architecture-Neutral”
4) Support the statement “java is robust”. Discuss.
5) What is importance of Unicode in java? Explain.
6) What is the significance of Java’s byte code?
7) Compare inheritance with polymorphism
8) List the applications of object oriented programming.
9) Differentiate between abstraction and information hiding.
10) What is byte code? How it will be generated?
11) What is Object Oriented Programming? How it is different from Procedural concepts?
12) Write a short note on the features of Object Oriented Programming
13) "Write Once and Run Anywhere" - Support this statement with proper reasoning.
14) Write a Java program to find the value of n!, where n is a given integer.
15) State and explain the atomic elements of Java program.
16) Define class and object in java
17) Give the naming conventions in java.
18) Write java program using ternary operator to find maximum of three numbers.
19) Give a note on type casting in java.
20) What are the naming conventions for Java identifiers?
21) Illustrate type casting in java with an example.

PART-B

1. a) What are the problems with procedure languages? How object oriented languages overcomes the
problems of procedural languages?
b) Give a brief note on Java Virtual Machine.
2. a) Define java byte code. Why java generates byte code?
b) Give the characteristics of OOPs in detail.
3. a) When a procedural language fails? Explain in detail with suitable examples.
b) List and explain java buzzwords.
4. a) List and explain the applications of OOPs.
b) Write the structure of java program.
5. What are java Buzzwords? Explain about them.
6. a) What are the drawbacks of procedural languages? Explain the need of object oriented
programming with suitable program.
b) Discuss the lexical issues of Java.
7. a) Compare procedural languages with object oriented languages
b) Explain the important features of Java.
8. a) Discuss the principles of object oriented languages in detail.
b) What is the role and responsibility of JVM in program execution?
9. a) List and explain Java buzzwords. Which factors are making Java famous language?
b) Give the program structure of Java.
10 a) What is procedural language? Differentiate between procedural language and OOP.
b) What are the features of java? Explain.
11. a) Explain briefly the following object oriented concepts.
i) Abstraction ii) Polymorphism
b) "Java is called Machine Independent language" - Justify this statement with proper explanation.
12. a) Write a Java program to generate a pyramid of numbers for given number N using for loop.
b) Discuss on the advantages and disadvantages of Object Oriented Programming.
13. a) Write a Java program to interchange the rows and columns of a given matrix.
b) Write short note on the following Object Oriented concepts
i) Encapsulation ii) dynamic binding
14. a) Write a Java program to check whether a given number is palindrome or not?
b) Explain about Java Tokens with examples.
15. a) Explain the fundamental forces that necessitated the invention of Java along with the key factors
involved in moulding the java language.
a) Explain the mechanisms that help you to implement the object-oriented model.
16. Explain different categories operators in java.
17. a) Explain Primitive type conversion and casting with examples.
b) Explain precedence rules and associativity concept
18. a) What is an array? How arrays are declared and initialized? Explain with examples.
b) Write a java program to check the given string is a palindrome or not.
19. a) List various types of statements and quote suitable examples for each type.
b) What are the primitive data types in Java? Write about type conversions.
20 a) Write a Java program to find the sum of the squares of the diagonal elements of a square matrix.
b) Write a Java program to sort a given set of strings in the alphabetical order where the strings are
supplied through the command line.
21. a) Java was used for internet applications. Why?
b) Discuss about primitive data types.
c) Write a java program to generate the Fibonacci series.
22. a) Discuss various control structures available in Java.
b) Write a java program to simulate the operation of numerical calculator to perform the functions
Addition (+), Subtraction (-), Multiplication (*) and Division (/).
23. a) What are the bit wise operators supported by Java? Explain each with an example.
b) Illustrate the usage of jump statements in Java with an example program.
ASSIGNMENT:

PART-A
1) Support the statement “java byte code gives high performance”.
2) What is importance of Unicode in java? Explain.
3) What is the significance of Java’s byte code?
4) Compare inheritance with polymorphism
5) Differentiate between abstraction and information hiding.
6) What is byte code? How it will be generated?
7) Illustrate type casting in java with an example.

PART-B
1. a) What are the problems with procedure languages? How object oriented languages overcomes the
problems of procedural languages?
b) List and explain the applications of OOPs.
2. What are java Buzzwords? Explain about them.
3. a) Discuss the principles of object oriented languages in detail.
b) What is the role and responsibility of JVM in program execution?
4. a) Explain Primitive type conversion and casting with examples.
b) Explain precedence rules and associativity concept
5. a) Discuss the lexical issues of Java.
b) Illustrate the usage of jump statements in Java with example.

Programs:

1) Write a Java program to find the value of n!, where n is a given integer.
2) Write java program using ternary operator to find maximum of three numbers.
3) Write a Java program to generate a pyramid of numbers for given number N using for loop.
4) Write a Java program to interchange the rows and columns of a given matrix.
5) Write a Java program to check whether a given number is palindrome or not?
6) Write a Java program to find the sum of the squares of the diagonal elements of a square matrix.
7) Write a Java program to sort a given set of strings in the alphabetical order where the strings are
supplied through the command line.
8) Write a java program to generate the Fibonacci series.
9) Write a java program to simulate the operation of numerical calculator to perform the functions
Addition (+), Subtraction (-), Multiplication (*) and Division (/).
10) Write a java program to check the given string is a palindrome or not.

You might also like