Java Programming Language: Fundamentals and Concepts, Study notes of Computer Science

study notes for second year students

Typology: Study notes

2021/2022

Available from 01/29/2022

babythangarasu
babythangarasu 🇮🇳

4.7

(3)

9 documents

1 / 58

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
JAVA
UNIT I
Object-Oriented Paradigm
It is used to eliminate some of the errors encountered in the procedural approach.
It allows us to decompose a problem into number of entities called Objects and then built data
and functions around the entities.
The combination of data and methods make up an object.
Object = data + methods
The data of an object can be accessed only by the methods associated with the object.
Some of the features of object-oriented paradigm are:
1. Emphasis is on data rather than procedure
2. Programs are divided into Objects.
3. Data structures are designed such that they characterize the objects.
4. Methods that operate on the data of an object are tied together in the data structure.
5. Data is hidden and cannot be accessed by external functions.
6. Objects may communicate with each other through methods.
7. New data and methods can be easily added whenever necessary.
8. Follows bottom-up approach in program design.
Object-Oriented Programming is an approach that provides a way of modularizing programs by
creating partitioned memory area for both data and functions that can be used as templates for
creating copies such modules on demand.
Basic Concepts of Object-Oriented Programming
The important object oriented features are namely:
1. Object 2. Class 3. Methods 4. Data abstraction 5. Encapsulation 6. Inheritance
7. Polymorphism 8. Message passing
Object
This is the basic unit of object oriented programming.
That is both data and function that operate on data are bundled as a unit called as object.
It represents any person, place and etc.
Every object has its own properties and features that illustrate what the object can do.
An object is a specimen of class.
It can be singly recognized by its name.
Class
A class is grouping of objects that have the identical properties, common behavior and shared
relationship.
A class bins the data and its related functions together.
Objects are nothing but variables of type class.
Once a class has been declared, the programmer can create a number of objects associated with
the class.
The syntax used to create an object is similar to the syntax used to create an integer variable in C.
The class defines the characteristics and action of objects.
Method
An operation required for an object when coded in class is called a method.
All objects in a class carry out certain common actions or operations.
The operations that are required for an object are to be defined in the class.
Class A
{
Private
data member1;
data member2;
public:
method1() { }
method2() {}
};
Data Abstraction
It refers to the procedure of representing essential features without including the background
details.
A powerful method to achieve abstraction is through the manipulation of hierarchical
classifications.
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c
pf1d
pf1e
pf1f
pf20
pf21
pf22
pf23
pf24
pf25
pf26
pf27
pf28
pf29
pf2a
pf2b
pf2c
pf2d
pf2e
pf2f
pf30
pf31
pf32
pf33
pf34
pf35
pf36
pf37
pf38
pf39
pf3a

Partial preview of the text

Download Java Programming Language: Fundamentals and Concepts and more Study notes Computer Science in PDF only on Docsity!

JAVA

UNIT I

Object-Oriented Paradigm

 It is used to eliminate some of the errors encountered in the procedural approach.  It allows us to decompose a problem into number of entities called Objects and then built data and functions around the entities.  The combination of data and methods make up an object. Object = data + methods  The data of an object can be accessed only by the methods associated with the object.  Some of the features of object-oriented paradigm are:

  1. Emphasis is on data rather than procedure
  2. Programs are divided into Objects.
  3. Data structures are designed such that they characterize the objects.
  4. Methods that operate on the data of an object are tied together in the data structure.
  5. Data is hidden and cannot be accessed by external functions.
  6. Objects may communicate with each other through methods.
  7. New data and methods can be easily added whenever necessary.
  8. Follows bottom-up approach in program design.  Object-Oriented Programming is an approach that provides a way of modularizing programs by creating partitioned memory area for both data and functions that can be used as templates for creating copies such modules on demand.

