Skip to content

Chapter 1 : Introduction to Java

Saket Khopkar edited this page Jan 1, 2022 · 12 revisions

Fundamental / Basic concepts of Object Oriented Programming:

  1. Objects:
  • Objects are the basic run time entities in object oriented system.
  • Objects are the variables of the type class.
  • They may represent a place, a person, a bank account, a table of data, or any item that the program must handle. They may represent user defined data such as time, limit.
  • Each object contains data and code (function) to manipulate the data.
  • Example: Customer and Account are two objects in a program, then Customer object can send a message to the Account object requesting for the bank balance.
  1. Classes:
  • Class is a collection of objects of similar types.
  • Class is a user defined data type.
  • Once a class has been defined, we can create any number of objects of that class.
  • Class contains variables (data members) and functions (methods or member functions).
  • Example: fruit mango, apple, banana; Here, fruit is a class and mango, apple, banana are objects of the class fruit.
  1. Data Abstraction:
  • Abstraction refers to the act of representing essential features without including the background details or explanations.
  • Classes are defined as a list of attributes (variables) and functions to operate on these attributes.
  • The attributes are called as data members and functions are called as methods or member functions.
  • Classes use the concept of data abstraction hence they are known as Abstract Data Types (ADT).
  1. Encapsulation:
  • The wrapping up of data and functions into a single unit (called class) is known as encapsulation.
  • Data encapsulation is the most striking feature of the class.
  • The data is not accessible to outside world, and only those functions which are wrapped in the class can access it.
  • This insulation of the data from direct access by the program is called as data hiding or information hiding.
  1. Inheritance:
  • The mechanism of deriving new class from old one is called as inheritance.
  • Old class is called as base or super class and new class is called as derived or sub class.
  • Inheritance provides the idea of reusability. In inheritance instead of creating the same which already exists, we can reuse it.
  • Reusability increase reliability and saves time as well as money.
  • A derived class inherits some or all properties of base class.
  1. Polymorphism:
  • Polymorphism means the ability to take more than one form.

Operator Overloading:

  • The process of making an operator to exhibit different behaviors in different instances is known as operator overloading.
  • Example: 10 + 15 =25 Here, + add two numbers, because operands are numbers. “New”+”York”=”NewYork” Here, + concatenates (join) two strings, because operands are strings. So, here + operator is overloaded.

Function Overloading:

  • Using single function name to perform different types of task is called as function overloading.
  • Example :- Shape -> Draw() . Here Shape is the base class and Draw is its method.
  • Circle -> Draw(), Box -> Draw(), Triangle -> Draw() These are the method that are inherited from the Shape base class.
  • Here, Draw() method does different function in different classes, yet its name is same.
  1. Dynamic Binding:
  • Binding refers to the linking of a procedure call (function call) to the code (function body) to be executed in response to the call.
  • Dynamic binding means that the code associated with a given procedure call is not known until the call at run time.
  • Dynamic binding is associated with polymorphism and inheritance.
  • In above diagram, by inheritance, every object will have this ‘draw’ procedure. Its algorithm is unique to each object and so the draw procedure will be redefined in each class that defines the object.
  • At run time, the code matching the object under current reference will be called.
  1. Message Passing:
  • Object Oriented Program consists of a set of objects that communicate with each other.
  • The process of programming in an object oriented language therefore involves the following basic steps:
  1. Creating classes that defines objects and their behavior.
  2. Creating objects from class definitions.
  3. Establishing communication among objects.
  • Objects communicate with one another by sending and receiving information.
  • A message for an object is a request for execution of a procedure, and therefore will invoke a function (procedure) in receiving objects that generates the desired results.
  • Message passing involves specifying the name of the object, the name of the function (message) and the information to be sent.
  • Objects have a life cycle. They can be created and destroyed. Communication with an object is feasible as long as it is alive.

Benefits of Object Oriented Programming

  • Inheritance eliminates redundant (repeated) code. We can derive new class from existing class. It gives reusability, hence saves development time.
  • Due to data hiding programs becomes more secure.
  • It is possible to have multiple instances of an object to co-exist without any interference.
  • It models real-world problems very well.
  • It is easy to partition the work in a project based on objects.
  • Object oriented systems can be easily upgraded from small to large systems.
  • Software complexity can be easily managed.
  • Message passing technique for communication between objects makes the interface description with external systems much simpler.
  • The data centered design approach is used.

