JavaUNIT-1 Notes (1)
JavaUNIT-1 Notes (1)
JavaUNIT-1 Notes (1)
Modular structure OOP provides a clear and modular structure for program development. This enables us to define abstract
data types where implementation details can be kept hidden.
Easy to maintain and upgrade Object-oriented systems can be easily upgraded. It is easy to maintain and modify the
existing code. Because of the modularity, it is easier to locate and correct the problem rather than search for the problem in
the entire program.
Inheritance This allows us to eliminate redundant code and use existing classes.
Data hiding The programmer can hide the data and functions in a class from other classes. It helps in the building of secure
programs.
History of java:
Java was developed by James Gosling in 1995, he is known as the father of java. Java team members are known as Green
Team, they initiated a revolutionary task to develop a language for digital devices such as set-top boxes, televisions etc.
Currently, Java is used in internet programming, mobile devices, games, e-business applications etc. Firstly it was called
"Greentalk" by James Gosling. Later, it is changed to “Oak”.
Why Oak name for Java language? Oak is a symbol of strength and choosen as a national tree of many countries like
U.S.A., France, Germany, Romania etc. In 1995, Oak was renamed as "Java" because it was already a trademark by Oak
Technologies.
INTRODUCTION TO JAVA:
It is a simple programming language. Java makes writing, compiling, and debugging programming easy. It helps to create
reusable code and modular programs. Java is a class- based, object-oriented programming language and is designed to have
as few implementation dependencies as possible. A general-purpose programming language made for developers to write
once run anywhere that is compiled Java code can run on all platforms that support Java. Java applications are compiled to
byte code that can run on any Java Virtual Machine. The syntax of Java is similar to c/c++. Now more than 3 billion devices
run java.
Features of Java (buzz words)
There is given many features of java. They are also known as java buzzwords.
1. Simple
2. Object-Oriented
3. Portable and Platform independent
4. Secured
5. Robust
6. Architecture neutral
7. Multithreaded
8. Distributed applications
9. Compiler/Interpreter
Simple:
Java is simple language. It does not use pointer, goto statements, etc. It eliminates operator overloading and
multiple inheritance.
Object-Oriented:
Everything in java is an object. Object oriented means we organise our software as a combination of different
types of objects that incorporates both data and behaviour.
Portable and Platform independent:
Write once and run anywhere. Java programs are portable because of its ability to run the program on any
platform and no dependency on the underlying hardware/operating system.
Secured:
Security is an important feature of Java and this is the strong reason that programmer use this language for
programming on Internet. The absence of pointers in Java ensures that programs cannot get right of entry to
memory location without proper approval.
Robust:
Java is a most strong language which provides many securities to make certain reliable code. It is design as
garbage –collected language, which helps the programmers virtually from all memory management problems.
Java also includes the concept of exception handling, which detain serious errors and reduces all kind of threat
of crashing the system.
Architecture neutral:
Irrespective of architecture the memory allocated to the variables will not vary. Whatever the architecture we
are using that memory allocated for the variables is same.
Eg: In C language the size of the datatype is depends on the architecture of the compiler, So if we take integer
variable in 16bit compiler it occupies 2bytes of memory, and if it is 32bit compiler it is 4bytes of memory.
Here, the memory allocation depends on the architecture.
Multithreaded:
Concurrent execution of several parts of same program at same time. So this will improve CPU utilization.
Distributed applications:
It is software that runs on multiple computers connected to a network at the same time. [A java program is able
to create this Distributed applications].
Compiler/Interpreter: Usually a computer language is either compiled or interpreted. Java combines both these
approaches thus making java a two-stage system. First, java compiler translates source code into bytecode.
Bytecodes are not machine instructions and therefore, in the second stage, java interpreter generates machine
code that can be directly executed by the machine that is running the java program so we can say that java is
both compiled and interpreted language.
2 C is divided into small parts called 2 Java is divided into some parts called class and
functions. objects.
8 In C declaration variables are declared at 8 In Java variables are declared any where.
the beginning.
9 free() is a function to release the memory 9 A compiler will free up the memory by calling the
in C. Garbage collector.
11 Function oriented program follows top to 11 Object oriented programming follows bottom up
down approach. approach.
12 C does not have access 12 It has 3-access specifiers public, private, protected
specifiers/modifiers. and default.
13 Data can move freely from function to 13 Objects can move and can communicate with each
function in the system. other.
14 No data hiding is possible hence, security 14 In Java provides data hiding hence, security is
is not possible. possible.
Documentation Section:
It is an important section but optional for a java program. It includes basic information about a java program. The
information includes the description of the program. Whatever we write in the documentation section, the java compiler
ignores the statements during execution of the program. To write the statements in the documentation section, we use
comments. The comments may be single-line, multi-line and documentation comments.
Single-line comment: //Example for Single line comment
Multi-line comment: /*it is an example of multiline comment*/
Documentation comment: /**it is an example of documentation comment*/ (This comment style is new in java. The main
purpose of this type of comment is to automatically generate program documentation. The java doc tool reads these
comments and uses them to prepare your program’s documentation in HTML format.)
Package Declaration:
It is an optional declaration. Package name can be defined by programmer with any name. Package contains a group
of classes. By default compiler consider as these classes, which are defined under it belongs to this package.
Package packagename;
Import statements:
It contains many predefined classes and interfaces. If we want to use any class of a
particular package, we need to import that class. We use the import keyword to import the class.
import java.util.Scanner; //it imports the scanner class
import java.util.*; //it imports all the class of the java.
Interface Section:
An interface is similar to classes, which consist of group of method declaration. It is an optional section and can be
used when programmers want to implement multiple inheritance.
Interface car
{
Void start();
Void stop();
}
Class Definition:
In this section, we define the class. Without the class, we cannot create any java program. We use the class keyword
to define the class.
class Example //class definition
{
}
Main method:
In this section, we define the main() method. It is essential for all java programs. Because the execution of all java
programs starts from the main() method. In other words, it is an entry point of the class. It must be inside the class.
public static void main(String args[])
{
}
WRITING SIMPLE JAVA PROGRAMS:
Java is purely an object-oriented language and the classes are the means to achieve the same. Therefore, after the import
statement, as discussed, every program starts with the declaration of a class. A program may have one or more classes. A
class declaration starts with the keyword class, followed by the identifier or name of the class. Giving the name of a
package at the top is optional.
In Program 2.1, the class name is Start. The body of the class, which may consist of several statements or calls to other
methods, is enclosed between the braces {}. A sample of class declaration is illustrated in Fig. 2.1.
Java’s main() method is the starting point from where the JVM starts the execution of a Java
program. JVM will not execute the code, if the program is missing the main method. Hence, it is one of the most important
methods of Java, and having a proper understanding of it is very important.
The Java compiler or JVM looks for the main method when it starts executing a Java program. The signature of the main
method needs to be in a specific way for the JVM to recognize that method as its entry point. If we change the signature of
the method, the program compiles but does not execute.
Java Example
Let's have a quick look at java programming example
1. class Simple {
2. public static void main(String args[]) {
3. System.out.println("Hello Java");
4. }
5. }
Public:
It is an access modifier, which specifies from where the main() method public makes it globally available. It is made public,
so that JVM (java virtual machine) can invoke it from outside the class as it is not present in the current class.
class Example
{
private static void main(String[] args)
{
System.out.print(“a”);
}
Output:
Error: method not found in class, please define the main method as:
public static void main(String[] args)
Static (Direct access without object):
It is a keyword when it is associated with a method, makes it a class related method. The main() method is static so that JVM
can invoke it without instantiating the class(Without creating an object for a class).
class Ex
{
public void main(String[] args)
{
System.out.print(“a”);
}
Output: Error: method not found in class Ex, please define the main method as:
public static void main(String[] args).
Void:
It is a keyword and is used to specify that a method doesn’t return anything. As the main() method doesn’t return
anything, its return type is void. As soon as the main() method terminates, the Java program terminates too. In Java, every
method has the return type. Void keyword acknowledges the compiler that main() method does not return any value. Hence,
it doesn’t make any sense to return from the main() method as JVM can’t do anything with its return value of it.
If main method is not void, we will get an error.
Main:
It is the name of java main method & it is the identifier that the JVM looks for as the starting point of the java program.
Note: main is not a keyword.
String[] args:
It stores java command line arguments and is an array of type. (When you run a java program with command prompt or want
to give command line arguments, then “String[] args” is used) Here, the name of the string array is args but it is not fixed and
user can use any name.
The main() method also accepts some data from the user. It accepts a group of strings, which is called a string array. It is used
to hold the command line arguments in the form of string values.
main(String args[])
Here, agrs[] is the array name, and it is of String type. It means that it can store a group of string. Remember, this array can
also store a group of numbers but in the form of string only. Values passed to the main() method is called arguments. These
arguments are stored into args[] array, so the name args[] is generally used for it.
The class body starts with the left brace ({) and ends with the right closing brace (}). A class body may comprise statements
for declaration of variables, constants, expressions, and methods.
In the aforementioned case, we have written “class body” after// because it is a comment. Anything written after double slash
(//) up to the end of a line becomes a comment. Comments are neglected by the compiler. They are not part of a program.
Tokens are the smallest elements of a program that is meaningful to the compiler. They are also known as the
fundamental building blocks of the program.
Java compiler breaks the line of code into text (words) is called Java tokens.
Tokens can be classified as follows:
1. Keywords
2. Identifiers
3. Constants/literals
4. Separators
5. Operators
6. Comments
Keyword: Keywords are pre-defined or reserved words in a programming language. Each keyword is
meant to perform a specific function in a program. Since keywords are referred names for a compiler,
they can’t be used as variable names because by doing so, we are trying to assign a new meaning to
the keyword which is not allowed. Java language supports following keywords:
Identifiers:
Identifiers are used to name a variable, constant, function, class, and array. Remember that the identifier name must be
different from the reserved keywords.
2.All names of classes and interfaces should start with a capital letter, if the name contains more than
one word then the second word’s first character should be capital letter. Ensure that there should not
be any spaces between the words.
Ex:- Student, HelloJava
3.All the Names of variables should start with a lower-case character. If more than one word is present,
the other words should start with upper case character. The names are generally nouns.
Some examples are s, x, y, ch, price, age, etc.
4. Names of Constant variables should be written in capital letters and if there are more than one word
an underscore is used between words.
Ex:- MAX, TOTAL_VALUE
5. Names of packages should be written in name should be in written in lowercase only.Ex:- mypack,
mypackage, java.lang etc
Constants/Literals:
Constants are also like normal variables. But the only difference is, their values cannot be modified by the
program once they are defined. Constants refer to fixed values. They are also called as literals. Constants may
belong to any of the data type.
In java, a literal may be one of the following
1. Integer literals
2. Floating point literals
3. Boolean literals
4. Character literals
5. String literals
6. Null Literals
Integer Literals: Interger literals are sequence of digits. The whole numbers are described by different number
systems such as decimal numbers, hexadecimal numbers, octal numbers, and binary numbers. Each number has a
different set of digits. The digital literals may be of the following types.
Decimal Integer Literals : These are sequences of decimal digits which are 0, 1, 2, 3, 4, 5, 6, 7, 8, and 9. The
decimal numbers are the numbers used in everyday computation. Examples of such literals are 6, 453, 34789, etc.
Hex Integral Literals: These are sequences of hexadecimal digits which are 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D,
E, and F. The values 10 to 15 are represented by A, B, C, D, E, and F or a, b, c, d, e, and f. The numbers are
preceded by 0x or 0X for distinction. Examples are 0x56ab or 0X6AF2, etc.
Octal Integer Literals: These are sequences of octal digits which are 0, 1, 2, 3, 4, 5, 6, and 7. For distinction,
these numbers are preceded by 0. Examples of literals are 07122, 04, 043526, etc.
Binary Literal: These are sequences of binary digits. Binary numbers have only two digits—0 and 1 and a base 2.
These numbers are preceded by 0b for identification by the computer. Examples of such literals are 0b0111001,
0b101, 0b1000, etc.
Floating Point Literal: These are floating decimal point numbers or fractional decimal numbers with base 10.
Examples of such numbers are 3.14159, 567.78, etc.
Boolean Literal: These are Boolean values. There are only two values—true or false.
Character Literal: These are the values in characters. Characters are represented in single quotes such as ‘A’,
‘H’, ‘k’, and so on. The character may as well be represented in hexadecimal or octal numbers. More examples are
‘b’, ‘z’, ‘\uFFFF’, ‘\178’, etc.
String Literals: These are strings of characters in double quotes. Examples are “Delhi”, “John”, “AA”, etc.
Null Literal: There is only one value of Null Literal, that is, null.
Seperators:- In java, the different separators are represented by parentheses ‘()’, braces ‘{}’, square brackets ‘[]’,
commas ‘,’, semicolon ‘;’, and period ‘.’. Each of these is used for different applications as listed in Table 2.3.
Operators:- There are 37 operators in Java. Java provides many types of operators which can be used according
to the need. They are classified based on the functionality they provide. Some of the types are-
Arithmetic Operators
Unary Operators
Assignment Operator
Relational Operators
Logical Operators
Ternary Operator(conditional operator)
Bitwise Operators and bit-shift operators
instance of operator
Comments:
In Java, Comments are the part of the program which are ignored by the compiler while compiling the Program.
They are useful as they can be used to describe the operation or methods in the program. The Comments are
classified as follows:
• Single Line Comments
• Multiline Comments
The documentation section is optional and contains the comments in the java program code. The comments are
part of java program that are ignored and not compiled by the compiler.
The main purpose of the comments in the documentation section is to improve the readability and
maintainability of the java programming code. The comments are added to the program code especially in the
large and complex project where number of programmers are writing the programming code. The comments
inserted in the program code makes it easier to understand the programming code.
The documentation section is an important section but optional for a Java program. It includes basic information
about a Java program. The information includes the author's name, date of creation, version, program name,
company name, and description of the program. It improves the readability of the program. Whatever we write in
the documentation section, the Java compiler ignores the statements during the execution of the program. To write
the statements in the documentation section, we use comments. The comments may be single-line, multi-line,
and documentation comments.
Package statement:
The package statement in java program is optional and identifies the package that a java program is a part of the
package. The package declaration is optional. It is placed just after the documentation section. In this section, we
declare the package name in which the class is placed. Note that there can be only one package statement in a
Java program. It must be defined before any class and interface declaration. It is necessary because a Java class
can be placed in different packages and directories based on the module they are used. For all these classes
package belongs to a single parent directory. We use the keyword package to declare the package name. For
example:
Import statements:
This is the statement after the package statement. It is similar to # include in c/c++. The package contains the
many predefined classes and interfaces. If we want to use any class of a particular package, we need to import that
class. The import statement represents the class stored in the other package. We use the import keyword to import
the class. It is written before the class declaration and after the package statement. We use the import statement in
two ways, either import a specific class or import all classes of a particular package. In a Java program, we can use
multiple import statements.
For example:
The above statement instructs the interpreter to load the Scanner class from the java.util package.
Note:
Import statement should be before the class definitions.
A java file can contain N number of import statements.
Interface statements:
An interface is like a class but includes a group of method declarations. It is an optional section. We can create an
interface in this section if required. We use the interface keyword to create an interface. An interface is a slightly
different from the class. It contains only constants and method declarations. Another difference is that it cannot
be instantiated. We can use interface in classes by using the implements keyword. An interface can also be
used with other interfaces by using the extends keyword. For example:
interface car
{
void start();
void stop();
}
Note: Methods in interfaces are not defined just declared.
Class definitions:
Java is a true oop, so classes are primary and essential elements of java program. A programcan have multiple
class definitions. In this section, we define the class. It is vital part of a Java program. Without the class, we cannot
create any Java program. A Java program may conation more than one class definition. We use the class keyword
to define the class. The class is a blueprint of a Java program. It contains information about user-defined methods,
variables, and constants. Every Java program has at least one class that contains the main() method.
For example
class Student
{
//class definition
}
Main method class:
Every stand-alone program required a main method as its starting point. As it is true oop the main method is kept
in a class definition. Every stand-alone small java program should contain at least one class with main method
definition. In this section, we define the main() method. It is essential for all Java programs. Because the
execution of all Java programs starts from the main() method. In other words, it is an entry point of the class. It
must be inside the class. Inside the main method, we create objects and call the methods. We use the following
statement to define the main() method:
JAVA STATEMENTS:
The java program consists of set of instructions, where every instructions are called statements
in java.
A statement specifies an action in a Java program.
Java statements can be broadly classified into the following categories:
Empty Statement
Variable Declaration statement
Labelled Statement
Expression statement
Control statement
Selection statement
Iteration statement
Jump statement
Synchronization statement
Guarding statement
COMMAND LINE ARGUMENTS:
A Java application can accept any number of arguments from the command line. These arguments can be passed at
the time of running the program. This enables a programmer to check the behaviour of a program for different
values of inputs. When a Java application is invoked, the runtime system passes the command line arguments to
the application’s main method through an array of strings. It must be noted that the number of arguments that we
can pass through a command line can be obtained through the number of elements in an array. To ensure this, we
can make use of the length property of the array. Command line arguments are parameters that are passed to the
application program atthe time of execution. The parameters are received by args array of string type.
The first argument is stored at args[0]
The second argument is stored at args[1] and so on…..
Example 1:
class Xyz
{
public static void main(String args[])
{
System.out.println(“Enter any number:” +args[0]);
}
}
OUTPUT:
Compile: javac Xyz.java
run: java Xyz 23
EXAMPLE-2
class Sum
{
public static void main(String ar[])
{
int x,y,s;
x=Integer.parseInt(ar[0]);
y=Integer.parseInt(ar[1]);
s=x+y;
System.out.println("sum of " + x + " and " + y +" is " +s);
}
}
OUTPUT:
Method Description
import java.util.*;
class UserInputDemo
{
public static void main(String[] args)
{
Scanner sc= new Scanner(System.in); //System.in is a standard input stream
System.out.print("Enter first number- ");
int a= sc.nextInt();
System.out.print("Enter second number- ");
int b= sc.nextInt();
System.out.print("Enter third number- ");
int c= sc.nextInt();
int d=a+b+c;
System.out.println("Total= " +d);
}
}
ESCAPE SEQUENCE CHARACTERS:
If a character is preceded by a backslash (\) is known as Java escape sequence or escape characters.
It may include letters, numerals, punctuations, etc.
Escape characters must be enclosed in quotation marks (""). These are the valid character literals.
The Java compiler interprets these characters as a single character that adds a specific meaning to the
compiler.
Escape Characters Description
programming style refers to the conventions and guidelines followed to write clean, readable, and
maintainable code. While there are various style guides (like Google's, Oracle's, and others), the core
principles remain consistent.
Key Elements of Java Programming Style
Naming Conventions
Class names: Start with a capital letter, use nouns or noun phrases (e.g., Customer, OrderProcessor).
Method names: Start with a lowercase letter, use verbs or verb phrases (e.g., calculateTotal,
displayMessage).
Variable names: Start with a lowercase letter, use descriptive names (e.g., customerName,
orderQuantity).
Constants: Use all uppercase letters with underscores (e.g., MAX_VALUE, PI).
Indentation and Formatting
Use consistent indentation (usually 4 spaces).
Place opening curly braces on the same line as the control structure (e.g., if, for, while).
Use braces for all control structures, even for single-line statements.
Limit line length to improve readability.
Comments
Use clear and concise comments to explain the code's purpose.
Add comments to clarify complex logic or non-obvious code sections.
Avoid excessive commenting; well-named variables and methods often reduce the need for comments.
Code Organization
Break down code into logical methods and classes.
Use meaningful and descriptive method and class names.
Follow a consistent structure within classes (e.g., fields, constructors, methods).
Use appropriate access modifiers (public, private, protected).
Code Readability
Use meaningful variable and method names.
Avoid magic numbers; use constants instead.
Write clean and concise code.
Consider using white space effectively to improve readability.
VARIABLES:
A variable in Java is essentially a named container that holds data values during program execution. It's like a
box with a label (the variable name) where you can store different items (data).
Key Characteristics:
Data Type: Defines the type of data a variable can hold (e.g., numbers, characters, text).
Name: A unique identifier for the variable.
Value: The data stored in the variable, which can change during program execution.
Declaring a Variable
To use a variable, you must first declare it, specifying its data type and name:
Java
data_type variable_name;
Example:
Java
int age;
String name;
double salary;
Assigning a Value
Once declared, you can assign a value to a variable using the assignment operator (=):
Java
age = 30;
name = "Alice";
salary = 50000.50;
There are three types of variables:
1. Local variable
2. Instance variable
3. Static/class variable.
Local variable:
A variable that is declared and used inside the body of methods, constructor or blocks is called
local variable, it cannot be defined with "static" keyword.
{
data_type variable=value;
}
}
{
int z=x+y;
System.out.println(z);
}
public static void main(String[] args)
{
Localvar v= new Localvar();
v.m(10,20);
}
OUTPUT:
30
Instance variable:
A variable that is declared inside the class but outside the body of a method, constructor or any block
are called instance variable.
The instance variable is initialized at the time of the class loading or when an object of the class is
created.
An instance variable can be declared using different access modifiers available in Java like default,
private, public, and protected.
Syntax:
class class_name
{
}
}
int a=10;
public static void main(String[] args)
{
OUTPUT:
10
Static variable:
A variable which is declared with a static keyword is called a static variable. It is also called as a class
variable, because it is associated with a class.
Static variables are always declared inside the class but outside of any methods, constructors or any blocks.
Static variable will get the memory only once. If we changes the value of static variable, it will replace the
previous value and display the changed value, this is because it is constant for every object created.
Syntax:
class class_name
{
…………
………….
}
}
OUTPUT:
10
10
//EXAMPLE 2
class StaticDemo
{
Static int count=0;
public void increment()
{
count++;
}
public static void main(String args[])
{
StaticDemo obj1=new StaticDemo ();
StaticDemo obj2=new StaticDemo ();
StaticDemo obj3=new StaticDemo ();
obj1.increment();
obj2.increment();
obj3.increment();
System.out.println("Obj1: count is="+obj1.count);
System.out.println("Obj2: count is="+obj2.count);
System.out.println("Obj3: count is="+obj3.count);
}
}
//program to demonstrate local, instance, and static variables
class Example
{
int a=10;
static int b=20;
void m()
{
int c=30;
int d=a+b+c;
System.out.println(d);
}
OUTPUT:
20
20
60
10
Scope and life time of variable:
Scope Lifetime of variable
Instance variable: Throughout the class except in Until the object stays in
Static methods. memory.
Static variable: Throughout the class Until the end of the program.
Data Types:
Data types specify the different sizes and values that can be stored in the variable. There are two types of data
types in Java:
1. Primitive data types: The primitive data types include boolean, char, byte, short, int, long, float and
double.
2. Non-primitive data types: The non-primitive data types include Classes, Interface, Strings and
Arrays.
● Why Java is strongly typed language?
Java is a strongly typed programming language because every variable must be declared with a data type.
Data Type Default Value Default size Range
2,147,483,648 to
int 0 4 bytes or 32 bits
2,147,483,647
9,223,372,036,854,775,808
long 0 8 bytes or 64 bits to
9,223,372,036,854,775,807
Key Characteristics:
User-defined: Created by programmers to represent specific data structures.
Reference variables: Instead of holding direct values, they hold references to memory locations
where the actual data is stored.
Memory allocation: Typically allocated on the heap.
Size: Not fixed, can vary depending on the data stored.
Rich set of methods: Offer a wide range of operations through built-in methods.
Understanding with Examples:
// String (non-primitive)
String name = "Alice"; // Holds a reference to a String object
// Array (non-primitive)
int[] numbers = {1, 2, 3, 4, 5}; // Holds a reference to an integer array
// Class (non-primitive)
class Person
{
String name;
int age;
}
Person person1 = new Person(); // Creates a Person object
person1.name = "java";
person1.age = 10;
// Driver Class
class Date_Time
{
// main function
public static void main(String[] args)
{
Date time = new Date();
// Driver Class
class Date_Time {
// main function
public static void main(String[] args)
{
Date time = new Date();
Output
Current Time: 11:32:36
Hours: 11 Minutes: 32 Seconds: 36
Attribute Final:
Operators
An operator is a special symbol performing specific operations on operands. The operators are classified and listed
according to their precedence order. Java operators are generally used to manipulate primitive data types.
1. Arithmetic operator
2. Unary operator
3. Ternary operator
4. Assignment operator
5. Relational operator
6. Bitwise operator
7. Logical operator
Arithmetic operator:
Java arithmetic operators are used to perform addition, subtraction, multiplication, and division. They act as basic
mathematical operations.
// Arithmetic Operator Example
class Arithmetic
{
public static void main(String[] args)
{
int a=1+1;
int b=a*3;
int c=b/4;
int d=c-a;
int e=42%10;
System.out.println(“a=”+a);
System.out.println(“b=”+b);
System.out.println(“c=”+c);
System.out.println(“d=”+d);
System.out.println(“e=”+e);
}
}
OUTPUT:
a=2
b=6
c=1
d=-1
e=2
Unary operator:
The ++ and – increment and decrement operators. The increment operator increases the operand value by 1 and the
decrement operator decreases the operand value by 1, these operators are unique in that they can appear both in
postfix and prefix forms. In the prefix form the operand is incremented or decremented before the value is
obtained. In the postfix form the previous value is obtained for the use in the expression and then the opearand is
modified.
Ex:
x=42 x=42
y=++x; y=x++;
O/P: y=43 O/P: y=42
//java program using unary operator
public class unaryop
{
public static void main(String[] args)
{
int r = 6;
System.out.println("r=: " + r++);
System.out.println("r=: " + r);
int x = 6;
System.out.println("x=: " + x--);
System.out.println("x=: " + x);
int y = 6;
System.out.println("y=: " + ++y);
int p = 6;
System.out.println("p=: " + --p);
}
}
Ternary Operator
The ternary operator is a conditional operator that decreases the length of code while performing
comparisons and conditionals. This method is an alternative for using if-else and nested if-else statements.
The order of execution for this operator is from left to right.
Condition: It is the expression to be evaluated which returns a boolean value. Statement 1: It is the
statement to be executed if the condition results in a true state.
//Example program
class Test
{
public static void main(String[] args)
int febdays=29;
String result;
}
}
{
int a = 10;
int b = 20;
int c = 0;
c = a + b;
System.out.println("c = a + b = " + c );
c += a ;
System.out.println("c += a = " + c );
c -= a ;
System.out.println("c -= a = " + c );
c *= a ;
System.out.println("c *= a = " + c );
}
}
Relational Operator: These are used to compare two operands/ variables for equality, non equality, greater
than, less than, it always returns a Boolean value true or false.
int a=10;
int b=20;
System.out.println(“a==b:” + a==b);
System.out.println(“a!=b:” + a!=b);
System.out.println(“a>b:” + a>b);
System.out.println(“a=b:” + a>=b);
System.out.println(“a<=b:” + a<=b);
Bitwise Operator: These are used to perform manipulation of individual bits of their operands. They can be
applied to the integer types long, int, short and byte.
Types of Bitwise Operator
Bitwise AND &
Bitwise exclusive OR ^
Bitwise inclusive OR |
Bitwise Compliment ~
Bitwise left shift <<
Bitwise right shift >>
Unsigned Right Shift Operator >>>
{
public static void main(String[] args)
{
int x = 9, y = 8; // bitwise and
System.out.println("x & y = " + (x & y)); // 1001 & 1000 = 1000 = 8
}
OUTPUT:
x&y =8
//BitwiseXorExample
public class BitwiseXorExample
OUTPUT:
x^y=1
//BitwiseInclusiveOrExample
public class BitwiseInclusiveOrExample
{
OUTPUT:
x|y=9
//Write a program for Bitwise Operators.
class BitwiseOp
{
int a=60;
int b=13;
int c;
System.out.println(“a&b:” +c);
System.out.println(“a|b:” +c);
System.out.println(“a^b:” +c);
c=~a;
System.out.println(“~a:” +c);
c=a>>2;
System.out.println(“a>>2:” +c);
c=a<<>>2;
System.out.println(“a>>>2:” +c);
int x = 50;
System.out.println("x>>2 = " + (x >>2));
OUTPUT:
x>>2=12
{
public static void main(String[] args)
byte x,y;
x=10;
y=-10;
System.out.println(“Bitwise leftshift: x<<>2 =”+(x>>2));
Logical Operators
Logical operators are used to check whether an expression is true or false. They are used in decision making.
Operators
&& (Logical AND)
|| (Logical OR)
! (Logical NOT)
//Write a program for logical operators AND, OR, NOT
class Main
// || operator
// ! operator
• Associativity: This defines the order in which operators of the same precedence are evaluated.
It can be left-to-right or right-to-left.
Operator Associativity
` ` (bitwise OR)
` ` (logical OR)
Example
Consider the expression: int result = 5 + 3 * 2;
//EXAMPLE
public class OperatorPrecedenceExample
{
public static void main(String[] args) { int a = 5, b = 3, c = 2;
// Example 1: Precedence
// Example 2: Associativity
int result2 = a = b = c; // Output: 2
System.out.println("Result 2: " + result2);
Note:
• Associativity determines the order of evaluation when operators have the same precedence.
Control statements
Control statements is one of the fundamentals required for programming. It determines which statement to
execute, and it controls the flow of execution of the program. Statements can be executed multiple times or
only under a specific condition.
(or)
The default execution flow of a program is a sequential order. But the sequential
order of execution flow may not be suitable for all situations. Sometimes, we may
want to jump from line to another line, we may want to skip a part of the program,
or sometimes we may want to execute a part of the program again and again. To
The ”selection” statements are used for testing conditions, the “ iteration” statements are used to create
cycles, and the jump statements is used to alter a loop.
Syntax:
if(condition)
{
statement; //executes when condition is true
int x = 10;
int y = 12;
if(x+y > 20)
}
}
if-else statement:
The if-else statement is an extension to the if statement, which uses another block of code, i.e., else block.
The else block is executed if the condition of the if block is evaluated as false.
Syntax:
if(condition)
else
{
{
int a=15;
if(a>20)
}
else
}
}
Syntax:
if(condition 1)
{
else if(condition 2)
{
statement 2; //executes when condition 2 is true
}
else
{
statement 2; //executes when all the conditions are false
System.out.println("city is meerut");
}
else if (city == "Noida")
System.out.println("city is noida");
{
System.out.println("city is agra");
else
{
System.out.println(city);
}
}
}
Iteration Statements
• An iteration statement, or loop, repeatedly executes a statement, known as the loop body, until the
controlling expression is false (0).
The while statement evaluates the control expression before executing the loop body.
The do statement evaluates the control expression after executing the loop body; at least one execution of
the loop body is guaranteed.
The for statement executes the loop body based on the evaluation of the second of three expressions
Syntax :
while (boolean condition)
loop statements...
//Example
import java.io.*;
class WhileExample
{
int i=0;
while (i<=10)
{
System.out.println(i);
i++;
}
for loop:
Syntax:
for (initialization condition; testing condition;increment/decrement)
statement(s)
//Example
import java.io.*;
class ForExample
{
System.out.println(i);
do while:
Syntax:
do
{
statements..
}
while (condition);
//Example
import java.io.*;
class DoWhileEx
{
int i=0;
do
System.out.println(i);
i++;
}
while(i<=10);
• Nested Loop:
• Nested loop means a loop statement inside another loop statement.
• There are different combinations of loop using for loop, while loop, do-while loop.
import java.io.*;
class NestedFor
{
public static void main (String[] args)
{
for(int i = 0; i < 3; i++)
{
for(int j = 0; j < 2; j++)
{
System.out.println(i);
}
System.out.println();
}
}
}
For-each loop
• A for-each loop is a simplified way to iterate through elements in an array.
Syntax:
for (data_type variable : array)
Example:
// Array of numbers
int[] numbers = {1, 2, 3, 4, 5};
System.out.println(number);
}
}
{
public static void main(String[] args)
{
// array declaration
int ar[] = { 10, 50, 60, 80, 90 };
for (int element : ar)
Continue Statement
• Statement is often used inside in programming languages inside loops control structures. Inside the
loop, when a continue statement is encountered the control directly jumps to the beginning of the
loop for the next iteration instead of executing the statements of the current iteration.
Syntax:
continue;
{
// For loop for iteration
if (i == 10 || i == 12) {
Break statement
• Break Statement is a loop control statement that is used to terminate the loop. As soon as the break
statement is encountered from within a loop, the loop iterations stop there, and control returns from the
loop immediately to the first statement after the loop.
Syntax:
break;
//Example
public class BreakExample
{
for (int i = 1; i <= 10; i++)
System.out.println(i);
if (i == 5)
{
break; // Terminates the loop when i becomes 5
System.out.println("Loop is terminated.");
}
}