Basic Concepts of Object-Oriented Programming

 The important object oriented features are namely:

  1. Object 2. Class 3. Methods 4. Data abstraction 5. Encapsulation 6. Inheritance
  2. Polymorphism 8. Message passing Object  This is the basic unit of object oriented programming.  That is both data and function that operate on data are bundled as a unit called as object.  It represents any person, place and etc.  Every object has its own properties and features that illustrate what the object can do.  An object is a specimen of class.  It can be singly recognized by its name. Class  A class is grouping of objects that have the identical properties, common behavior and shared relationship.  A class bins the data and its related functions together.  Objects are nothing but variables of type class.  Once a class has been declared, the programmer can create a number of objects associated with the class.  The syntax used to create an object is similar to the syntax used to create an integer variable in C.  The class defines the characteristics and action of objects. Method  An operation required for an object when coded in class is called a method.  All objects in a class carry out certain common actions or operations.  The operations that are required for an object are to be defined in the class. Class A { Private data member1; data member2; public: method1() { } method2() {} }; Data Abstraction  It refers to the procedure of representing essential features without including the background details.  A powerful method to achieve abstraction is through the manipulation of hierarchical classifications.

 For example a computer is made of various parts such as CPU, Keyboard, and so on.  We think it as a single unit, but the single unit has several sub-units.  They together do the single task.  By assembling sub-parts we can built a single system.  It is used to define a data type available in the programming language, called as abstract data type  It consists of a set of values and a set of operations. Encapsulation  The packing up of data and functions into a single component is known as encapsulation.  The data is not reachable by the outside functions.  Only those functions that are able to access the data are defined within the class.  With encapsulation we accomplish data hiding.  Data hiding is an important feature using which an object can be used without the user knowing how it works internally.  Fundamental of encapsulation is class. Inheritance  It is the method by which objects of one class get the properties of another class.  It provides the thought of reusability.  The programmer can add new properties to the existing class without changing it.  This can be achieved by deriving a new class from the existing one.  The new class will possess features of both the classes.  For example, re, yellow, and blue are the main colors.  The orange is created from the combination of red and yellow, green is created from yellow and blue and violet is created from red and blue.  The orange has the attributes of both red and yellow, which produces a new effect. Polymorphism  It allows the same function to act in a different way in different classes.  It holds an ability to take more than one form. Dynamic Binding  Binding means connecting one program to another program that is executed in reply to the call.  Dynamic binding is also called as late binding.  The code present in the specified program is unknown till it is executed. Message passing  The objects communicate with one another.  The programming with these objects should be followed with the following steps:

  1. Declaring classes that define objects and their actions.
  2. Declaring objects from classes.
  3. Implementing relation between objects.  Data is transferred from one object to another object.  It consists of indicating the name of the object, function and required data elements. Object.method(data) Benefits of OOP  Through inheritance, we can eliminate redundant code and extend the use of existing classes.  We can built programs from the standard working modules that communicate with one another, rather than having to start writing the code from scratch. This leads to saving of development time and higher productivity.  The principle of data hiding helps the programmer to build secure programs that cannot be invaded by code in other parts of the program.  It is possible to have multiple objects to coexist without any interference.  It is possible to map objects in the problem domain to those objects in the program.  It is easy to partition the work in a project based on objects.  The data-centered design approach enables us to capture more details of a model in an implementation form.  Object-oriented systems can be easily upgraded from small to large systems.  Message passing techniques for communication between objects make the interface descriptions with external systems much simpler,  Software complexity can be easily managed.

Applications of OOP

 The OOP technology is changing the style of software engineers to think, analyze, plan and implement the software.

  1. Familiar, simple and small
  2. Multithreaded and Interactive
  3. High Performance
  4. Dynamic and Extensible

Compiled and Interpreted

 Usually a computer language is either compiled or interpreted.  Java combines both these approaches thus making Java two-stage system.  First, Java compiler translates source code into bytecode instructions.  Second, Java interpreter generates machine code that can be directly executed by the machine that is running the Java program.

Platform-Independent and Portable

 Java programs can be easily moved from one computer to another, anywhere and anytime.  Changes and upgrades in OS, processor and system resources will not force any changes in Java program.  This is the reason why Java has become popular language on Internet which interconnects different kinds of systems worldwide.  Java ensures portability in 2 ways.  First, java compiler generates bytecode instructions that can be implemented on any machine.  Second, the size of the primitive data types are machine-independent.

Object-Oriented

 Java is a true object-oriented language.  All program code and data reside within objects and classes.  Java comes with an extensive set of classes, arranged in packages, that we can use in our programs by inheritance.

Robust and Secure

 Java is a robust language.  It provides many safeguards to ensure reliable code.  It has strict compile time and run time checking for data types.  It is designed as a garbage-collected language relieving the programmers virtually all memory management problems.  Security becomes an important issue for a language that is used for programming on Internet.  Java systems not only verify all memory access but also ensure that no viruses are communicated with an applet.