Applications of Object Oriented Programming

  • Real-Time Systems
  • Simulation and Modeling
  • Object-Oriented Databases
  • Hypertext, Hypermedia and Expertext
  • Artificial Intelligence and Expert Systems
  • Neural Networks and Parallel Programming
  • Decision Support and Office Automation Systems
  • CIM / CAM / CAD Systems

Java Features

  1. Compiled and Interpreted:
  • Usually computer language is compiled or interpreted. But Java combines both these approaches thus making Java a two stage system.
  • First, Java compiler translates source code into bytecode. Bytecode is intermediate code and it is not machine code.
  • In Second stage, Java interpreter generates machine code that can be directly executed by the machine that is running the Java program.
  • We can thus say that Java is compiled and interpreted language.
  1. Platform-Independent and Portable:
  • Portability is most significant feature of Java over other languages.
  • Java programs can be easily moved from one computer system to another, anywhere and anytime.
  • Changes and upgrades in operating systems, processors and system resources will not force any changes in Java programs.
  • Due to above reasons Java is popular language for programming on Internet which interconnects different types of systems worldwide.
  • We can download a Java applet from a remote computer onto our local system via Internet and execute it locally. This makes the Internet an extension of the user’s basic system providing practically unlimited number of accessible applets and applications.
  • Java ensures portability in two ways. First, Java compiler generates bytecode that can be implemented on any machine. Secondly, the sizes of the primitive data types are machine-independent.
  1. Object Oriented:
  • Java is a true object-oriented language. Almost everything in Java is an object. 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.
  • The object model in Java is simple and easy to extend.
  1. 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 garbage-collected language, which relieves the programmer from memory management problems.
  • It incorporates exception handling, which captures run time errors and eliminates any risk of crashing the system.
  • Security is very important for a language that is used for programming on Internet.
  • Java verifies all memory access and ensures that no viruses are communicated with an applet.
  • The absence of pointers in Java ensures that programs cannot gain access to memory locations without proper authorization.
  1. Distributed:
  • Java is designed as a distributed language for creating applications on networks. It has 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.
  1. Simple, Small and Familiar:
  • Java is a small and simple language. 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.
  • Java also eliminates operator overloading and multiple inheritance.
  • To make the language look familiar to the existing programmers, it was modelled on C and C++ and therefore, Java code “looks like a C++ code. In fact, Java is a simplified version of C++.
  1. Multithreaded and Interactive:
  • Multithreaded means handling multiple tasks simultaneously.
  • Java supports multithreaded programs. 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 distant computer. This feature greatly improves the interactive performance of graphical application.
  • The Java runtime comes with tools that support multiprocessor synchronization and construct smoothly running interactive system.
  1. High Performance:
  • Java performance is impressive though it is an interpreted language. This is mainly due to bytecode.
  • According to Sun, Java speed is comparable to the native C / C++. Java architecture is also designed to reduce overheads during runtime.
  • Incorporation of multithreading enhances the overall execution speed of Java programs.
  1. Dynamic and Extensible:
  • Java is 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 programs support functions written in other languages such as C and C++. These functions are known as native methods. This facility enables the programmers to use the efficient functions available in these languages. Native methods are linked dynamically at runtime.

Why Java is so Popular on Internet?

Applet:

  • Java is strongly associated with Internet. Java is used to create applet or we can download the remote applet and run them on local machine using java enabled web browser such as HotJava.
  • Applets have made the Internet a true extension of the storage system of the local computer.
  • Internet users can setup their websites containing Java applets that could be used by other remote users of Internet. This ability of Java to hitch a ride on Information Superhighway has made Java a unique programming language for Internet. Hench Java is popularly known as Internet Language.

Security:

  • Security is very important for a language that is used for programming on Internet.
  • Java verifies all memory access and ensures that no viruses are communicated with an Applet.
  • The absence of pointers in Java ensures that programs cannot gain access to memory locations without proper authorization.

Portability:

  • Java ensures portability in two ways. First, Java compiler generates bytecode that can be implemented on any machine. Secondly, the sizes of the primitive data types are machine-independent.

As the java support applet, portability and security features which are the very important features related to internet hence Java is popular on Internet.


What is Byte Code?

  • The output produced by the Java compiler is not executable code, it is intermediate code called as byte code.
  • Byte code is highly optimized set of instructions executed by Java run time system (JVM).
  • Byte code is machine independent.

What is JVM?

  • Java Compiler produces an intermediate code 'bytecode' for machine that does not exist. This machine is known as Java Virtual Machine and it only exists inside computer memory.
  • It is a simulated computer inside the computer and does all major functions of real computer.
  • The virtual machine code is not machine specific. The Machine-Specific code (known as Machine Code) is generated by Java Interpreter by acting as intermediary between virtual machine and real machine.

