Java-unit_1
Java-unit_1
Methods: Introduction, Defining Methods, Overloaded Methods, Overloaded Constructor Methods, Class
Objects as Parameters in Methods, Access Control, Recursive Methods, Nesting of Methods, Overriding
Methods, Attributes Final and Static.
UNIT III:
Arrays:Introduction, Declaration and Initialization of Arrays, Storage of Array in Computer Memory, Accessing
Elements of Arrays, Operations on Array Elements, Assigning Array to Another Array, Dynamic Change of
Array Size, Sorting of Arrays, Search for Values in Arrays, Class Arrays, Two-dimensional Arrays, Arrays of
Varying Lengths, Three-dimensional Arrays, Arrays as Vectors.
Inheritance :Introduction, Process of Inheritance, Types of Inheritances, Universal Super Class- Object Class,
Inhibiting Inheritance of Class Using Final, Access Control and Inheritance, Multilevel Inheritance, Application
of Keyword Super, Constructor Method and Inheritance, Method Overriding, Dynamic Method Dispatch,
Abstract Classes, Interfaces and Inheritance.
1|Page
UNIT IV:
Packages and Java Library: Introduction, Defining Package, Importing Packages and Classes into Programs,
Path and Class Path, Access Control, Packages in Java SE, Java.lang Package and its Classes, Class Object,
Enumeration, class Math, Wrapper Classes, Auto-boxing and Auto- unboxing, Java util Classes and Interfaces,
Formatter Class, Random Class, Time Package, Class Instant (java.time.Instant), Formatting for Date/Time in
Java, Temporal Adjusters Class, Temporal Adjusters Class.
Exception Handling: Introduction, Hierarchy of Standard Exception Classes, Keywords throws and throw, try,
catch, and finally Blocks, Multiple Catch Clauses, Class Throwable, Unchecked Exceptions, Checked
Exceptions.
Java I/O and File: Java I/O API, standard I/O streams, types, Byte streams, Character streams, Scanner class,
Files in Java(Text Book 2)
UNIT V:
String Handling in Java:Introduction, Interface Char Sequence, Class String, Methods for Extracting
Characters from Strings,Comparison, Modifying, Searching; Class String Buffer.
Multithreaded Programming:Introduction, Need for Multiple Threads Multithreaded Programming for Multi-
core Processor, Thread Class, Main Thread-Creation of New Threads, Thread States, Thread Priority-
Synchronization, Deadlock and Race Situations, Inter-thread Communication - Suspending, Resuming, and
Stopping of Threads.
Java Database Connectivity: Introduction, JDBC Architecture, Installing MySQL and MySQL Connector/J,
JDBC Environment Setup, Establishing JDBC Database Connections, ResultSet Interface
Java FX GUI: Java FX Scene Builder, Java FX App Window Structure, displaying text and image, event
handling, laying out nodes in scene graph, mouse events (Text Book 3)
Text Books:
1. JAVA one step ahead, Anitha Seth, B.L.Juneja, Oxford.
2. Joy with JAVA, Fundamentals of Object Oriented Programming, DebasisSamanta, MonalisaSarma,
Cambridge, 2023.
3. JAVA 9 for Programmers, Paul Deitel, Harvey Deitel, 4th Edition, Pearson.
References Books:
1. The complete Reference Java, 11thedition, Herbert Schildt,TMH
2. Introduction to Java programming, 7th Edition, Y Daniel Liang, Pearson
Online Resources:
1. https://nptel.ac.in/courses/106/105/106105191/
2. https://infyspringboard.onwingspan.com/web/en/app/toc/lex_auth_012880464547618816347_shared/overview
2|Page
UNIT - I
UNIT I: Object Oriented Programming: Basic concepts, Principles, Program Structure in Java: Introduction,
Writing Simple Java Programs, Elements or Tokens in Java Programs, Java Statements, Command Line Arguments,
User Input to Programs, Escape Sequences Comments, Programming Style.
Data Types, Variables, and Operators :Introduction, Data Types in Java, Declaration of Variables, Data Types,
Type Casting, Scope of Variable Identifier, Literal Constants, Symbolic Constants, Formatted Output with printf()
Method, Static Variables and Methods, Attribute Final, Introduction to Operators, Precedence and Associativity of
Operators, Assignment Operator ( = ), Basic Arithmetic Operators, Increment (++) and Decrement (- -) Operators,
Ternary Operator, Relational Operators, Boolean Logical Operators, Bitwise Logical Operators.
Control Statements: Introduction, if Expression, Nested if Expressions, if–else Expressions, Ternary Operator?:,
Switch Statement, Iteration Statements, while Expression, do–while Loop, for Loop, Nested for Loop, For–Each
for Loop, Break Statement, Continue Statement.
Introduction:
Procedure Oriented Programming (POP):
➢ The problem is viewed in a procedure oriented programming as a sequence of things
to be done such as reading, calculating and printing.
➢ A number of functions are used to perform these operations.
➢ POP divides the program into small parts called functions.
➢ In a procedure oriented programming the primary focus is on function since
everything is represented inside the function only.
Object Oriented Programming (OOP):
➢ Oops was invented to overcome the drawbacks of Pops.
➢ OOP treats data as a critical element in the program development and does not
moved freely around the system.
➢ Object oriented programming divides a problem into a number of entities called
objects.
➢ Everything is represented in the form of object in OOPs.
➢ Objects protects of its data and functions from outside objects.
➢ The data of an object can be accessed only by the functions associated with the
object
Introduction to Java
Java History:
➢ Java is a general purpose object oriented programming language developed by Sun
Microsystems of USA in 1991.
➢ Originally java was called “OAK” by James Gosling, one of the inventors of java
language.
➢ Java was developed for consumer electronic devices like TV’s, VCR’s and such other
electronic machines.
➢ The main goal of java team is developing of simple, portable and highly reliable
language.
➢ Patrick Naughton, one of the java developers team member discovered that the existing
languages(C or C++) had some limitations
➢ However they modeled their new language java by removing some of the features of C
and C++
Java used in:
✓ Desktop applications
✓ Mobile applications
✓ Enterprise applications
✓ Web applications
✓ Games and Robotics
3|Page
Features of Java (Or) Java Buzzwords
The following are most important features of Java.
1. Compiled and Interpreted. 8. High Performance.
2. Platform–Independent and Portable. 9. Dynamic and Extensible.
3. Object Oriented 10. Ease of Development
4. Robust and Secure. 11. Scalability and Performance
5. Distributed. 12. Monitoring and manageability
6. Simple Small and Familiar. 13. Desktop Client.
7. Multithreaded and Interactive.
4|Page
Java Virtual Machine (JVM):
➢ All language compilers translate the “Source code” into “Machine code” for a specific
machine.
➢ But Java Compiler produces an intermediate code known as “Bye code” for a
specific machine called Java Virtual Machine (JVM).
➢ JVM is also called “Java interpreter”, and its functionality is converting “Byte code”
into “Machine code”.
➢ The Machine code is not machine independent. i.e., machine code is dependent.
➢ This Machine dependent code is generated by JVM.
➢ Java acts as an intermediate between “Byte code” and “Machine code”.
Functions of JVM:
➢ Collecting classes from API (Application Program Interface).
➢ Allocating memory to the objects.
➢ Calling methods.
➢ Calling I/O resources.
➢ Producing output.
➢ Submitting machine code to the processor.
➢ Removing memory allocated to the objects.
➢ Maintaining threads, executing constructors.
➢ Executing static methods.
Basic Concepts of OOP / Object Oriented Programming Principles
The following are the basic concepts of object oriented programming language.
1. Objects 2. Class 3. Data Abstraction 4. Encapsulation
1. Objects:
• Objects are the basic run time entities in an object oriented programming.
• Objects may represent a person, a place, a bank account or any item.
• Object takes memory space and has an address.
• Objects are the variables and classes are data types.
• Each object contains data and methods. By using methods, we can manipulate
data.
5|Page
Geethanjali Institute of Science and Technology: Nellore II B.Tech – CSE – I Sem
2. Classes:
Class Objects
Fruit Mango,banana,apple
Furniture Bench,chair,table
Bike Hero,Yamaha,Honda
vehicle Car,truck,bus
3. Data Abstraction:
• Removing of unnecessary information and representing necessary information is
called data abstraction. (or)
Hiding of unnecessary information and highlighting of necessary information is
called data abstraction.
• Classes use the concept of abstraction, and are defined with a list of data items
(variables) and methods (functions).
4. Encapsulation:
• Data encapsulation is most important feature of class.
• The process of combining data and methods (functions) in a single unit is known
as Encapsulation.
• The data of a class is accessed by only the methods of same class.
• By using encapsulation, we can accomplish data hiding.
Abstraction
6|Page
Geethanjali Institute of Science and Technology: Nellore II B.Tech – CSE – I Sem
5. Inheritance:
• The process of creating a new class from old class is called inheritance.
• Inheritance is very useful to add additional features to an existing class without
modifying it.
• The new class will have the combined features of new class and old class.
• New class is called derived class or sub class and old class is called super class
or base class.
6. Polymorphism:
• Polymorphism means the ability to take more than one form with a single name.
• “Polymorphism” comes from the ‘Greek’ word. “Poly” means “many” and
“morphism” means “forms”. i.e., many forms.
• It’s a quality that allows one name to be used in two more purposes.
• An action is depends on the type of the data.
• There are two types of polymorphisms.
1. Compile time polymorphism.
2. Run time polymorphism.
7. Dynamic binding:
• Dynamic binding means linking the code at the time of executing the program.
• It is associated with polymorphism and inheritance.
8. Message passing:
• A message for an object is nothing but request to execute a procedure.
• Message passing specifies name of the object, name of the method (message) and
the information to be sent.
7|Page
Every programming language follows certain program structure which is followed
by the programmer.
8|Page
Implementing of java program includes a series of steps. Thy are
1. Create a program
2. Compiling the program
3. Running the program
1. Create a program:
We can create a program using any text editor such as notepad, edit etc; assume
that we have entered the following program.
class Test
{
public static void main(String args[ ])
{
System.out.println(“Hello Java”);
}
}
The filename should be similar to the main method class name and extension is
.java. This file is called source file. So the file name is Test.java
2. Compiling the program:
Java compiler is used to compile the source of program. “javac” is the java compiler.
The following is used for compilation.
E:\> Javac Test.java
If everything is ok, the javac compiler creates a class file called “Test.class” containing
the byte codes. The compiler automatically names the bytecode as <classname>.class.
3. Running the program:
We need to use the java interpreter “java” to run a standalone program. At the
command prompt, type
E:\>java Test
Now the interpreter looks for the main( ) method in the program and begins execution
from there. It can be display the output as: Hello Java
Naming Conventions in Java
Naming conventions specify the rules to be followed in the java programmer while
writing the names of packages, classes, methods etc .
Packages can be named using the standard Java naming rules. Packages begin with
lowercase letters. This makes easy for users to
distinguish package names from class names. We
know that all class names begin with an uppercase
letter.
Example : This statement uses a fully qualified
class name Math to invoke the method sqrt( ). Note
that methods begin with lowercase letters. Every
package name must be unique. Duplicate names will
cause run-time errors.
9|Page
Naming Conventions of the Different Identifiers
The following table shows the popular conventions used for the different identifiers.
Identifiers Naming Rules Examples
Type
It should start with the uppercase letter. public class Employee
It should be a noun such as Color, Button, System, Thread, {
Class
etc. //code snippet
Use appropriate words, instead of acronyms. }
class Employee
{
It should start with lowercase letter.
// method
It should be a verb such as main(), print(), println().
void draw()
Method If the name contains multiple words, start it with a lowercase
{
letter followed by an uppercase letter such as
//code snippet
actionPerformed().
}
}
//package
package com.javatpoint;
It should be a lowercase letter such as java, lang.
class Employee
Package If the name contains multiple words, it should be separated
{
by dots (.) such as java.util, java.lang.
//code snippet
}
class Employee
It should be in uppercase letters such as RED, YELLOW. {
If the name contains multiple words, it should be separated //constant
Constant
by an underscore(_) such as MAX_PRIORITY. static final int MIN_AGE
It may contain digits but not as the first letter. = 18; //code snippet
}
10 | P a g e
The smallest individual element in the program is called token. Java supports 5
types of tokens. They are
1. Keywords (Pre-Defined Words)
2. Identifiers (User-defined Words)
3. Literals (Constants)
4. Operators
5. Separators
1. Keywords:
➢ System or language defined words are called Keywords.
➢ Keywords are also called Pre-defined words or reserved words.
➢ There are 50 keywords used in Java language.
➢ Keywords h..ave a specific meaning and purpose, that purpose will not be changed
by the programmer.
➢ The following are the list of keywords in Java language:
2. Identifiers:
• Programmer or user defined words are known as Identifiers.
• An identifier is a name, given to a program element such as variables, constants,
function names, array names and so on.
Rules for an identifier:
1. An identifier must contain combination of alphabets, digits and underscore only.
2. The first letter must be an alphabet.
3. The length of an identifier can be upto 31 characters.
4. Commas are not allowed
5. Spaces are not allowed
6. Special symbols other than underscore are not allowed
7. Keywords must not be used as identifiers.
8. An identifier must not be repeated in a program.
Examples:
Valid Identifiers: a salary sum stud_num c123 etc.
Invalid Identifiers: a+b 2abc float etc.
11 | P a g e
3. Literals (Or) Constants:
Literals are constants. They cannot be change their values during the execution of the
program. The following are various types of Literals.
LITERALS
12 | P a g e
5. Separators:
Separators are the symbols used to indicate where groups of score are divided and
arrange.
1) Parenthesis →()
2) Braces →{}
3) Brackets →[]
4) Comma →,
5) Period →.
6) Semi colon →;
Declaration of Variables:
A variable must be declared before it is used in the program. While declaration, the
compiler reserves memory space and creates an address (unsigned integer) to each
variable.
Syntax: datatype var1, var2, ;
Eg: int a, b, sum ;
float avg, f ;
char ch;
Initialisation of Variables: Assigning a value to a variable at the time of declaration is
called Initialisation. If the value is not assigned to a variable by default a garbage
(unknown) value is assigned.
13 | P a g e
• The area of the program where the variable is accessible and where the variable is
not accessible is called its scope
• Scope determines life time of the variable.
• Lifetime is nothing but when the variable is created and when the variable is
destroyed.
• A block defines the scope of a variable. A block is a piece of code placed between
opening closing curly braces { }.
• Java allows defining a variable inside the block. The variable inside the block is not
accessible in outside the block.
• Java variables are classified into three kinds.
1. Instance variables.
2. Class variables (static)
3. Local variables.
1. Instance variables :
• Instance variables are declared inside a class
• These are created when the objects are instantiated.
• These variables are access through object
2. Class Variables or Static Variables :
• These variables are declared inside the class but outside the methods and blocks
but by using ‘static’ keyword.
• Declare inside Class and outside Method.
• Class variables are global to all objects of a class.
• Allocates only one copy of memory and shared by all objects.
3. Local variables :
• Variables declared and used inside methods are called local variables.
• They are not available for use outside the method definition.
• Local variables can also be declared inside program blocks that are defined between
an opening brace { and a closing brace }.
Block 1
int m = 10;
}
In the above figure the variable x declared in block 1 and is available in all the three
blocks. The variable n declared in block 2 and is available only in block 2. Similarly m is
accessible in block3
14 | P a g e
/* Example program for scope of variables*/
class ScopeEx
{
public static void main(String args[])
{
int i=10; Output::
//block1 i=10
{ j=20
int j=20; i=10
System.out.println("i="+i); j=30
System.out.println("j="+j);
}
//block2
{
int k=30;
System.out.println("i="+i);
System.out.println("k="+j);
}
System.out.println("i="+i);
//System.out.println("j="+j); Error
//System.out.println("k="+k); Error
}
}
Ex.2:- /*Types of Varibles*/
import java.util.*;
import java.lang.*;
class
{
static int c=30; /*static variables*/
int a=10; /*Instance variables*/
public static void main(String args[]) /*Main Method*/
{
int b=20; /*local variables*/
System.out.println(c);
System.out.println(b);
Varible obj=new Varible(); /*Object Creation*/
System.out.println(obj.a);
}
}
Escape / Backslash Character constants :
Java supports some special backslash character constants that are used in output
methods.
Constant Meaning
‘\b’ Back Space
‘\f’ Form Feed
‘\n’ New Line
‘\r’ Carriage return
‘\t’ Horizontal tab
‘\’’ Single quotes
‘\”’ Double quotes
‘\\’ Back Slash
Ex:- public class Test
{
public static void main(String[] args)
{
System.out.println("Hello Dear" +"\n welcome to"+ "\t My World ");
}
}
15 | P a g e
DATA TYPES
Every variable in Java has a data type. The data type specifies the size and type of
data is stored and manipulated in the variable. The Java supports the following data types.
Integer:
Integer types can hold whole numbers such as 78,45 etc. The size of the value is
depends on the type of the integer data type. Java supports 4 types of integer data types.
They are
Example:
class Test
{
public static void main(String[] args) Output:
{ Int value 100
int i = 100;
Long value 100
long l = i; //automatic type conversion
float f = l; //automatic type conversion Float value 100.0
System.out.println("Int value "+i);
System.out.println("Long value "+l);
System.out.println("Float value "+f);
}
}
2. Explicit conversion:
• The type conversion performed by the programmer by specifying data type in the
expression is called explicit conversion.
• In the explicit conversion converting higher type into lower type is called
Narrowing.
• Widening may causes loss of data.
Syntax: (type-name) expression
Example
class Test
{ Output:
public static void main(String[] args) Double value 100.04
{ Long value 100
double d = 100.04; Int value 100
long l = (long)d; //explicit type casting
int i = (int)l; //explicit type casting
System.out.println("Double value "+d);
System.out.println("Long value "+l); //fractional part lost
System.out.println("Int value "+i); //fractional part lost
}
}
17 | P a g e
OPERATORS
Operators: - An operator is a symbol that performs an operation. If an operator acts
on a single variable, then it is called ‘Unary Operator’. If an operator acts on two variables
then it is called ‘Binary Operator’. If an operator acts on three variables then it is called
‘Ternary Operator’. The following are the Operators available in Java.
1) Arithmetic Operators.
2) Relational Operators.
3) Logical Operators.
4) Assignment Operators.
5) Increment and decrement Operators.
6) Conditional Operators.
7) Bitwise Operators.
8) Special Operators.
1. Arithmetic operators:
The Arithmetic operators are used to perform arithmetic calculations such as
addition, subtraction etc. The following are the various arithmetic operators.
Operator Meaning Example Result
+ Addition 10+3 13
– Subtraction 10–3 7
* Multiplication 10*3 30
/ Division 10/3 3
10/3.0 3.3333
% Modulo division (Remainder) 10%3 1
2. Relational Operators:
• The relational operators are used to compare two values or variables.
• If a relational operator placed between two operands then it is called simple
condition.
• The result of simple condition is either true (1) or false (0)
• The following are the relational operators.
Operator Meaning Example Result
== Equal to 10 = = 15 0 (F)
!= Not equal to 10 != 15 1 (T)
> Greater than 10 > 15 0 (F)
< Less than 10 < 15 1 (T)
>= Greater than or equal to 10 >= 15 0 (F)
<= Less than or equal to 10 <= 15 1 (T)
3. Logical Operators:
• Logical operators are used to combine two or more simple conditions.
• If a logical operator is placed beftween two or more simple conditions then it is
called compound condition.
• The result of compound condition is also either true (1) or false (0).
Operator Meaning
&& Logical AND
|| Logical OR
! Logical NOT
18 | P a g e
(a) Logical AND (&&) Operator:
• The && operator returns true if all the given conditions are true otherwise returns
false.
• The && operator returns false if any one of the given condition is false otherwise
returns true
Truth Table
Condition1 Condition2 Condition1 && Condition2
TRUE TRUE TRUE
TRUE FALSE FALSE
FALSE TRUE FALSE
FALSE FALSE FALSE
Examples:
10>14 && 15<30 && 67<89 → False
23!=34 && 15>10 && 45<78 → True
(b) Logical OR ( ¦¦ ) Operator:
• The ¦¦ operator returns true if any one of the given condition is true otherwise
returns false.
• The ¦¦ operator returns false if all the given conditions are false otherwise returns
true. Truth Table
Condition1 Condition2 Condition1¦¦ Condition2
TRUE TRUE TRUE
TRUE FALSE TRUE
FALSE TRUE TRUE
FALSE FALSE FALSE
Examples:
10>14 ¦¦ 45<30 ¦¦ 67!=67 → False
23!=34 ¦¦ 15>70 ¦¦ 85<78 → True
(c) Logical NOT (!) Operator:
• This operator negates the result of a condition.
• It means if the condition is true then it gives false. If the condition is false then it
returns true.
Truth Table
Condition ! (Condition)
TRUE FALSE
FALSE TRUE
Example:
!(70<50)→!(false)→true
19 | P a g e
4. Assignment Operators:
• The assignment operators are used to assign (store) a value to a variable.
• An assignment operator always consists of a variable on left hand side and a valid
expression/constant/variable on right hand side.
• There are two types of assignment operators. They are
i. Simple Assignment Operator
ii. Compound Assignment Operators
i. Simple Assignment Operator: The equal sign ‘=’ is used as simple assignment
operator. Syntax: Variable = Expression / Constant / Variable.;
Ex: a = 10; c=a+b; a = b; a = b = 50;
ii. Compound Assignment Operators: These are used to perform arithmetic operation
with the specified variable.
Compound
Syntax: Variable operator = Expression / Constant / Variable.;
Example: Let a=10, then
Operator Example Meaning Final Value of ‘a’
+= a += 5 a=a+5 15
–= a –= 5 a=a–5 5
*= a *= 5 a=a*5 50
/= a /= 5 a=a/5 2
%= a %= 5 a=a%5 0
7. Bitwise Operators:
Java has the capability of manipulating the bits (0 or 1) directly stored in the
memory. These operators perform bitwise operations on a bit by bit level. However, they
must be used only with integer or character type of values. The operators are as follows
Operator Meaning
& Bitwise AND
¦ Bitwise OR
^ Bitwise XOR (Exclusive OR)
~ 1’s complement
<< Left shift
>> Right shift
>>> Right shift with Zero fill
21 | P a g e
Bitwise AND (&) operator: If all the bits are “1” then this operator returns “1” otherwise
it returns “0”.
Truth table:
& 1 0
1 1 0
0 0 0
Example: Let x = 15 and y = 19, then z = x & y is as follows
Value of x : 00001111
Value of y : 00010011
Value of z : 00000011
(x & y)
Bitwise OR ( ¦ ) operator: If any or all the bits are “1” then it returns “1” otherwise it
returns “0”.
Truth table:
¦ 1 0
1 1 1
0 1 0
Example: Let x = 15 and y = 19, then z = x ¦ y is as follows
Value of x : 00001111
Value of y : 00010011
Value of z : 00011111
(x ¦ y)
Bitwise XOR ( ^ ) operator: If one bit is “1” and other is “0” then it returns “1” otherwise
it gives “0”.
Truth table: ^ 1 0
1 0 1
Example: Let x = 15 and y = 19, then 0 1 0 z = x ^ y is as follows
Value of x : 00001111
Value of y : 00010011
Value of z : 00011100
(x ^ y)
1’s complement (~) operator: This operator is a unary operator that reverses the state of
each bit. That means it changes “0” as “1” and “1” as “0”. Example: Let x = 19, then z =
~x is as follows
Value of x : 00010011
Value of z : 11101100
( ~x )
Left Shift (<<) operator:
This operator is used to move bit patterns to the left. It is used in the following form op<<n
,Here, ‘op’ is an integer value and ‘n’ is number of bit positions. The left shift operator shifts
all the bits of operand ‘op’ to the left by ‘n’ positions. The left most ‘n’ bits in the original bit
pattern will be lost and right most ‘n’ bit positions are filled with zeros.
Example: Let us consider ‘a’ is an unsigned integer whose bit pattern is as follows:
a→ 1100110011001111
a<<3 → 0110011001111000
a<<5 → 1001100111100000
22 | P a g e
The left shift operator is used for multiplication purpose. It means, x<<n gives the
result as x*2n. Example : 5<<1 gives 10, 5<<2 gives 20, 5<<3 gives 40
Right Shift (>>) operator: This operator is used to move bit patterns to the right. It is used
in the following form op>>n
Here, ‘op’ is an integer value and ‘n’ is number of bit positions. This operator shifts all
the bits of operand ‘op’ to the right by ‘n’ positions. The right most ‘n’ bits in the original bit
pattern will be lost and left most ‘n’ bit positions are filled with zeros.
Example: Let us consider ‘a’ is an unsigned integer whose bit pattern is as follows:
a→ 1100110011001111
a>>3 → 0001100110011001
a>>5 → 0000011001100110
The right shift operators can also be used for division purpose. It means, x>>n gives the
result as xn
2
Example : 15>>1 gives 7, 15>>2 gives 3, 15>>3 gives 1
8. Special Operators: The following are the special operators used in Java.
1) Instanceof Operator
2) Dot Operator
3) Type Cast Operator
4) new Operator
Instanceof Operator: The instanceof 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 side. This operator
determines whether the object belongs to a particular class or not.
It gives true if the object person belongs to the class student; otherwise it is false
Dot Operator : this operator is also called as member selection operator(.) . the Dot
Operator is used to access the instance variables, methods of class objects, classes, and
sub-packages from a package.
Ex: person.age;
person.salary( );
Type Cast Operator : Cast operator is used to convert one data type into another data
type. This operator can be used by writing datatype inside parenthesis.
new Operator : new operator is used to create objects to classes. Objects are created on
heap memory by JVM, at runtime.
Syntax : classname obj = new classname( );
23 | P a g e
Priority of Operators:
When several operators are used in a statement, it is important to know which operator
will execute first and which will come next. To determine that, certain rules of operator
precedence are followed:
❖ First, the contents inside the braces: ( ) and [ ] will be executed
❖ Next, ++ and --
❖ Next, *, /, and % will execute
❖ + and - will come next
❖ Relational operators are execute next
❖ Boolean and bitwise operators
❖ Logical operators will come afterwords
❖ Then ternary operator
❖ Assignment operators are executed at the last
24 | P a g e
Reading Input with Java.util.Scanner Class:
➢ The Scanner class is mainly used to get the user input, and it belongs to the java.util
package.
➢ In order to use the Scanner class, you can create an object of the class and use any
of the Scanner class methods.
➢ In the below example, we can use nextLine() method, which is used to read Strings.
importjava.util.Scanner;// import the Scanner class
public class Example
{
public static void main(String args[])
{
Scanner s=new Scanner(System.in);//Create a Scanner object
System.out.println(“Enter username”);
String name=s.nextLine();// Read user input
System.out.println(“name is :” +name);//Output user input
}
}
Output: After successful compilation of the above program the output will be:
Enter user name : Venukumar
Name is Venukumar
Scanner Class Methods:-
Method Description
nextBoolean() Reads a Boolean value from the user
nextByte() Reads a byte value from the user
nextDouble() Reads a double value from the user
nextFloat() Reads a float value from the user
nextInt() Reads a int value from the user
nextLine() Reads a String value from the user
nextLong() Reads a long value from the user
nextShort() Reads a short value from the user
BufferedReader class:-
Reads text from a character-input stream, buffering characters so as to
provide for the efficient reading of characters, arrays, and lines. The buffer size
may be specified, or the default size may be used. The default is large enough for
most purposes
BufferedReader is used to decrease the time for taking input. Generally, we
use the Scanner class.
25 | P a g e
Example:-
import java.io.*;
class Addition1
{
public static void main(String args[])
throws Exception
{
int a, b, c;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter any two numbers to add:");
a = Integer.parseInt(br.readLine());
b = Integer.parseInt(br.readLine());
c = a + b;
System.out.println("\nSum of two numbers:" + c);
}
}
Output: Enter any two numbers to add:
30 20
Sum of two numbers: 50
26 | P a g e
Command Line Arguments:
➢ The java command-line argument is an argument i.e. passed at the time of running the
java program.
➢ The arguments passed from the console can be received in the java program and it can
be used as an input
➢ Any argument provided in the command line is stored in a String class array called
args[], which is the formal argument of main() function.
➢ The individual element of an array args[] is accessed by a number called “index”.
➢ The index of first argument is “0” and the index of last argument is “args.length-1”
➢ There is no restriction on the number of java command line arguments. We can specify
any number of arguments.
➢ All the supplied arguments are string class objects later they can be translated into
any other types using “Wrapper classes”.
Syntax:
Example1:
import java.lang.String;
import java.lang.System; Output:
class Cmd Pascal
{ C
public static void main(String[] args) C++
{ Java
for(int i=0;i< args.length;i++) Basic
{ Oracle
System.out.println(args[i]);
}
}
}
Compiling : javac Cmd.java
Running: java Cmd Pascal C C++ Java Basic Oracle
Ex 2:-
class CommandLineExample
{
public static void main(String args[])
{
System.out.println("Your first argument is: "+args[0]);
}
}
Output:- compile by > javac CommandLineExample.java
run by > java CommandLineExample venukumar
Output: Your first argument is: venukumar
27 | P a g e
• Control structures (statements) used to specify the order in which an instruction is
executed in the program.
• Control structures are used to change the execution sequence.
• In Java, the control statements are classified into 3 types. They are as follows:
Control Statements
1. ‘if’ statement:-
It is a conditional branching statement that executes the specified set of
instructions based on the condition.
Condition
T
Syntax: if (condition)
StatementBlock; Statement Block
F
• In the above syntax, if the condition is true then the statements in the statement-
block are executed, otherwise they are not executed.
• When there are multiple statements then they must be enclosed within curly braces
‘{ }’.
Examples:
1. if (avg >= 75)
System.out.println(“grade is distinction”);
2. if (a < 0)
a++;
28 | P a g e
2. ‘if-else’ statement:
It is conditional branching statement that executes the statements based on the
condition. If the condition is true then it executes one group of statements (true part)
otherwise it executes another group of statements (false part).
Flowchart:
Syntax: if (condition)
StatementBlock1;
else Condition
StatementBlock2;
Statement Block-2 Statement Block-1
if (condition1) Flowchar
{
if (condition2)
statement-block1 ; Cond-1
else
statement-block2 ;
} Cond-2 Cond-3
else
{
Statementblock1 Statementblock3
if (condition3) Statementblock2 Statementblock4
statement-block3 ;
else
statement-block4 ;
}
In the above syntax,
i. If ‘condition1’ and ‘condition2’ are true then stament-block1 is executed
ii. If ‘condition1’ is true and ‘condition2’ is false then stament-block2 is executed
iii. If ‘condition1’ is false and ‘condition3’ is true then stament-block3 is executed
iv. If ‘condition1’ and ‘condition3’ are false then stament-block4 is executed
Ex:- class Nesting
{
public static void main(String args[])
{
int a=3,b=7,c=4;
Sytem.out.print(“Larget value is : “);
if( a>b)
{
if(a>c)
System.out.println(a);
else
System.out.println(b);
}
else
{
if (b>c)
System.out.println(b);
else
System.out.println(c);
} } }
29 | P a g e
4. else-If ladder: An if statement followed by at least one else if statement then it is
called else-if ladder. Once an else if succeeds, none of the remaining else if's or else's will
be tested. None of the else-if statements are succeeded the final else statement is
executed.
Syntax:
if(cindition1)
Statement1;
else if(cindition2)
Statement2;
else if(cindition3)
Statement3;
else if(condition n)
Statement n;
else
Default statements;
Example:
int x = 30;
if( x == 10 )
System.out.print("Value of X is 10");
else if( x == 20 )
System.out.print("Value of X is 20");
else if( x == 30 ) {
System.out.print("Value of X is 30");
else
System.out.print("This is else statement");
30 | P a g e
Working:
• If a case value matches to the ‘operand’, the switch statement executes all the
statements in that block.
• If there is ‘break’ statement in that block then it stops execution of switch
statement. If ‘break’ is not present then all the remaining blocks are also executed.
• If any value doesn’t match the operand then the default block is executed, if it is
specified in the switch statement.
Example 1:
int a=4;
switch (a)
{
case 1: System.out.println(“Sunday”);
break;
case 2: System.out.println(“Monday”);
break;
case 3: System.out.println(“Tuesday”);
break;
case 4: System.out.println(“Wednesday”);
break;
case 5: System.out.println(“Thursday”);
break;
case 6: System.out.println(“Friday”);
break;
case 7: System.out.println(“Saturday”);
break;
default: System.out.println(“Wrong Value”);
}
Example 2:-
//To perform all arithmetic operators using switch
import java.util.Scanner;
public class Switchex
{
public static void main(String[] args)
{
int a, b, op;
Scanner sc = new Scanner(System.in); //object of the Scanner class
System.out.println("Enter the first number:");
a = sc.nextInt(); //reading input from the user
System.out.println("Enter the second number:");
b = sc.nextInt();
System.out.println("Enter 1.Addition\n 2.Subtraction \n 3.Multiplication \n 4.division:");
op = sc.nextInt();
switch(op)
{
case 1: System.out.println(+(a+b));
break;
case 2: System.out.println(+(a-b));
break;
case 3: System.out.println(+(a*b));
break;
case 4: System.out.println(+(float)a/b);
break;
default: System.out.println("Wrong Value");
}
}
}
31 | P a g e
The repetitive control statements are used to execute a group of statements
repeatedly as long as the given condition is satisfied. The repetitive control statements are
also called Iterative (or) Looping control statements.
In 'C' language, there are 3 types of repetitive control structures. They are
1. While structure
2. Do…while structure
3. For structure
1. While Structure (while loop):
• This statement executes one or more statements repeatedly as long as the
condition is satisfied.
• It is an entry control loop structure. Because first it evaluates the condition
after that it executes statement part.
• Looping process is continued in while loop as long as the condition is true; when
the condition becomes false the loop will be terminated.
Flow diagram:-
Syntax: while (condition)
{
T
Statementblock; Condition Statement-block
}
F
Here,
− The condition must be enclosed within parenthesis.
The statement-block specifies one or more statements. When there is more than one
statement, they must be enclosed in flower braces ‘{ }’
Ex : class ExWhile
{
public static void main(String args[ ])
{
int i=1;
while(i<=100)
{
System.out.print(i);
++i;
}
}
}
o/p: 1 2 3 4 …….100
Example :
class ExDoWhile
{
public static void main(String args[ ])
{
int i=1;
do
{
System.out.print(i);
++i;
} while(i<=100);
}
} Output:- : 1 2 3 4 …….100
{
statement-block;
}
• It executes the statements in initialization part and then it checks the condition.
• If the condition is true then it executes all the statements in the statement-block.
• After executing all the statements, increment/decrement part is executed then
again checks the condition.
This looping process is continued as long as condition is true. When the condition is false,
the loop is terminated
Flow diagram:-
Ex:- Initialization
class ExFor
{
public static void main(String args[ ]) T
{ Condition
int i;
Statement-block
for(i=1 ; i<=100 ; i++) F
System.out.print(i);
}
} Increment /decrement
33 | P a g e
The unconditional branching statements are used to transfer the control from one
place to another place within a program without using any condition.
The following are the unconditional control structures used in 'JAVA' language.
1. Break 2. Continue 3. Return
1. Jumping out of a Loop (or) Break Statement:
Normally the break statement is used in switch statement. But it is also used to
terminate the execution of a loop unconditionally.
Syntax:
break ;
Example:
int i=1;
for(i=1;i<=100;i++)
{
System.out.println(i);
if(i==50)
Output: 1 2 3 4 …….50
break;
3. Return Statement :
return statement is used in a method to come out of it to the calling method. return
statement is often used in the methods.
Examples : return (x+y); //calculates x+y and return that value
return -5; // return -5 to the calling method.
Ex:- class Demo
{
public static void main( String args [ ] )
{
int res=Demo.square(10);
System.out.println(“Result = “ + res);
}
static int square(int num)
{
return num * num;
}
} Output : Result = 100
34 | P a g e