Distributed

 Java is designed as a distributed language for creating applications on networks.  It has the ability to share both data and programs.  Java applications can open and access remote objects on Internet as easily as they can do in a local system.  This enables multiple programmers at multiple remote locations to collaborate and work together on a single project.

Simple, Small and Familiar

 Many features of C and C++ that are either redundant or sources of unreliable code are not part of Java.  For example, Java does not use pointers, preprocessor header files, goto statement and many others.  To make the language look familiar to the existing programmers, it was modeled on C and C++ languages.

 Java uses many constructs of C and C++, so Java code “looks like a C++” code.

Multithreaded an Interactive

 Multithreaded means handling multiple tasks simultaneously.  This means that we need not wait for the application to finish one task before beginning another.  For example, we can listen to an audio clip while scrolling a page and at the same time download an applet from a distant computer.

 The java runtime comes with tools that support multiprocess synchronization and constructs

smoothly running interactive systems.

High Performance

 Java performance is impressive for an interpreted language, mainly due to use of intermediate bytecode.  Java speed is comparable to the C/C++.

 Java architecture is also designed to reduce overheads during runtime.

Dynamic and Extensible

 Java is a dynamic language.  Java is capable of dynamically linking in new class libraries, methods, and objects.  Java can also determine the type of class through a query, making it possible to either dynamically link or abort the program, depending on the response.  Java supports functions written in other languages such as C and C++.

 These functions are known as native methods. Native methods are linked dynamically at runtime.

Additional Features of J2SE 5.

1. Ease of Development 2. Scalability and Performance 3. Monitoring and Manageability 4. Desktop Client 5. Core XML Support 6. Supplementary character support 7. JDBC RowSet

Ease of Development

 Java 2 Standard Edition (J2SE) 5.0 supports feature, such as Generics, Enhanced for Loop, Autoboxing or unboxing, Typesafe Enums, Varargs, static import and Annotation.  These features reduce the work of the programmer by shifting the responsibility of creating reusable code to the compiler.

 The resulting source code is free from bugs because the errors made by the compiler are less

when compared to those made by the programmers.

Scalability and Performance

 J2SE 5.0 assures a significant in scalability and performance by improving the startup time and reducing the amount of memory used in Java 2 runtime environment.  For example, the introduction of the class, data sharing in the Hotspot Java Virtual Machine (JVM) improves the startup time by loading the core classes from the jar files into a shared archive.

Monitoring and Manageability

 Java supports number of APIs, such as JVM Monitoring and Management API, Sun Management Platform Extension, Logging, Monitoring and Management Interface, and Java Management Extension (JMX) to monitor and manage Java applications.  For example, JVM Monitoring and Management API is used to track the information at the application level and JVM level when deploying a large application.

Desktop Client

 J2SE 5.0 provides enhanced features to meet the requirements and challenges of the Java desktop users.  It provides an improved Swing look and feel called Ocean.  This feature is mainly used for developing graphics applications that require OpenGL hardware acceleration.

Miscellaneous Features

Core XML Support

 It adds powerful XML feature to the Java platform.  Java contains some special packages for interface, to instantiate Simple API for XML(SAX) and Document Object Model (DOM) parsers to parse an XML document.

Supplementary Character Support

 Java adds the 32-bit supplementary character support as part of the Unicode 4.0 support.  The supplementary characters are encoded with UTF-16 values to generate a different character called, surrogate codepoint.

Difference between Java and C

 Java is lot like C but the major difference is the Java is an Object-Oriented Language.  Java does not include the C unique statement keywords sizeof and typedef.  Java does not contain the data types struct and union.  Java does not define the type modifiers keywords auto, extern, register, signed and unsigned.  Java does not support an explicit pointer type.  Java does not have a preprocessor and therefore we cannot use #define, #include and #ifdef statements.

 It is the web browser from Sun Microsystems that enables the display of interactive content on the web, using the Java language.  It is written entirely in Java.  When the Java language was first developed and ported to the Internet, no browsers were available that could run Java applets.  HotJava is currently available for SPARC/Solaris platform as well as Windows 95, Windows NT and Windows XP.

Netscape Navigator

 It is from Netscape Communication Corporation, is a general-purpose browser that can run Java applets.  Available for Windows 95, NT, Solaris and Apple Macintosh, Netscape Navigator is one of the most widely used browser.

 It has many useful features such as visual display about downloading process and indication of

the number bytes downloaded.