Java Environment

  • Java Environment includes large number of development tools and hundreds of classes and methods.
  • The development tools are the part of Java Development Kit (JDK) and classes and methods are the part of Java Standard Library (JSL), also known as Application Programming Interface (API).

Java Development Kit (JDK)

  • The JDK comes with collection of tools that are used for developing and running Java Programs. They include:
  1. appletviewer (for viewing applets) :- Enables us to run applets (without actually using Java compatible browser).
  2. javac (java compiler) :- Translates Java source code to byte code files that interpreter can understand.
  3. java (java interpreter) :- Runs applets and applications by reading and interpreting bytecode files.
  4. javap (java disassembler) :- Enables us to convert bytecode files into program description.
  5. javah (java for C header files) :- Produces header files for use with native methods.
  6. javadoc (for creating HTML Document) :- Creates HTML format documentation from Java source code files.
  7. jdb (java debugger) :- Helps us to find errors in our programs.

Application Programming Interface (API)

  • The Java Standard Library (JSL or API) includes hundreds of classes and methods grouped into several functional packages. Most commonly used packages are:
  1. Language Support Package :- A collection of classes and methods required for implementing basic features of Java.
  2. Utilities Package :- A collection of classes to provide utility functions such as Date and Time.
  3. Input / Output Package :- A collection of classes required for input and output manipulation.
  4. Networking Package :- A collection of classes for communicating with other computers via Internet.
  5. AWT Package :- The Abstract Window Toolkit package contains classes that implements platform independent Graphical User Interface.
  6. Applet Package :- This includes set of classes that allow us to create Java Applets.

Simple java program

  • File name :- SampleOne.java
class SampleOne
{
    public static void main(String args[])
    {
        System.out.println("Hello World");
    }
}
  • Class Declaration The first line declares a class, which is an object oriented construct. As stated earlier, Java is true object oriented so everything must be placed inside the class. 'class' is a keyword that and declares new class definition as follows. 'SampleOne' is a java identifier that specifies the name of the class to be defined.

  • Opening Brace Every class in Java starts off with opening brace and should close with same matching brace.

  • The Main Line The third line where main function is defined. Every java program must include a main method. This is the starting point for the interpreter to begin execution of program. A java application can have many classes but one of them must have a main() method to initiate the execution. Note that :- Java Applets will not use main() method.

  1. Public :- main() method stands unprotected and is accessible to all other classes.
  2. Static :- main() method belongs to class, not to any object.
  3. void :- main() does not return anything.
  • The Output Line Since Java is true object oriented language, every method must be part of the object. The 'println' method is a member of 'out' object which is static member of 'System' class. Every statement must end with semicolon.

Java Program Structure

Documentation Section:

  • It consists of set of comments lines that provides the name of the program, programmer and other details about the program.
  • Multiline comment /------/ and single line comment //------ both are available in Java. Java uses a third style of comment /**------*/ known as documentation comment. This form of comment is used for generating documentation automatically.

Packages Statement:

  • It is used to declare and create user defined packages. It is not necessary that user defined class belongs to this package. Syntax: package package_name; Ex: package student;

Import Statements:

  • It is used to import and use readymade classes and interfaces from the packages. It is similar to #include statement in C. Ex: import java.lang.*;
  • This statement will import all the classes and interfaces form the lang package of Java.

Interface Statements:

  • Interface is like a class, but it contains only abstract methods and final, static variables. It is generally used to implement multiple inheritance.

Class Definition:

  • A Java program may contain multiple class definitions. Classes in this section doesn’t have main().

Main Method Class:

  • Every Java program should have main( ) function. Main method creates objects of various classes and establishes communication between them. Java programs start their execution from main method. It is the only essential part of the Java program.

Command Line Arguments

  • Command Line Arguments are parameters that are supplied to the application program at the time of invoking its execution.
  • They must be supplied at the time of its execution after the file name.
  • In the main (), the args is declared as an array of strings known as string objects. Any arguments provided in the command line at the time of program execution, are passes to the array args as its elements.
  • Using index or subscripted notation we can access the individual elements of an array.
  • The number of elements in the array args can be getting with the length parameter, like: cnt = args.length;
  • Below Program illustrates the use of command line arguments.
