1. PROGRAMMING IN JAVA
A. SIVASANKARI
ASSISTANT PROFESSOR
DEPARTMENT OF COMPUTER SCIENCE
SHANMUGA INDUSTRIES ARTS AND SCIENCE COLLEGE,
TIRUVANNAMALAI. 606601.
Email: sivasankaridkm@gmail.com
2. PROGRAMMING IN JAVA
UNIT - 1 B
ď§ BASIC OPERATORS
ď§ CONTROL
STATEMENTS
ď§ CONSTRUCTORS
ď§ JAVA PACKAGE
ď§ METHOD
OVERLOADING
A. SIVASANKARI - SIASC-TVM
3. BASIC OPERATORS
⢠Java provides a rich set of operators to manipulate variables. We can divide all the
Java operators into the following groups .
1. Arithmetic Operators
2. Relational Operators
3. Bitwise Operators
4. Logical Operators
5. Assignment Operators
6. Misc Operators
THE ARITHMETIC OPERATORS
⢠Arithmetic operators are used in mathematical expressions in the same way that
they are used in algebra. The following table lists the arithmetic operators
⢠Assume integer variable A holds 10 and variable B holds 20, then -
PROGRAMMING IN JAVA
A. SIVASANKARI - SIASC-TVM
4. Operator Description Example
+ (Addition)
Adds values on either side of the operator.
A + B will give 30
- (Subtraction)
Subtracts right-hand operand from left-hand
operand.
A - B will give -10
* (Multiplication)
Multiplies values on either side of the operator.
A * B will give 200
/ (Division)
Divides left-hand operand by right-hand operand.
B / A will give 2
% (Modulus)
Divides left-hand operand by right-hand operand
and returns remainder. B % A will give 0
++ (Increment)
Increases the value of operand by 1.
B++ gives 21
-- (Decrement)
Decreases the value of operand by 1.
B-- gives 19
PROGRAMMING IN JAVA
A. SIVASANKARI - SIASC-TVM
5. THE RELATIONAL OPERATORS
Operator Description Example
== (equal to)
Checks if the values of two operands are equal or not, if yes
then condition becomes true.
(A == B) is not
true.
!= (not equal to)
Checks if the values of two operands are equal or not, if
values are not equal then condition becomes true. (A != B) is true.
> (greater than)
Checks if the value of left operand is greater than the value
of right operand, if yes then condition becomes true.
(A > B) is not
true.
< (less than)
Checks if the value of left operand is less than the value of
right operand, if yes then condition becomes true. (A < B) is true.
>= (greater than or equal
to)
Checks if the value of left operand is greater than or equal to
the value of right operand, if yes then condition becomes
true.
(A >= B) is not
true.
<= (less than or equal to)
Checks if the value of left operand is less than or equal to the
value of right operand, if yes then condition becomes true.
(A <= B) is true.
PROGRAMMING IN JAVA
A. SIVASANKARI - SIASC-TVM
6. ⢠THE BITWISE OPERATORS
⢠Java defines several bitwise operators, which can be applied to the integer types, long, int,
short, char, and byte.
⢠Bitwise operator works on bits and performs bit-by-bit operation. Assume if a = 60 and b =
13; now in binary format they will be as follows â
⢠a = 0011 1100
⢠b = 0000 1101
⢠-----------------
⢠a&b = 0000 1100
⢠a|b = 0011 1101
⢠a^b = 0011 0001
⢠~a = 1100 0011
PROGRAMMING IN JAVA
A. SIVASANKARI - SIASC-TVM
7. Operator Description Example
& (bitwise and)
Binary AND Operator copies a bit to the result if it
exists in both operands.
(A & B) will give 12 which is
0000 1100
| (bitwise or)
Binary OR Operator copies a bit if it exists in either
operand.
(A | B) will give 61 which is
0011 1101
^ (bitwise XOR)
Binary XOR Operator copies the bit if it is set in one
operand but not both.
(A ^ B) will give 49 which is
0011 0001
~ (bitwise compliment)
Binary Ones Complement Operator is unary and has
the effect of 'flipping' bits.
(~A ) will give -61 which is
1100 0011 in 2's complement
form due to a signed binary
number.
<< (left shift)
Binary Left Shift Operator. The left operands value is
moved left by the number of bits specified by the right
operand.
A << 2 will give 240 which is
1111 0000
>> (right shift)
Binary Right Shift Operator. The left operands value
is moved right by the number of bits specified by the
right operand.
A >> 2 will give 15 which is
1111
>>> (zero fill right shift)
Shift right zero fill operator. The left operands value is
moved right by the number of bits specified by the
right operand and shifted values are filled up with
zeros.
A >>>2 will give 15 which is
0000 1111
PROGRAMMING IN JAVA
A. SIVASANKARI - SIASC-TVM
The following table lists the bitwise operators â
Assume integer variable A holds 60 and variable B holds 13
8. THE LOGICAL OPERATORS
⢠The following table lists the logical operators
⢠Assume Boolean variables A holds true and variable B holds false, then
Operator Description Example
&& (logical and)
Called Logical AND operator. If both the operands are
non-zero, then the condition becomes true.
(A && B) is false
|| (logical or)
Called Logical OR Operator. If any of the two operands are
non-zero, then the condition becomes true.
(A || B) is true
! (logical not)
Called Logical NOT Operator. Use to reverses the logical
state of its operand. If a condition is true then Logical NOT
operator will make false.
!(A && B) is true
PROGRAMMING IN JAVA
A. SIVASANKARI - SIASC-TVM
9. THE ASSIGNMENT OPERATORS
Operator Description Example
=
Simple assignment operator. Assigns values from right side operands to left
side operand.
C = A + B will assign value of A + B
into C
+=
Add AND assignment operator. It adds right operand to the left operand and
assign the result to left operand.
C += A is equivalent to C = C + A
-=
Subtract AND assignment operator. It subtracts right operand from the left
operand and assign the result to left operand.
C -= A is equivalent to C = C â A
*=
Multiply AND assignment operator. It multiplies right operand with the left
operand and assign the result to left operand.
C *= A is equivalent to C = C * A
/= Divide AND assignment operator. It divides left operand with the right
operand and assign the result to left operand.
C /= A is equivalent to C = C / A
%=
Modulus AND assignment operator. It takes modulus using two operands
and assign the result to left operand.
C %= A is equivalent to C = C % A
<<= Left shift AND assignment operator. C <<= 2 is same as C = C << 2
>>= Right shift AND assignment operator. C >>= 2 is same as C = C >> 2
&= Bitwise AND assignment operator. C &= 2 is same as C = C & 2
^= bitwise exclusive OR and assignment operator. C ^= 2 is same as C = C ^ 2
|= bitwise inclusive OR and assignment operator. C |= 2 is same as C = C | 2
PROGRAMMING IN JAVA
A. SIVASANKARI - SIASC-TVM
10. MISCELLANEOUS OPERATORS
CONDITIONAL OPERATOR ( ? : )
⢠Conditional operator is also known as the ternary operator. This operator consists of three
operands and is used to evaluate Boolean expressions. The goal of the operator is to decide,
which value should be assigned to the variable. The operator is written as â
variable x = (expression) ? value if true : value if false
⢠public class Test {
⢠public static void main(String args[]) {
⢠int a, b;
⢠a = 10;
⢠b = (a == 1) ? 20: 30;
⢠System.out.println( "Value of b is : " + b );
⢠b = (a == 10) ? 20: 30;
⢠System.out.println( "Value of b is : " + b );
⢠}
⢠}
OUTPUT
⢠Value of b is : 30
⢠Value of b is : 20
PROGRAMMING IN JAVA
A. SIVASANKARI - SIASC-TVM
11. Category Operator Associativity
Postfix expression++ expression-- Left to right
Unary ++expression â-expression +expression âexpression ~ ! Right to left
Multiplicative * / % Left to right
Additive + - Left to right
Shift << >> >>> Left to right
Relational < > <= >= instanceof Left to right
Equality == != Left to right
Bitwise AND & Left to right
Bitwise XOR ^ Left to right
Bitwise OR | Left to right
Logical AND && Left to right
Logical OR || Left to right
Conditional ?: Right to left
Assignment = += -= *= /= %= ^= |= <<= >>= >>>= Right to left
PRECEDENCE OF JAVA OPERATORS
PROGRAMMING IN JAVA
A. SIVASANKARI - SIASC-TVM
12. SCOPE RESOLUTION OPERATOR / DOUBLE COLON (::) OPERATOR IN JAVA
The double colon (::) operator, also known as method reference operator in Java, is used to call
a method by referring to it with the help of its class directly. They behave exactly as the lambda expressions. The
only difference it has from lambda expressions is that this uses direct reference to the method by name instead of
providing a delegate to the method.
Syntax:
⢠<Class name>::<method name>
⢠Example: To print all elements of the stream:
⢠Using Lambda expression:stream.forEach( s-> System.out.println(s));
COMMENTS
⢠The Java comments are the statements that are not executed by the compiler and interpreter. The comments
can be used to provide information or explanation about the variable, method, class or any statement. It can
also be used to hide program code.
Types of Java Comments
There are three types of comments in Java.
1. Single Line Comment
2. Multi Line Comment
3. Documentation Comment
SAMPLE
⢠//This is single line comment
⢠/* This is multi line comment */
⢠/** This is documentation comment */
PROGRAMMING IN JAVA
A. SIVASANKARI - SIASC-TVM
13. KEYBOARD INPUT
⢠import java.util.Scanner; - imports the class Scanner from the library java.util.
⢠Scanner scanner = new Scanner(System.in); - creates a new Scanner object, that is connected
to standard input (the keyboard)
⢠String inputString = scanner. nextLine();
READING DATA FROM KEYBOARD
⢠There are many ways to read data from the keyboard. For example:
1. InputStreamReader
2. Console
3. Scanner
4. DataInputStream etc.
InputStreamReader class
⢠InputStreamReader class can be used to read data from keyboard.I t performs two tasks:
⢠connects to input stream of keyboard
⢠converts the byte-oriented stream into character-oriented stream
⢠BufferedReader class
⢠BufferedReader class can be used to read data line by line by readLine() method
PROGRAMMING IN JAVA
A. SIVASANKARI - SIASC-TVM
15. JAVA - DECISION MAKING
PROGRAMMING IN JAVA
A. SIVASANKARI - SIASC-TVM
16. LOOP CONTROL OR ITERATION STATEMENT
⢠A loop statement allows us to execute a statement or group of statements multiple times and following is
the general form of a loop statement in most of the programming languages
Sr.No. Loop & Description
1 while loop
Repeats a statement or group of statements while a given condition is true. It
tests the condition before executing the loop body.
2 for loop
Execute a sequence of statements multiple times and abbreviates the code that
manages the loop variable.
3 do...while loop
Like a while statement, except that it tests the condition at the end of the loop
body.
PROGRAMMING IN JAVA
A. SIVASANKARI - SIASC-TVM
18. JUMP STATEMENTS OR LOOP CONTROL STATEMENTS
⢠Loop control statements change execution from its normal sequence. When execution leaves a
scope, all automatic objects that were created in that scope are destroyed.
Sr.No. Control Statement & Description
1 break statement
Terminates the loop or switch statement and transfers execution to the statement immediately
following the loop or switch.
2 continue statement
Causes the loop to skip the remainder of its body and immediately retest its condition prior to
reiterating.
PROGRAMMING IN JAVA
A. SIVASANKARI - SIASC-TVM
20. CONSTRUCTORS
⢠A constructor initializes an object when it is created. It has the same name as its class and is
syntactically similar to a method. However, constructors have no explicit return type.
⢠Typically, you will use a constructor to give initial values to the instance variables defined by
the class, or to perform any other start-up procedures required to create a fully formed object.
⢠All classes have constructors, whether you define one or not, because Java automatically
provides a default constructor that initializes all member variables to zero. However, once you
define your own con.
⢠class ClassName {
⢠ClassName() {
⢠}
⢠}
Java allows two types of constructors namely
1. No argument Constructors
2. Parameterized Constructors
No argument Constructors
⢠As the name specifies the no argument constructors of Java does not accept any parameters
instead, using these constructors the instance variables of a method will be initialized with
fixed values for all objects
PROGRAMMING IN JAVA
A. SIVASANKARI - SIASC-TVM
21. SAMPLE PROGRAM
⢠Public class MyClass {
⢠Int num;
⢠MyClass() {
⢠num = 100;
⢠}
⢠}
⢠public class ConsDemo {
⢠public static void main(String args[]) {
⢠MyClass t1 = new MyClass();
⢠MyClass t2 = new MyClass();
⢠System.out.println(t1.num + " " + t2.num);
⢠}
⢠}
⢠OUTPUT
⢠This would produce the following result
⢠100 100
PROGRAMMING IN JAVA
A. SIVASANKARI - SIASC-TVM
22. PARAMETERIZED CONSTRUCTORS
Most often, you will need a constructor that accepts one or more parameters.
Parameters are added to a constructor in the same way that they are added to a method, just
declare them inside the parentheses after the constructor's name.
⢠Here is a simple example that uses a constructor
⢠// A simple constructor.
⢠class MyClass {
⢠int x;
⢠// Following is the constructor
⢠MyClass(int i ) {
⢠x = i;
⢠}}
⢠public class ConsDemo {
⢠public static void main(String args[]) {
⢠MyClass t1 = new MyClass( 10 );
⢠MyClass t2 = new MyClass( 20 );
⢠System.out.println(t1.x + " " + t2.x);
⢠}
⢠}
OUTPUT
⢠10 20
PROGRAMMING IN JAVA
A. SIVASANKARI - SIASC-TVM
23. JAVA PACKAGE
⢠In simple words, it is a way of categorizing the classes and interfaces. When developing
applications in Java, hundreds of classes and interfaces will be written, therefore categorizing
these classes is a must as well as makes life much easier.
⢠Import Statements
⢠In Java if a fully qualified name, which includes the package and the class name is given, then
the compiler can easily locate the source code or classes. Import statement is a way of giving
the proper location for the compiler to find that particular class.
⢠For example, the following line would ask the compiler to load all the classes available in
directory java_installation/java/io â
⢠import java.io.*; A Simple Case Study
⢠For our case study, we will be creating two classes. They are Employee and EmployeeTest.
⢠First open notepad and add the following code. Remember this is the Employee class and the
class is a public class. Now, save this source file with the name Employee.java.
⢠The Employee class has four instance variables - name, age, designation and salary. The class
has one explicitly defined constructor, which takes a parameter.
PROGRAMMING IN JAVA
A. SIVASANKARI - SIASC-TVM
24. PACKAGES
⢠As a package normally contains several classes and interfaces, java allows us to conveniently
split appear up a Package and keep its classes and interfaces separately in different source
files.
⢠Create all class are stored is called package.
SINGLE PACKAGE
⢠SYNTAX:
⢠Package packagename;
⢠Example:
⢠Package mypackage;
MULTI VALUED PACKAGE
⢠SYNTAX:
⢠Package pkg1[.pkg2][pkg3];
⢠Example:
⢠Package java.awt.image;
PACKAGE HIERARCHY
⢠Package java.events.mouse events; //Directories-Include all files
PROGRAMMING IN JAVA
A. SIVASANKARI - SIASC-TVM
25. SAMPLE PROGRAM
⢠import java.io.*;
⢠public class Employee
⢠{ String name; int age;
⢠String designation;
⢠double salary; // This is the constructor of the class Employee
⢠public Employee(String name) {
⢠this.name = name;
⢠} // Assign the age of the Employee to the variable age.
⢠public void empAge(int empAge)
⢠{ age = empAge;
⢠} /* Assign the designation to the variable designation.*/
⢠public void empDesignation(String empDesig)
⢠{ designation = empDesig;
⢠} /* Assign the salary to the variable salary.*/
⢠public void empSalary(double empSalary) {
⢠salary = empSalary;
PROGRAMMING IN JAVA
A. SIVASANKARI - SIASC-TVM
26. ⢠} /* Print the Employee details */
⢠public void printEmployee()
⢠{
⢠System.out.println("Name:"+ name );
⢠System.out.println("Age:" + age );
⢠System.out.println("Designation:" + designation );
⢠System.out.println("Salary:" + salary);
⢠}}
⢠Following is the EmployeeTest class, which creates two instances of the class Employee and invokes the
methods for each object to assign values for each variable
⢠Save the following code in EmployeeTest.java file.
⢠import java.io.*;
⢠public class EmployeeTest {
⢠public static void main(String args[])
⢠{ /* Create two objects using constructor */
⢠Employee empOne = new Employee(âSAISIVA");
⢠Employee empTwo = new Employee(âSAIDINESH");
⢠// Invoking methods for each object created
⢠empOne.empAge(26);
PROGRAMMING IN JAVA
A. SIVASANKARI - SIASC-TVM
27. ⢠empOne.empDesignation("Senior Software Engineer");
⢠empOne.empSalary(1000);
⢠empOne.printEmployee();
⢠empTwo.empAge(21);
⢠empTwo.empDesignation("Software Engineer");
⢠empTwo.empSalary(5000);
⢠empTwo.printEmployee();
⢠}}
⢠Now, compile both the classes and then run EmployeeTest to see the result as follows
OUTPUT
⢠C:> javac Employee.java
⢠C:> javac EmployeeTest.java
⢠C:> java EmployeeTest
⢠Name:SAISIVA
⢠Age:26
⢠Designation:Senior Software Engineer
⢠Salary:1000.0
⢠Name:SAIDINESH
⢠Age:21
⢠Designation:Software Engineer
⢠Salary:5000.0
PROGRAMMING IN JAVA
A. SIVASANKARI - SIASC-TVM
28. METHOD OVERLOADING
⢠If a class has multiple methods having same name but different in parameters, it is
known as Method Overloading.
⢠If we have to perform only one operation, having same name of the methods
increases the readability of the program.
⢠Suppose you have to perform addition of the given numbers but there can be any
number of arguments, if you write the method such as a(int,int) for two parameters,
and b(int,int,int) for three parameters then it may be difficult for you as well as
other programmers to understand the behaviour of the method because its name
differs.
Advantage of method overloading
⢠Method overloading increases the readability of the program.
There are two ways to overload the method in java
1. By changing number of arguments
2. By changing the data type
PROGRAMMING IN JAVA
A. SIVASANKARI - SIASC-TVM
29. 1) Method Overloading: changing no. of arguments
⢠In this example, we have created two methods, first add() method performs addition of two
numbers and second add method performs addition of three numbers.
⢠In this example, we are creating static methods so that we don't need to create instance for
calling methods
class Adder{
static int add(int a,int b){return a+b;}
static int add(int a,int b,int c){return a+b+c;}
}
class TestOverloading1{
public static void main(String[] args){
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(11,11,11));
}
}
OUTPUT
⢠22
⢠33
PROGRAMMING IN JAVA
A. SIVASANKARI - SIASC-TVM
30. 2) Method Overloading: changing data type of arguments
⢠In this example, we have created two methods that differs in data type. The first add method
receives two integer arguments and second add method receives two double arguments.
class Adder{
static int add(int a, int b){return a+b;}
static double add(double a, double b){return a+b;}
}
class TestOverloading2{
public static void main(String[] args){
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(12.3,12.6));
}
}
OUTPUT
⢠22
PROGRAMMING IN JAVA
A. SIVASANKARI - SIASC-TVM
31. PASSING AND RETURNING OBJECTS IN JAVA
⢠Although Java is strictly pass by value, the precise effect differs between whether a primitive
type or a reference type is passed.
⢠When we pass a primitive type to a method, it is passed by value. But when we pass an object
to a method, the situation changes dramatically, because objects are passed by what is
effectively call-by-reference. Java does this interesting thing thatâs sort of a hybrid between
pass-by-value and pass-by-reference. Basically, a parameter cannot be changed by the
function, but the function can ask the parameter to change itself via calling some method
within it.
⢠While creating a variable of a class type, we only create a reference to an object. Thus, when
we pass this reference to a method, the parameter that receives it will refer to the same object
as that referred to by the argument.
⢠This effectively means that objects act as if they are passed to methods by use of call-by-
reference.
⢠Changes to the object inside the method do reflect in the object used as an argument.
⢠In Java we can pass objects to methods.
⢠For example, consider the following program
PROGRAMMING IN JAVA
A. SIVASANKARI - SIASC-TVM
32. ⢠// Java program to demonstrate objects
⢠// passing to methods.
⢠class ObjectPassDemo
⢠{
⢠int a, b;
⢠ObjectPassDemo(int i, int j)
⢠{
⢠a = i;
⢠b = j;
⢠}
⢠// return true if o is equal to the invoking
⢠// object notice an object is passed as an
⢠// argument to method
⢠boolean equalTo(ObjectPassDemo o)
⢠{
⢠return (o.a == a && o.b == b);
⢠} } // Java program to demonstrate objects
⢠// passing to methods.
⢠class ObjectPassDemo
⢠{ int a, b;
PROGRAMMING IN JAVA
A. SIVASANKARI - SIASC-TVM
33. ⢠ObjectPassDemo(int i, int j)
⢠{
⢠a = i;
⢠b = j; }
⢠// return true if o is equal to the invoking // object notice an object is passed as an
⢠// argument to method
⢠boolean equalTo(ObjectPassDemo o)
⢠{ return (o.a == a && o.b == b); } } / Driver class
⢠public class Test
⢠{ public static void main(String args[])
⢠{
⢠ObjectPassDemo ob1 = new ObjectPassDemo(100, 22);
⢠ObjectPassDemo ob2 = new ObjectPassDemo(100, 22);
⢠ObjectPassDemo ob3 = new ObjectPassDemo(-1, -1);
⢠System.out.println("ob1 == ob2: " + ob1.equalTo(ob2));
⢠System.out.println("ob1 == ob3: " + ob1.equalTo(ob3));
⢠} }
OUTPUT
⢠ob1 == ob2: true ob1 == ob3: false
PROGRAMMING IN JAVA
A. SIVASANKARI - SIASC-TVM
34. Java toString() method
⢠If you want to represent any object as a string, toString() method comes into existence.
⢠The toString() method returns the string representation of the object.
⢠If you print any object, java compiler internally invokes the toString() method on the object.
So overriding the toString() method, returns the desired output, it can be the state of an object
etc. depends on your implementation.
⢠Advantage of Java toString() method
⢠By overriding the toString() method of the Object class, we can return values of the object, so
we don't need to write much code.
EXAMPLE
⢠public class Test {
⢠public static void main(String args[]) {
⢠Integer x = 5;
⢠System.out.println(x.toString());
⢠System.out.println(Integer.toString(12));
⢠}
⢠}
OUTPUT
⢠5
⢠12
PROGRAMMING IN JAVA
A. SIVASANKARI - SIASC-TVM
35. this keyword in java
⢠There can be a lot of usage of java this keyword. In java, this is a reference variable that
refers to the current object.
⢠Usage of java this keyword
⢠Here is given the 6 usage of java this keyword.
⢠this can be used to refer current class instance variable.
⢠this can be used to invoke current class method (implicitly)
⢠this() can be used to invoke current class constructor.
⢠this can be passed as an argument in the method call.
⢠this can be passed as argument in the constructor call.
⢠this can be used to return the current class instance from the method.
PROGRAMMING IN JAVA
A. SIVASANKARI - SIASC-TVM
36. ENUMERATION
⢠The Enumeration interface defines the methods by which you can enumerate (obtain one at a
time) the elements in a collection of objects.
⢠This legacy interface has been super ceded by Iterator. Although not deprecated, Enumeration
is considered obsolete for new code. However, it is used by several methods defined by the
legacy classes such as Vector and Properties, is used by several other API classes, and is
currently in widespread use in application code.
Method & Description
1. boolean hasMoreElements( )
⢠When implemented, it must return true while there are still more elements to extract, and false
when all the elements have been enumerated.
2. Object nextElement( )
This returns the next object in the enumeration as a generic Object reference.
⢠import java.util.Vector;
⢠import java.util.Enumeration;
⢠public class EnumerationTester {
⢠public static void main(String args[]) {
⢠Enumeration days;
⢠Vector dayNames = new Vector();
PROGRAMMING IN JAVA
A. SIVASANKARI - SIASC-TVM
38. JAVA GARBAGE COLLECTION
⢠Java garbage collection is the process by which Java programs perform automatic memory
management. Java programs compile to bytecode that can be run on a Java Virtual Machine,
or JVM for short.
⢠When Java programs run on the JVM, objects are created on the heap, which is a portion of
memory dedicated to the program. Eventually, some objects will no longer be needed.
⢠The garbage collector finds these unused objects and deletes them to free up memory.
Advantage of Garbage Collection
⢠It makes java memory efficient because garbage collector removes the unreferenced objects
from heap memory.
⢠It is automatically done by the garbage collector(a part of JVM) so we don't need to make
extra efforts.
PROGRAMMING IN JAVA
A. SIVASANKARI - SIASC-TVM