Internet Explorer

 It is another popular browser developed by Microsoft for Windows 95, NT and XP.  Both Navigator and Explorer use tool bars, icons, menus and dialog boxes for easy navigation.  Explorer uses a just-in-time (JIT) compiler which greatly increases the speed of execution.

Overview of Java Language

 Java is a general-purpose, object-oriented programming language.  We can develop two types of Java programs:

  1. Stand-alone applications
  2. Web applets  Executing a stand-alone Java program involves two steps:
  3. Compiling source code into bytecodes using javac compiler.
  4. Executing the bytecode program using java interpreter.  Applets are small Java programs developed for Internet applications.  An applet located on a distant computer can be downloaded via Internet and executed on a local client machine using a Java-capable browser.

 We can develop applets for doing everything from simple animated graphics to complex games

and utilities.

Simple Java Program

class sampleone { public static void main(String args[]) { System.out.println(:Java is better than C++); } }

Class Declaration

 The first line declares a class, which is an object-oriented construct  Java is a true object-oriented language so; everything must be placed inside a class.

 Class is a keyword and declares that a new class definition.

Opening Brace

 Every class definition in Java begins with an opening brace “{“ and ends with a matching closing brace “}”.

The main Line

 The third line in the above program defines a method named main.  Every Java application program must include the main() method.  A Java program can have any number of classes but only one of them must include a main method.  The keyword public is an access specifier that declares the main method as unprotected and therefore making it possible to all other classes.  The keyword static, which declares this method as one that belongs to the entire class and not a part of any objects of the class. The main must be declared as static since the interpreter uses this method before any objects are created.  The type modifier void states that the main method does not return any value.

String args[] declares a parameter named as args, which contains an array of objects of the class type String.

The Output Line

 The only executable statement in the program is : System.out.println(:Java is better than C++);  Since Java is a true object-oriented language, every method must be a part of an object.  The println method is a member of the out object, which is a static data member of System class.  The method println always appends a newline character to the end of the string.

 The above line prints the output on the screen.

Java Program Structure

 A Java program may contain many classes of which only one class defines a main method.  Classes contain data members and methods that operate on the data member of the class.  Methods may contain data type declarations and executable statements.  A Java program may contain one or more sections as given below: Suggested Optional Optional Optional Optional Essential