// WAP to find sum and average of three numbers.
import java.lang.*;
import java.io.*;
class CmdDemo
{
    public static void main(String args[])
    {
        int n1,n2,n3,sum,avg;
        int n1=Integer.parseInt(args[0]);
        int n2=Integer.parseInt(args[1]);
        int n3=Integer.parseInt(args[2]);
        sum=n1+n2+n3;
        avg=sum/3;
        System.out.println(“Sum = “ + sum);
        System.out.println(“Average = “ + avg);
    }
}
// Output: C:\>javac CmdDemo.java
// C:\> java CmdDemo 10 30 20
// Sum =30
// Average = 20
// WAP to accept and print student details.
import java.lang.*;
import java.io.*;
class Student
{
    public static void main(String args[])
    {
        String name = args [0];
        int rollno=Integer.parseInt(args[1]);
        float per=Float.parseFloat(args[2]);
        System.out.println(“Name = “ + name);
        System.out.println(“Roll Number = “ + rollno);
        System.out.println(“Percentage = “ + per);
    }
}
// Output: C:\>javac Student.java
// C:\> java Student Amol 12 86.5
// Name = Amol
// Roll Number = 12
// Percentage = 86.5

Java Tokens

  • Tokens are the smallest individual unit of the Java-Program.
  • Every meaningful entry in a Program is known as Token.
  • Every Java program is a collection of Tokens.
  • There are 5 types of tokens.

Keywords

  • Keywords are the words whose meaning is fixed and already known to the Complier.
  • Keywords are also called as reserved words.
  • There 50 keywords in Java.
  • Keywords are case sensitive and always written in lower case letters.
  • Note: boolean, true, false and null are not keywords, but we should not try to use them as user defined names in Java programs.

Identifiers

  • Identifier refers to the names given to variables, class, functions or arrays.
  • These are user defined names and consist of sequence of letters and digits.
  • Ex: num1, main, a, b, n1, etc.

Rules for Naming Identifiers:

  1. The first character in the identifier name must be an alphabet or underscore.
  2. It can be on any length.
  3. Identifier should not be a keyword.
  4. Uppercase and lowercase are significant.
  5. No commas or blank spaces are allowed within an identifier name.
  6. Must consist of only letters, digits, underscore or dollar sign.

Literals

  • Literals are sequence of characters (digits, letters and other characters) that represents constant value to be stored in variable.
  • Types of Literals:
  1. Integer literals
  2. Floating point literals
  3. Character literals
  4. String literals
  5. Boolean literals

Operators

  • An operator is a symbol that tells the computer to perform certain mathematical or logical calculations. Operators are used in programs to manipulate data and variables.
  • There are 8 types of operators are available in Java.

Constants

  • Constants in Java refer to fixed values that do not change during the execution of a program.

Numeric Constants: These constants refer to the sequence of digits. It may have decimal point and + or - sign.

  1. Integer Constants: It refers to sequence of digits without decimal point. It is of three types octal, decimal and hexadecimal. Ex: 78, -78, 0 etc.

  2. Real Constants: Numbers containing fractional part separated by a decimal point is called real constant. It may also have + or – sign. Ex: 1.2, 3.14, -3.24 etc.

Character Constants: These constants contain letters (alphabets) and any other character from Java character set.

  1. Single Character Constants: It contains any single character from Java character set & enclosed in a single quotation mark. These are represented by their ASCII values within computer. Ex: ’A’ ’b’ ’7’ ’+’ ’;’ etc.

  2. String Constants: Set of characters enclosed in double quotation mark is called as string constant. Ex: “Disha” “2015” etc. Backslash Character Constants:

  • These constants are used in output functions.
  • These are also called as escape sequences.
  • Note that each one represents one character, although they contain two.

Variables

Variable is a quantity whose value changes continuously throughout the program execution. Rules for variable names:

  1. The first character in the variable name must be an alphabet or underscore.
  2. Variable name can be of any length.
  3. Variable should not be a keyword.
  4. Uppercase and lowercase are significant.
  5. No commas or blank spaces are allowed within a variable name.
  6. Must consist of only letters, digits, underscore or dollar sign.

Types of variables: As variables are used to hold constants they are of constants type:

  1. Numeric Variables: These are used to represent numeric constants. Ex. prize, marks, etc.
  2. Character Variables: These are used to represent single character value. Ex. gender.
  3. String Variables: These are used to represent string values. Ex. city, stud_name, etc.

Declaration of variables: After designing suitable variable names, we must declare them to the compiler. Declaration of variables must be done before they are used in the program. Declaration does 3 things:

  1. It specifies what type of data the variable will hold.
  2. It tells compiler what the variable name is.
  3. It specifies how many bytes it will require to store. Syntax: data-type variable1, variable2, ---, variable-n; Declaration must end with semicolon (;). Ex: int marks; char gender; float percentage;

Initialization of Variables: Using Assignment Statement: It refers to assigning values to variables. Syntax: variable-name = value; Ex: marks = 75; gender = ’M’; percentage = 73.85f;

It is also possible to assign a value to the variable at the time of declaration. Syntax: data-type variable-name = value; Ex: int marks = 75; It is also possible to assign values to more than one variable in one statement. Ex: p = q = r =0;

Using Read Statement: We can give values interactively at run time through keyboard using readline() method. readLine() reads the input as a String which can be converted to required datatype using Wrapper classes. readLine() can generate IOException, so it needs to write in try block; otherwise we need to use throws IOException.

// Run time i/o using readLine().
import java.io.*;
class Demo
{
    public static void main(String args[]) throws IOException
    {
        String nm;
        int rn;
        float pr;
        InputStreamReader i=new InputStreamReader(System.in);
        BufferedReader b=new BufferedReader(i);
        System.out.print("Input name: ");
        nm = b.readLine();
        System.out.print("Input rollno: ");
        rn = Integer.parseInt(b.readLine());
        System.out.print("Input percentage: ");
        pr = Float.parseFloat(b.readLine());
        System.out.println("Name="+nm);
        System.out.println("Roll No="+rn);
        System.out.print("Percentage="+pr);
    }
}
// Output: Input name: Disha
// Input rollno: 23
// Input percentage: 86.4
// Name = Disha
// Roll No = 23
// Percentage = 86.4

Data Types

  • Data Type is a term which represents the type of value hold by the variable. Every variable in Java has the data type. Data type also specifies size of the value that can be stored.
  • Integer Types: Integers are whole numbers. Java has 4 types of integer storage, namely byte, short, int and long. Java does not support unsigned types and therefore all Java values are signed. Ex: 15, 567,-30, 0, etc.
  • Floating Point Types: It contains numbers with decimal point and with or without sign. There are two types of floating point storage, namely float (single-precision) and double (double-precision). In java floating point numbers are treated as double-precision quantities. To force them to be single-precision, we must append f or F to the numbers, like 3.14f or 3.14F. Ex: 15.7, 56.7, +30.5, -5.7, etc.
  • Character Type: A single character can be defined as a character (char) type data. It requires 2 bytes. Ex: ’A’, ’a’, ’-’, ’4’, etc.
  • Boolean Type: It is used to store true or false values. It is used to test the condition. It is denoted by boolean and require only 1 bit of storage.

Scope of variable

  • The area of the program where the variable is accessible (usable) is known as scope. Java variables are classified into three kinds: Instance Variables:
  • These are declared inside a class.
  • These are created when objects are instantiated (created) and therefore they are associated with the objects.
  • Separate copy of the variable will be created for every individual object of the class.
  • They take different values for each object.

Class Variables:

  • These are declared inside the class.
  • Class variables are global to a class and belong to the entire set of objects of that class.
  • Only one memory location is created for each class variable.

Local Variables:

  • These are declared inside a method / function.
  • These can be used only inside the method (in which it is declared). It cannot be used outside of that method.
  • These can also be declared inside the program blocks between { and }.
  • These can be used within only that block and cannot be used outside of that block.

Symbolic Constants

  • Symbolic constants refer to the variable name having value which cannot be changed.
  • They are also known as constant identifier or named constants.
  • For example, PI=3.14, this value cannot be changed so we can declare it as symbolic constant.

Rules:

  • Symbolic constants names must be in capital letters (convention not a rule).
  • After declaration of symbolic constants, they should not be reassigned any other value.
  • Data types of symbolic constants must be specified.
  • Symbolic constants cannot be declared inside a method.

Syntax: final data-type symbolic-name = value;

Example: final float PI = 3.14f; Advantages:

  • Modification of the program becomes easy.
  • Understanding of the program becomes easy.

Typecasting

  • Casting is very necessary when a method returns a type which we don't require.
  • Syntax :- type variable = (type) variable2;
// WAP to convert given number of days into months and day.
import java.lang.*;
import java.io.*;
class DayMonth
{
    public static void main(String args[])
    {
        int num=Integer.parseInt(args[0]);
        int days = num % 30;
        int month = num / 30;
        System.out.println(num+” days = “+month+” Month and “+days+” days.”);
    }
}
// Output:
// C:\>javac DayMonth.java
// C:\> java DayMonth 76
// 76 days = 2 Month and 16 days.

Operators and Expressions

An operator is a symbol that tells the computer to perform certain mathematical or logical calculations. Operators are used in programs to manipulate data and variables.

  1. Arithmetic Operators: Arithmetic Operators are used to do arithmetic operations in a program. Expression containing Arithmetic Operator is called as Arithmetic Expression. Suppose, a= 7 and b = 3