Documentation Section

 The documentation section comprises a set of comment lines giving the name of the program.  Comments explain why and what of classes and how of algorithms.  Java uses a comment /*…../ known as documentation comment.

Package Statement

 The first line allowed in a 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. package student;

Import Statement

 Before any class definitions it may be a number of import statements.  This is similar to the #include statement in C. import student.test;

 This statement instructs the interpreter to load the test class contained in the package student.

Interface Statements

 An interface is like a class but includes a group of method declarations.  It is used only when we wish to implement multiple inheritance features in the program.

Class Definition

 A Java program may contain multiple class definition.  Classes are primary and essential elements of a Java program.

Main Method Class

 Every Java stand-alone program requires a main method as is starting point, this class is the essential part of a Java program.  The main method crates objects of various classes and establishes communications between them.

Java Tokens

 A Java program is basically a collection of classes.  A class is defined by a set of declaration statements and methods containing executable statements.  Smallest individual units in a program are known as tokens.  A Java program is a collection of tokens, comments and white spaces.  It includes five types of tokens. They are:

  1. Reserved Keywords Documentation Section Package Statements Import Statements Interface Statements Class Definitions Main Method Class { Main Method Definition }

Brackets [] Used to declare array types and for dereferencing array values Semicolon ; Used to separate statements Comma , Used to separate consecutive identifiers in a variable declaration. Also used to chain statements together inside a ‘for’ statement Period. Used to separate package names from sub-packages and classes, also used to separate a variable or method from a reference variable.

Java Statements

 The statements in Java are like sentences in natural languages.  A statement is an executable combination of tokens ending with a semicolon.  Statements are executed in sequence in the order in which they appear.  It is possible to control the flow of execution, if necessary, using special statements. Java Statements Statement Description Remarks Empty Statement These do nothing and are used during program development as a place holder Same as C and C++ Labeled Statement Any statement can begin with a label. Such labels must not be keywords, already declared local variables or previously used labels in this module. Labels in Java are used as the arguments of Jump statements. Identical to C and C++ except their use with jump statements Expression Statement Most statements are expression statements. Java has seven types of Expression statements: assignment, Pre-Increment, Pre-Decrement, Post-Increment, Post- Decrement, Method Call and Allocation Expression Same as C++ Selection Statement These select one of several control flows. There are three types of selection statements in Java: if, if-else, and switch Same as C and C++ Iteration Statement These specify how and when looping will take place. There are three types of iteration statements, while, do and for Same as C and C++ except for jumps and labels Jump statement Jump statements pass control to the beginning or end of the current block, or to a labeled statement. Such labels must be on an iteration statement. The four types of Jump statement are break, continue, return and throw C and C++ do not use labels with jump statements Synchronization Statement These are used for handling issues with multithreading Now available in C and C++ Guarding Statement Guarding statements are used for safe handling of code that may cause exceptions. These statements use the keywords try, catch and finally Same as in C++ except finally statement.

Java Virtual Machine

 All language compilers translate source code into machine code for specific computer.  Java compiler also does the same thing.  Java compiler produces an intermediate code known as bytecode for a machine that does not exist.  This machine is called the Java Virtual Machine and it exists only inside the computer memory. Process of compilation Source code Bytecode  The virtual machine code is not machine specific.  The machine specific code is generated by the Java interpreter by acting as an intermediary between the virtual machine. Process of converting bytecode into machine code Java Program Java Compiler Virtual Machine Bytecode Java Interpreter

Virtual Machine Real Machine UNIT II  A programming language is designed to process certain kinds of data consisting numbers, characters and strings and to provide useful output known as information.  The task of processing data is accomplished by executing a sequence of instructions constituting a program.  These instructions are formed using certain symbols and words according to some rigid rules known as syntax rules.

Constants

 Constants refer to fixed values that do not change during the execution of program.  Java supports several types of constants as shown below: JAVA CONSTANTS Machine code

‘\’ Backslash

Variables

 A variable is an identifier that denotes a storage location used to store a data value.  A variable may take different value at different times during the execution of the program.  A variable name can be chosen by the programmer in a meaningful way so as to reflect what it represents in the program. Eg: average height total_height  The rules for defining a variable names are:

  1. They must not begin with a digit
  2. Uppercase and lowercase are distinct. This means that the variable Total is not the same as total or TOTAL
  3. It should not be a keyword
  4. White space is not allowed
  5. Variable names can be of any length.

Data types

 Every variable in Java has a data type.  Data types specify the size and type of values that can be stores.  Java language is rich in its data types.

Integer Types

 It can hold whole numbers.  The size of the values that can be stored depends on the integer data type we choose, Java supports four types of integers. They are byte, short, int and long.  Java does not support unsigned types and therefore all Java values are signed meaning they can be positive or negative.

Size and Range of Integer Types

Type Size Minimum Value Maximum value

byte One byte -128 127

short Two bytes -32, 768 32, 767

Int Four bytes -2, 147, 483, 648 2, 147, 483, 647

Long Eight bytes -9, 223, 372, 036,

Floating Point Types

 It is used to hold numbers containing fractional parts such as 27.59 (known as floating point constants).  There are two kinds of floating point storage. They are:

DATA TYPES IN JAVA

PRIMITIVE

Numeric Integer Floating-point Non-numeric Character (^) Boolean Non-primitive Interface Classes lasses Arrays Integer Byte Short Int Long Floating Point Float (^) Double

 The float type values are single-precision numbers while the double types represent double- precision numbers.  Floating point numbers are treated as double-precision quantities.  To force them to be in single precision mode, we must append f or F to the numbers. Eg: 1.23F

Size and Range of Floating Point Types

Type Size Minimum Value Maximum value

Float Four byte 3.4e-0.38 3.4e+0.

Double Eight bytes 1.7e-308 1.7e-

 All mathematical functions such as sin, cos and sqrt return double type values.  Floating point support a special value known as Not-a-Number(NaN). It is used to represent the result of operations such as division zero by zero, where an actual number is not produced.

Character Type

 To store character constants, Java provides a character data type called char.  The character type assumes a size of 2 bytes but, it can hold only a single character.

Boolean Type

 It is used when we want to test a particular condition during the execution of the program.  There are only two values that a Boolean type can take: true or false.  It is denoted by the keyword Boolean and uses only one bit of storage.  All comparison operators return Boolean type values.  The words true or false cannot be used as identifiers.

Declaration of Variables

 Variables are the names of storage locations  After designing suitable variable names, we must declare them to compiler.  Declaration does three things:

  1. It tells the compiler what the variable name is.
  2. It specifies what type of data the variable will hold.
  3. The place of declaration decides the scope of the variable.  A variable must be declared before it is used.  A variable can be used to store a value of any data type. Syntax: Type variable1, variable2, ……. Variable N;  Variables are separated by commas.  A declaration statement must end with semicolon. Eg: int count; char c1,c2;

Giving Values to Variables

 A variable must be given a value after it has been declared but before it is used in an expression.  This can be done in two ways:

  1. By using an assignment statement
  2. By using a read statement

Assignment Statement

 A simple method of giving value to a variable is through the assignment statement. Syntax: variablename = value Eg: initialvalue = 0;  We can also string assignment expression as x=y=z=0;  It is also possible to assign a value to variable at the time of its declaration. Syntax: type variablename = value; Eg: int finalvalue=100;  The process of giving initial value to variables is known as the initialization.  The ones that are not initialized are automatically set to zero.

Read Statement

 We may also give values interactively through the keyboard using the readLine() method.

 One example pi=3.  Another example is the total number of students whose mark-sheets are analyzed by a “test analysis program”.  The number of students, say 50, may be used for calculating the class total, class average, standard deviation etc.  We face two problems in the use of such programs. They are

  1. Problem in modification of the program

2. Problem in understanding the program

Modifiability

 We may like to change the value of “pi” from 3.142 to 3.14159 to improve the accuracy of calculations or the number 50 to 100 to process the test result of another class.  In both cases, we will have to search throughout the program and explicitly change the value of the constant wherever it has been used.  If any value is left unchanged, the program may produce disastrous outputs.

Understandability

 When a numeric value appears in a program, its use is not always clear, especially when the same value means different things in different places.  For example, the number 50 may mean the number of students at one place and the “pass marks” at another place of the same program. Symbolic constants  Assignment of a symbolic name to such constants frees us from those problems.  For example, we may use the name STRNGTH to denote the number of students and PASS_MARK to denote the pass marks required in a subject.  Constant values are assigned to these names at the beginning of the program.  Subsequent use of these variables in the program has the effect of causing their defined values to be automatically substituted at the appropriate points. Syntax: final type symbolic-name = value; Eg: f inal int STRNGTH = 100; final float PI = 3.  Symbolic names take the same form as variable names. But, they are written in capitals to distinguish them from normal variable names. This is only a convention, not a rule.  After declaration of symbolic constants, they should not be assigned any other value within the program by using an assignment statement.  Symbolic constants are declared for types. This is not done in C and C++ where they are defined using the # define statement.  They can not be declared inside a method. They should be used only as class data members in the beginning of the class.

Type Casting

 Where there is a need to store a value of one type into a variable of another type.

 In such situations, we must cast the value stored by proceeding it with the type name in

parentheses. Syntax: type variable1 = (type) variable2;  The process of converting one data type to another is called casting. Eg: int m=50; byte n = (byte)m; long count = (long) m;  Four integer types can be cast to any other type except Boolean.  Casting into a smaller type may result in a loss of data.  The float and double can be cast to any other type except Boolean.  Casting a floating point value to an integer will result in a loss of the fractional part.

Casts the Results in No Loss of Information

From To

byte short, char, int. long, float, double short int, long, float, double char int, long, float, double

int long, float, double long float, double float double

Automatic Conversion

 It is possible to assign a value of one type to a variable of a different type without a cast.  Java does the conversion of the assigned value automatically.  This is known as automatic type conversion.  Automatic conversion is possible only if the destination type has enough precession to store the source value. byte b = 75; int a = b;  The process of assigning a smaller type to a larger one is known as widening or promotion and that of assigning a larger type to a smaller one is known as narrowing. class A { public static void main (String args[]) { System.out.println(“Variables created”); char c=’x’; byte b=50; short s=1996; int i=12345; System.out.println(“C=”+c); Output System.out.println(“B=”+b); V ariables created System.out.println(“S=”+s); c=x System.out.println(“I=”+i); b= System.out.println(“Types converted”); s= short s1=(short)b; i= short s2=(short)i; //produces incorrect result Types converted System.out.println(“(short)b=”+s1); (short)b= System.out.println(“(short)i=”+s2); (short)i=- } }

Getting Values of Variables

 Java supports two output methods that can be used to send the result to the screen.

  1. print() method // print and wait
  2. println() method // print a line and move to the next line  The print() method sends information into a buffer.  This buffer is not flushed until a newline character is sent.  As a result, the print() method prints output on one line until a newline character is encountered. System.out.print(“Hello”); System.out.print(“world”);  Will display the words Hello world on one line.  The println() method takes the information provided and display it on a line followed by a line feed. System.out.println(“Hello”); System.out.println(“world”);  Will produces the following output. Hello World class A { public static void main(String args[]) { for(int i=1; i<=9; i++) { for(int j=1; j<=i; j++) {

a*b = 56 a/b = 3 (decimal part truncated) integer division a%b = 2 (remainder of integer division)  For modulo division, the sign of the result is always the sign of the first operand. Eg: -14 % 3 = - 14 % -3 = 2

Real Arithmetic / Floating Pont Arithmetic

 Floating Point Arithmetic involves only real operands of decimal or exponential notation.  Unlike C and C++, % can be used with floating point data.  The floating point modulus operator returns the floating point equivalent of an integer division. Eg: a = 20.5f b = 6.4f a + b = 26. a / b = 3. a % b = 1.

Mixed mode Arithmetic

 When one of the operands is real and the other is integer the expression is a mixed mode arithmetic expression. Eg: 15/10.0 = 1. 15/10 = 1

Relational Operator

 We often compare two quantities, and depending on their relation, take certain decision.  For example compare the age of two persons, or the price of two items etc.  The value of a relational expression is either one or zero.  The arithmetic operators have a higher priority over relational operators.  It is 1 if one is the specified relation is true and zero if it is false For eg: 10<20 is true 20<10 is false Relational Operators Operators Meaning < is less than <= is less than or equal to

is greater than = is greater than or equal to = = is equal to != is not equal to  A simple relational expression contains only one relational operator and is of the form: ae-1 relational operator ae-  ae-1 and ae-2 are arithmetic expressions, which may be variables or constants. Relational Expressions Expression Value 4.5<=10 TRUE 4.5<-10 FALSE -35>=0 FALSE 10<7+5 TRUE 4+3= =5+2 TRUE  Relational expressions are used in decision making statements.

Logical operator

 Logical Operators are used when we want to test more than one condition and make decisions.  Here the operands can be constants, variables and expressions Logical Operators Operators Meaning && Logical AND || Logical OR ! Logical NOT For Example: a > b && x == 10  An expression of this kind which combines two or more relational expressions is termed as a logical expression or a compound relational expression.

Assignment Operator

 Used to assign the result of an expression to a variable.  = is the assignment operator.

 In addition Java has a set of ‘short hand’ assignment operators of the form v op = exp ;  Where v is a variable, exp is an expression and op is a Java binary operator  The operator op= is known as shorthand assignment operator  The assignment statement v op = exp ; x+= is equivalent to v = v op(exp); x = x + 1 Shorthand Assignment Operators Assignment Operator Shorthand Operator a = a + 1 a += 1 a = a - 1 a -= 1 a = a * (n+1) a *= n+ a = a / (n+1) a /= n+ a = a % b a %= b

Increment and Decrement Operators

 The increment operator is ++ and decrement operator is –  The Operator + + adds 1 to the operand while -- subtracts 1,  Both are unary operators ++m; or m++; equivalent to m = m + 1; or m += 1; // prefix --m; or m--; equivalent to m = m - 1; or m -= 1; // postfix  A Prefix operator first adds 1 to the operand and then the result is assigned to the variable on left.  A postfix operator first assigns the value to the variable on the left and the increments the operand. class A Output { m= public static void main(String args[]) n= { ++m= int m = 10, n = 20; n++= System.out.println(“m=” +m); m= System.out.println(“n=” +n); n= System.out.println(“++m=” + ++m); System.out.println(“n++=” +n++); System.out.println(“m=” +m); System.out.println(“n=” +n); } }

Conditional operator

 The character pair ?: is used to check a condition and Select a Value depending on the Value of the condition.  It is also called as ternary operator Variable = (condition)? Value 1 : Value 2;  If the Value of the condition is true then Value 1 is e valued assigned to the varable, otherwise Value2. Eg: big = (a>b)? a:b;  This exp is equal to if (a>b) big = a; else big = b;

Bitwise operator

 It is used to perform operations at binary level i. e. bitwise.  These operators are used for testing the bits, or Shifting them right or left.  These operators are not applicable to float or double. B itwise Operators Operators Meaning & bitwise AND ! bitwise OR ^ bitwise exclusive OR