Categories of Arithmetic Expressions: i. Integer Arithmetic: When both the operands in a single arithmetic expression such as a + b are integers, the expression is called as integer expression, and operation is called integer arithmetic. Integer arithmetic always results in an integer value. Ex: 2 + 3 = 5

ii. Real Arithmetic: When both the operands in a single arithmetic expression such as a + b are real, the expression is called as real expression, and operation is called real arithmetic. Real arithmetic always results in a real value.

Ex: 2.5 + 3.2 = 5.7 iii. Mixed-mode Arithmetic: When one of the operand is real and other is integer, the expression is called as mixed-mode arithmetic expression and operation is called as mixed-mode arithmetic. Ex: 5 / 2.0 = 2.5

// WAP to demonstrate Arithmetic Operators.
import java.lang.*;
class Arithmetic
{
    public static void main(String args[ ])
    {
        int a = Integer.parseInt(args[0]);
        int b = Integer.parseInt(args[1]);
        System.out.println(“Add = “ + (a+b));
        System.out.println(“Sub = “ + (a-b));
        System.out.println(“Mul = “ + (a*b));
        System.out.println(“Div = “ + (a/b));
        System.out.println(“Rem = “ + (a%b));
    }
}
// Output: C:\> javac Arithmetic.java
// C:\> java Arithmetic23 5
// Add = 28
// Sub = 18
// Mul = 115
// Div = 4
// Rem = 3
  1. Relational Operators
  • Relational Operators are used to compare values. It results in true or false. Expression containing Relation Operator is called as Relational Expression.
// WAP to demonstrate Relational Operators.
import java.lang.*;
class Relational
{
    public static void main(String args[ ])
    {
        System.out.println(“Result 1 = “ + (4<9));
        System.out.println(“Result 2 = “ + (9<=9));
        System.out.println(“Result 3 = “ + (4>9));
        System.out.println(“Result 4 = “ + (4>=9));
        System.out.println(“Result 5 = “ + (9==7+2));
        System.out.println(“Result 6 = “ + (9!=8));
    }
}
// Output: C:\> javac Relational.java
// C:\> java Relational
// Result 1 = true
// Result 2 = true
// Result 3 = false
// Result 4 = false
// Result 5 = true
// Result 6 = true
  1. Logical Operators
  • Logical Operators are used to combine two or more Relational Expressions. It results in true or false. Expression containing Logical Operator is called as Logical Expression or Compound Relational Expression.
// WAP to demonstrate Logical Operators.
import java.lang.*;
class Logical
{
    public static void main(String args[ ])
    {
        System.out.println(“Result 1 = “ + (7> 6 && 7 < 10));
        System.out.println(“Result 2 = “ + (7 < 6 && 7 < 10));
        System.out.println(“Result 3 = “ + (7 < 6 || 7 < 10));
        System.out.println(“Result 4 = “ + (7 < 6 || 7 > 10));
        System.out.println(“Result 5 = “ + !(7>6));
    }
}
// Output: C:\> javac Logical.java
// C:\> java Logical
// Result 1 = true
// Result 2 = false
// Result 3 = true
// Result 4 = false
// Result 5 = false
  1. Assignment Operator
  • It is used to assign (store) the value on the right to the variable on left of ’=’ sign.
  • Syntax: variable = expression;
  • Ex: c = a + b, here result of a + b will be assigned to c.

Shorthand assignment operators:

  • Java also has shorthand assignment operators as follows:
  • Syntax: variable op= expression;
  • Example :- a = a + 1 will become a += 1.
  1. Increment and Decrement Operators
  • Increment operator ’++’ is use to increase the value of operand by 1 and decrement operator ’- -’ is used to decrease the value of operand by 1.

  • Syntax: variable ++ OR ++variable OR variable-- OR --variable

  • Suppose, m=5 m++ = 6 and ++m = 6 m-- = 4 and --m = 4 So, m++ (postfix) and ++m (prefix) results similarly when they form the statements independently. Difference between postfix and prefix: Difference 1: Suppose, m=5 y = ++m; Result: y = 6 and m=6 y = m++; Result: y = 5 and m=6 y = --m; Result: y = 4 and m=4 y = m--; Result: y = 5 and m=4 So, a prefix operator first adds 1 to the operand and then the result is assigned to the variable on left. On the other hand, a postfix operator first assigns the value to the variable on left and then increments the operand.

  • Difference 2: Suppose, m=5 System.out.println(++m); Result: 6 System.out.println(m++); Result: 5

// WAP to demonstrate Increment and Decrement Operators.
import java.lang.*;
class IncrDecr
{
    public static void main(String args[ ])
    {
        int m = 10, n = 20;
        System.out.println(“Value of m = “ + ++m);
        System.out.println(“Value of n = “ + n++);
        System.out.println(“Value of m = “ + m);
        System.out.println(“Value of n = “ + n);
    }
}
// Output: C:\> javac IncrDecr.java
// C:\> java IncrDecr
// Value of m = 11
// Value of n = 20
// Value of m = 11
// Value of n = 21
  1. Conditional Operator
  • A ternary operator pair ’? :’ in C is called as Conditional Operator. Expression containing Conditional Operator is called as Conditional Expression. It can be nested.

  • Syntax: variable = exp1 ? exp2 : exp3;

  • In above syntax, exp1 is always relational or logical expression. exp1 is calculated first and it results in true or false. If it is true exp2 is evaluated and that becomes the value of the variable, if not, exp3 is evaluated and that becomes the value of the variable.

  • Ex: a = 10; b = 15; x = (a > b) ?a : b; Here, x = b i.e. x = 15 Note: Same can be achieved by if—else statement: if(a > b) x = a; else x = b;

// WAP to find greatest of three numbers using Nested Conditional Operator.
import java.lang.*;
class CO
{
    public static void main(String args[ ])
    {
        int a = Integer.parseInt(args[0]);
        int b = Integer.parseInt(args[1]);
        int c = Integer.parseInt(args[2]);
        int max = (a>b) ? (a>c ? a : c) : (b>c ? b : c);
        System.out.println(“Greatest = “ + max);
    }
}
// Output: C:\> javac CO.java
// C:\> java CO 15 12 18
// Greatest 18
  1. Bitwise Operators:
  • Bitwise Operators are used to perform operations on individual bits. Bitwise Operators can operate upon int and char but not on float and double. Expression containing Bitwise Operator is called as Bitwise Expression.

  • One’s Complement: It converts 1 to 0 and 0 to 1. Ex: If a = 11010111 then ~a = 00101000

  • Bitwise Operators:

  • Left Shift Operator: The left shift operator is represented by <<. It shifts each bit to the left by specified number of position. Left shift by 1 is having the effect of multiplication by 2; left shift by 2 is having the effect of multiplication by 4, and so on. Ex: If variable a= 00010101, then, a<< 1 results in 00101010 and a>> 2 results in 01010100.

  • Right Shift Operator: The right shift operator is represented by >>. It shifts each bit to the right by specified number of position. Right shift by 1 is having the effect of integer division by 2, right shift by 2 is having the effect of integer division by 4, and so on. Ex: If variable a = 11010111, then, a>> 1 results in 01101011 and a>> 2 results in00110101.

  • Right Shift with Zero Fill: The >> operator preserves the leftmost bits. The leftmost bits are filled with the previous content. This is to do with sign extension. In this case there is a 1 at the left and it is preserved. If you do not want to keep the 1 to the left, use >>> operator which shifts 0’s into the leftmost bits.

// WAP to demonstrate Bitwise Operators.
class Bitwise
{
    public static void main(String args[])
    {
        int a = 60; // 60 = 0011 1100
        int b = 13; // 13 = 0000 1101
        int c;
        c = ~a; // -61 = 1100 0011
        System.out.println("~a=" + c);
        c = a & b; // 12 = 0000 1100
        System.out.println("a&b=" + c);
        c = a | b; // 61 = 0011 1101
        System.out.println("a|b=" + c);
        c = a ^ b; // 49 = 0011 0001
        System.out.println("a^b=" + c);
        c = a << 2; // 240 = 1111 0000
        System.out.println("a<<2=" + c);
        c = a >> 2; // 15 = 1111
        System.out.println("a>>2=" + c);
        c = a >>> 2; // 15 = 0000 1111
        System.out.println("a>>>2=" + c);
    }
}
// Output: C:\> javac Bitwise.java
// C:\> java Bitwise
// ~a = -61
// a&b=12
// a|b=61
// a^b=49
// a<<2=240
// a>>2=15
// a>>>2=15
  1. Special Operators:
  • Instanceof of Operator: It is an object reference operator and return true if the object on the left hand side is an instance of the class given on the right hand side. This operator allows us to determine whether the object belongs to a particular class or not.
  • Ex: person instanceof student; It is true if person object belongs to the student class; otherwise it’s false.
// WAP to demonstrate Instanceof Operator.
class Instance
{
    public static void main(String args[])
    {
        String s1 = “Hello”;
        String s2 = null;
        System.out.println(“Res1 = “ + (s1 instanceof java.lang.String) );
        System.out.println(“Res2 = “ + (s2 instanceof java.lang.String) );
    }
}
// Output: C:\> javac Instance.java
// C:\> java Instance
// Res1=true
// Res2=false
  • Dot Operator (.): It is used to access the instance variables and methods of class objects.
  • Ex: person.age // Reference to the variable age person.salary ( ) // Reference to the method salary () It is also used to access classes and sub-packages from a package.

Decision making and looping

  • When some statements need to be repeated we can use looping control structure.
  • Types of loops:
  1. Entry Control Loops
  2. Exit Control Loops
  • Entry Controlled Loops: In this type of loops condition is tested before getting entry inside the loop body. Body of the loop keeps on executing till the condition is true. Once the condition becomes false loop get stop. In this type of loop if the condition becomes false at very first time body of the loop does not executed once also. Example: while and for loop.

  • Exit Controlled Loops: In this type of loops condition is tested after body of the loop. Body of the loop keeps on executing till the condition is true. Once the condition becomes false loop get stop. In this type of loop body of the loop executes at least once even if the condition is false at very first time. Example: do---while loop.

  • While Loop: Description: It is entry controlled loop. The loop gets iterate till the given condition is true. Once the condition becomes false loop gets stop. In it if the condition becomes false at very first time body of the loop does not executed once also.

  • Do While Loop: Description: It is exit controlled loop. In it condition is tested while exiting from the loop. Loop keeps executing till the condition is true. Once the condition becomes false loop stops. In it body of the loop executes at least once even if the condition becomes false at very first time.

  • For Loop: Description: It is entry controlled loop. It is compact version of while loop. In for loop initialization, test condition and increment / decrement are written on same line. Execution of for loop is as follows: i. Initialization of loop control variable. ii. Test condition. iii. Body of the loop. iv. Increment or decrement of loop control variable. Here, steps ii to iv keeps on repeating till the condition is true. Once the condition becomes false loop get stop.

  • Nested Loops: Description: When one for loop is put inside another loop it is called as nested loops. In nesting inner loop executes entirely for one iteration of outer loop, so inner loop executes more number of times as compared to outer loop. Nesting of while, do-while and for loop is possible.

  • Enhanced For Loop / For Each Loop: Enhanced for loop / for each loop is an extended language feature introduced with Java J2SE 5.0 release. This feature is useful to retrieve the array elements efficiently rather than using array indexes. We can also use this feature to eliminate the iterators in for loop and to retrieve the elements from collection. So, it is use to track the elements of an array efficiently.

// Program For Enhanced For Loop / For Each Loop
class ForDemoEnh
{
    public static void main(String args[])
    {
        int ary[]={30,10,60,70,40};
        for(int i : ary) /* for(int i=0;i<=4;i++) */
        {
            if(i<50) /* if(ary[i]<50) */
            {
                System.out.println(i); /* S.o.p(ary[i]) */
            }
        }
    }
}
// Output: 30
// 10
// 40
  • Jumps In Loops: Sometimes, when executing a loop we may need to exit the loop or to skip a part of the loop as soon as certain condition occurs. For example, if we want to search a given name from the list of 100 names. A program loop should be written to repeat 100 times, but as soon as desired name is found we should terminate the loop. To support above things, Java permits a jump from one statement to the end or beginning of a loop as well as a jump out of a loop using break and continue statement. Java also support labeled break and continue statement to jump from nested loops.

  • Break Statement:

  • Simple break: The simple break statement is used to early exit from loop, switch or any other block. It can jump outside of the loop in which it is written. It cannot jump outside of more than one loop at a time. Behavior of simple break is shown in figure. It is generally associated with if statement.

  • Labeled break: The labeled break statement is used to jump outside of the nested loops. It can jump outside of more than one nested loop at a time. Behavior of labeled break is shown below. It is generally associated with if statement.

  • Continue Statement:

  • Simple continue: The simple continue statement is used to transfer the control to the beginning of the loop. Whenever continue statement is encountered remaining part of the loop will be skipped and control immediately transfer to the beginning of the loop. It can skip / continue only one loop in which it is written. Behavior of continue is shown in fig. It is generally associated with if statement.

  • Labeled continue: The labeled continue statement is used to transfer the control to the beginning of the nested loops. It can skip / continue any specified nested loop. Behavior of labeled continue is shown below. It is generally associated with if statement.