SlideShare a Scribd company logo
JAVA
PROGRAMMING
UNIT - I
Introduction to Java – Naming conventions and data types – Literals – operators in
Java – Control statements in Java – Classes and Objects – Instance Variables, set
Methods – Initializing objects with constructors.
INTRODUCTION TO JAVA
• JAVA was developed by James Gosling at Sun Microsystems in the
year 1991, later acquired by Oracle Corporation.
• Java is a programming language and a platform.
• Java is a high level, robust, object-oriented and secure 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++.
Why named as JAVA?
•Java is the name of an island in Indonesia where the first coffee (named java coffee)
was produced.
•And this name was chosen by James Gosling while having coffee near his office.
Note that Java is just a name, not an acronym.
Why we use Java?
• Java works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc.)
• It is one of the most popular programming language in the world
• It is easy to learn and simple to use
• It is open-source and free
• It is secure, fast and powerful
• It has a huge community support (tens of millions of developers)
• Java is an object oriented language which gives a clear structure to programs and
allows code to be reused, lowering development costs
• As Java is close to C++ and C#, it makes it easy for programmers to switch to Java or
vice versa
Java Applications
• Mobile applications (specially Android apps)
• Desktop Applications such as acrobat reader, media player, antivirus, etc.
• Enterprise Applications such as banking applications.
• Web applications such as irctc.co.in
• Web servers and application servers
• Embedded System
• Smart Card
• Robotics
• Games
• Database connection
• And much, much more!
Types of Java Applications
There are mainly 4 types of applications that can be created using Java programming:
1) Standalone Application
Standalone applications are also known as desktop applications or window-based
applications. These are traditional software that we need to install on every machine.
Examples of standalone application are Media player, antivirus, etc. AWT and Swing are
used in Java for creating standalone applications.
2) Web Application
An application that runs on the server side and creates a dynamic page is called a web
application. Currently, Servlet, JSP, Struts, Spring, Hibernate, JSF, etc. technologies are used for
creating web applications in Java.
3) Enterprise Application
An application that is distributed in nature, such as banking applications, etc. is called an
enterprise application. It has advantages like high-level security, load balancing, and clustering.
In Java, EJB is used for creating enterprise applications.
4) Mobile Application
An application which is created for mobile devices is called a mobile application. Currently,
Android and Java ME are used for creating mobile applications.
Java Platforms / Editions
There are 4 platforms or editions of Java:
1) Java SE (Java Standard Edition)
It is a Java programming platform. It includes Java programming APIs such
as java.lang, java.io, java.net, java.util, java.sql, java.math etc. It includes
core topics like OOPs, String, Regex, Exception, Inner classes,
Multithreading, I/O Stream, Networking, AWT (Abstract Window Toolkit),
Swing, Reflection, Collection, etc.
2) Java EE (Java Enterprise Edition)
It is an enterprise platform that is mainly used to develop web and enterprise
applications. It is built on top of the Java SE platform. It includes topics like Servlet,
JSP, Web Services, EJB, JPA, etc.
3) Java ME (Java Micro Edition)
It is a micro platform that is dedicated to mobile applications.
4) JavaFX
It is used to develop rich internet applications. It uses a lightweight user interface API.
Main Features of Java
1. Platform Independent: Compiler converts source code to bytecode and then the
JVM executes the bytecode generated by the compiler.
•This bytecode can run on any platform be it Windows, Linux, macOS which means if
we compile a program on Windows, then we can run it on Linux and vice versa.
•Each operating system has a different JVM, but the output produced by all the OS is the
same after the execution of bytecode.
•That is why we call java a platform-independent language.
2. Object-Oriented Programming Language: Organizing the program in the terms of
collection of objects is a way of object-oriented programming, each of which represents an
instance of the class.
The four main concepts of Object-Oriented programming are:
•Abstraction
•Encapsulation
•Inheritance
•Polymorphism
3. Simple: Java is one of the simple languages as it does not have complex features like
pointers, operator overloading, multiple inheritances, Explicit memory allocation.
4. Robust: Java language is robust that means reliable. It is developed in such a way that it
puts a lot of effort into checking errors as early as possible, that is why the java compiler is
able to detect even those errors that are not easy to detect by another programming language.
The main features of java that make it robust are garbage collection, Exception Handling,
and memory allocation.
5. Secure: In java, we don’t have pointers, and so we cannot access out-of-bound arrays i.e
it shows ArrayIndexOutOfBound Exception if we try to do so.
That’s why several security flaws like stack corruption or buffer overflow is impossible to
exploit in Java.
6. Distributed: We can create distributed applications using the java programming
language. Remote Method Invocation and Enterprise Java Beans are used for creating
distributed applications in java. The java programs can be easily distributed on one or
more systems that are connected to each other through an internet connection.
7. Multithreading: Java supports multithreading. It is a Java feature that allows
concurrent execution of two or more parts of a program for maximum utilization of
CPU.
8. Portable: As we know, java code written on one machine can be run on another
machine. The platform-independent feature of java in which its platform-independent
bytecode can be taken to any platform for execution makes java portable.
9. High Performance: Java architecture is defined in such a way that it reduces
overhead during the runtime and at some time java uses Just In Time (JIT) compiler
where the compiler compiles code on-demand basics where it only compiles those
methods that are called making applications to execute faster.
10. Dynamic flexibility: Java being completely object-oriented gives us the flexibility to
add classes, new methods to existing classes and even creating new classes through sub-
classes. Java even supports functions written in other languages such as C, C++ which
are referred to as native methods.
11. Sandbox Execution: Java programs run in a separate space that allows user to execute their
applications without affecting the underlying system with help of a bytecode verifier. Bytecode
verifier also provides additional security as it’s role is to check the code for any violation access.
12. Write Once Run Anywhere: As discussed above java application generates ‘.class’ file which
corresponds to our applications(program) but contains code in binary format. It provides
architecture-neutral ease as bytecode is not dependent on any machine architecture. It is the
primary reason java is used in the enterprising IT industry globally worldwide.
13. Power of compilation and interpretation: Most languages are designed with purpose either
they are compiled language or they are interpreted language. But java integrates arising enormous
power as Java compiler compiles the source code to bytecode and JVM executes this bytecode to
machine OS-dependent executable code.
Example
// Demo Java program
// Importing classes from packages Out Put:
import java.io.*; Welcome
// Main class
public class GFG {
// Main method
public static void main(String[] args)
{
// Print statement
System.out.println("Welcome");
}
}
Explanation:
1. Comments:
Comments are used for explaining code and are used in a similar manner in Java or
C or C++. Compilers ignore the comment entries and do not execute them.
Comments can be of a single line or multiple lines.
Single Line Comments:
Syntax:
// Single line comment
Multi-line Comments:
Syntax: /* Multi line comments*/
2. Import java.io*: This means all the classes of io package can be imported. Java io
package provides a set of input and output streams for reading and writing data to files or
other input and output streams for reading and writing data to files or other input or
output sources.
3. Class: The class contains the data and methods to be used in the program. Methods
define the behaviour of the class. Class GFG has only one method main in Java.
4. Static void main(); Static keyword tells us that this method is accessible without
instantiating the class.
5. void: keywords tell that this method will not return anything. The main() method is
the entry point of our application.
6. System.in: This is the standard input stream that is used to read characters from
the keyboard or any other standard input device.
7. System.out: This is the standard output stream that is used to produce the result of a
program on an output device like the computer screen.
8. println(): This method in Java is also used to display text on the console. It prints
the text on the console and the cursor moves to the start of the next line at the console.
The next printing takes place from the next line.
Java Naming Convention
•Java naming convention is a rule to follow as you decide what to name your identifiers
such as class, package, variable, constant, method, etc.
Advantage of Naming Conventions in Java
•Readability of Java program is very important.
•It indicates that less time is spent to figure out what the code does.
Naming Conventions of the Different
Identifiers
Identifiers Type Naming Rules Examples
Class It should start with the uppercase letter.
It should be a noun such as Color, Button,
System, Thread, etc.
Use appropriate words, instead of
acronyms.
public class Employee
{
//code snippet
}
Interface It should start with the uppercase letter.
It should be an adjective such as Runnable,
Remote, ActionListener.
Use appropriate words, instead of
acronyms.
interface Printable
{
//code snippet
}
Method It should start with lowercase letter.
It should be a verb such as main(), print(),
println().
If the name contains multiple words, start
it with a lowercase letter followed by an
uppercase letter such as
actionPerformed().
class Employee
{
// method
void draw()
{
//code snippet
}
}
Variable It should start with a lowercase letter such as
id, name.
It should not start with the special characters
like & (ampersand), $ (dollar), _ (underscore).
If the name contains multiple words, start it
with the lowercase letter followed by an
uppercase letter such as firstName, lastName.
class Employee
{
// variable
int id;
//code snippet
}
Package It should be a lowercase letter such as java,
lang.
If the name contains multiple words, it should
be separated by dots (.) such as java.util,
java.lang.
//package
package com.example.mypackage;
class Employee
{
//code snippet
}
Constant It should be in uppercase letters such as RED,
YELLOW.
If the name contains multiple words, it should
be separated by an underscore(_) such as
MAX_PRIORITY.
It may contain digits but not as the first letter.
class Employee
{
//constant
static final int MIN_AGE = 18;
//code snippet
}
CamelCase in Java naming conventions
•Java follows camel-case syntax for naming the class, interface, method, and variable.
•If the name is combined with two words, the second word will start with uppercase
letter always such as actionPerformed(), firstName, ActionEvent, ActionListener, etc.
Data Types in Java
Data types specify the different sizes and values that can be stored in the variable.
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, Interfaces,
and Arrays.
Java Primitive Data Types
In Java language, primitive data types are the building blocks of data manipulation.
These are the most basic data types available in Java Language.
There are 8 types of primitive data types:
•boolean data type
•byte data type
•char data type
•short data type
•int data type
•long data type
•float data type
•double data type
Integer Types:
Size and Range of Integer Types
Floating point Types
•Floating point type will hold numbers containing fractional parts such as 27.59 and -
1.375.
•There are two types of floating point
•The float types values are single precision numbers
•Double type values are double precision numbers
Type Size Minimum Value Maximum Value
Float 4 bytes 3.4e-038 1.7e+0.38
Double 8 bytes 3.4e-038 1.7e+308
CharacterType
•The character type assumes a size of two bytes
•But it can hold only a single character
Boolean Type
•Boolean types is used when we want to test a particular condition during the execution
of the program.
•There are only two values true or false
•Boolean type is denoted with the keyword Boolean and uses 1 bit of storage.
LITERALS
• Literal in Java is a synthetic representation of boolean, numeric, character, or string data.
• Literals are the constant values that appear directly in the program.
•It can be assigned directly to a variable. It is a means of expressing particular values in the
program, such as an integer variable named “/count is assigned an integer value in the following
statement.
int count = 0;
• A literal ‘0’ represents the value zero.
•Thus, a constant value assigned to the variable can be referred to as literal.
Literals in Java can be classified into six types, as below:
•Integral Literals
•Floating-point Literals
•Char Literals
•String Literals
•Boolean Literals
•Null Literals
1. Integral Literals
Integral literals are specified in four different ways, as follows:
Decimal: It has base ten, and digits from 0 to 9.
For example,
Int x = 108;
Octal: It has base eight and allows digits from 0 to 7. While assigning an octal literal in the Java code, a
number must have a prefix 0.
For example,
int x = 0745;
Hexadecimal:
It has base 16. Hexadecimal allows digits from 0 to 9, and characters from A to F. Even though Java is case
sensitive, and it also provides an exception for using either uppercase or lowercase characters in the code for
hexadecimal literals.
For example,
int x = 0X123Fadd;
Binary:
It can be specified in binary literals, that is 0 and 1 with a prefix 0b or 0B.
For example,
int x = 0b1011;
2. Floating-Point Literals
Floating-point literals can be expressed using only decimal fractions or as exponential notation. For
example,
decimalNumber = 89d;
decimalNumber = 3.14159e0;
decimalNumber = 1.0e-6D;
Floating-point literals can indicate a positive or negative value, leading + or – sign respectively. If not
specified, the value is always considered positive. It can be represented in the following formats:
-Integer digits (representing digits 0 through 9) followed by either a suffix or an exponent to distinguish it
from an integral literal.
-/integer digit.
- integer digit.integer digit
An optional exponent of the form might be as below:
-an optional exponent sign + or –
-the exponent indicator e or E
–integer digit representing the integer exponent value
An optional floating-point suffix might be as below:
Single precision (4 bytes) floating-point number indicating either for F
Double precision (8 bytes) floating-point number indicating d or D
3. Char Literals
• Character (Char) literals have the type char and are an unsigned integer primitive type.
•They are constant value character expressions in the Java program.
•These are sixteen-bit Unicode characters that range from 0 to 65535.
•Char literals are expressed as a single quote, a single closing quote, and the character in Java.
• Char literals are specified in four different ways, as given below:
•Single quote: Java literal is specified to a char data type as a single character enclosed in a single quote.
•For example,
•char ch = ‘a’;
Char Literal: Java literal is specified as an integer literal representing the Unicode value of a char. This integer can
be specified in octal, decimal, and hexadecimal, ranging from 0 to 65535.
For example,
char ch = 062;
Escape Sequence: Every escape char can be specified as char literal.
For example,
char ch = ‘n’;
Unicode Representation: Java literal is specified in Unicode representation ‘uzzz’, where zzzz are four
hexadecimal numbers.
For example,
char ch = ‘u0061’;
4. String Literals
•A sequence of (zero or more including Unicode characters) characters within double quotes is
referred to as string literals.
For example,
String s = “Hello”;
•String literals may not have unescaped line feed or newline characters, but the Java compiler
always evaluates compile-time expressions.
• Unicode escape sequences or special characters can be used within the string and character
literal as backlash characters to escape special characters, as shown in the table below:
JAVA PROGRAMMING-Unit I - Final PPT.pptx
5. Boolean Literals
Boolean literals allow only two values and thus are divided into two literals:
True: it represents a real boolean value
False: it represents a false boolean value
For example,
boolean b = true;
boolean d = false;
6. Null Literals
•Null literal is a particular literal in Java representing a null value. This value refers to no object. Java
throws NullPointerException.
• Null often describe the uninitialized state in the program. It is an error to attempt to dereference the null
value.
Operators in Java
Operator in Java is a symbol that is used to perform operations. For example: +, -, *, / etc.
There are many types of operators in Java which are given below:
•Unary Operator,
•Arithmetic Operator,
•Shift Operator,
•Relational Operator,
•Bitwise Operator,
•Logical Operator,
•Ternary Operator and
•Assignment Operator.
Operator Type Category Precedence
Unary postfix expr++ expr--
prefix ++expr --expr +expr -expr ~ !
Arithmetic multiplicative * / %
additive + -
Shift shift << >> >>>
Relational comparison < > <= >= instanceof
equality == !=
Bitwise bitwise AND &
bitwise exclusive OR ^
bitwise inclusive OR |
Logical logical AND &&
logical OR ||
Ternary ternary ? :
Assignment assignment = += -= *= /= %= &= ^= |= <<= >>=
>>>=
Java Unary Operator
The Java unary operators require only one operand. Unary operators are used to
perform various operations i.e.:
•incrementing/decrementing a value by one
•negating an expression
•inverting the value of a boolean
Java Unary Operator Example: ++
and --
1.public class OperatorExample{
2.public static void main(String args[]){
3.int x=10;
4.System.out.println(x++);//10 (11)
5.System.out.println(++x);//12
6.System.out.println(x--);//12 (11)
7.System.out.println(--x);//10
8.}}
Output:
10
12
12
10
Java Unary Operator Example 2: ++
and --
1.public class OperatorExample{
2.public static void main(String args[]){ Output:
3.int a=10; 22
4.int b=10; 21
5.System.out.println(a++ + ++a);//10+12=22
6.System.out.println(b++ + b++);//10+11=21
7.
8.}}
Java Unary Operator Example: ~
and !
1.public class OperatorExample{ Output:
2.public static void main(String args[]){ -11
3.int a=10; 9
4.int b=-10; false
5.boolean c=true; true
6.boolean d=false;
7.System.out.println(~a);//-11 (minus of total positive value which starts from 0)
8.System.out.println(~b);//9 (positive of total minus, positive starts from 0)
9.System.out.println(!c);//false (opposite of boolean value)
10.System.out.println(!d);//true
11.}}
Java Arithmetic Operators
Java arithmetic operators are used to perform addition, subtraction, multiplication,
and division. They act as basic mathematical operations.
Java Arithmetic Operator Example
1.public class OperatorExample{ Output:
2.public static void main(String args[]){ 15
3.int a=10; 5
4.int b=5; 50
5.System.out.println(a+b);//15 2
6.System.out.println(a-b);//5 0
7.System.out.println(a*b);//50
8.System.out.println(a/b);//2
9.System.out.println(a%b);//0
10.}}
Java Arithmetic Operator Example: Expression
1.public class OperatorExample{
2.public static void main(String args[]){
3.System.out.println(10*10/5+3-1*4/2);
4.}}
Output:
21
Java Left Shift Operator
The Java left shift operator << is used to shift all of the bits in a value to the
left side of a specified number of times.
Java Left Shift Operator Example
1.public class OperatorExample{
2.public static void main(String args[]){
3.System.out.println(10<<2);//10*2^2=10*4=40
4.System.out.println(10<<3);//10*2^3=10*8=80
5.System.out.println(20<<2);//20*2^2=20*4=80
6.System.out.println(15<<4);//15*2^4=15*16=240
7.}}
Output:
40
80
80
240
Java Right Shift Operator
The Java right shift operator >> is used to move the value of the left operand to
right by the number of bits specified by the right operand.
Java Right Shift Operator Example
1.public OperatorExample{
2.public static void main(String args[]){
3.System.out.println(10>>2);//10/2^2=10/4=2
4.System.out.println(20>>2);//20/2^2=20/4=5
5.System.out.println(20>>3);//20/2^3=20/8=2
6.}}
Output:
2
5
2
Java Shift Operator Example: >> vs
>>>
1.public class OperatorExample{
2.public static void main(String args[]){
3. //For positive number, >> and >>> works same
4. System.out.println(20>>2);
5. System.out.println(20>>>2);
6. //For negative number, >>> changes parity bit (MSB) to 0
7. System.out.println(-20>>2);
8. System.out.println(-20>>>2);
9.}}
Output:
5
5
-5
1073741819
Java AND Operator Example: Logical
&& and Bitwise &
•The logical && operator doesn't check the second condition if the first condition is
false. It checks the second condition only if the first one is true.
•The bitwise & operator always checks both conditions whether first condition is true
or false.
1.public class OperatorExample{ Output:
2.public static void main(String args[]){ false
3.int a=10; false
4.int b=5;
5.int c=20;
6.System.out.println(a<b&&a<c);//false && true = false
7.System.out.println(a<b&a<c);//false & true = false
8.}}
Java AND Operator Example: Logical
&& vs Bitwise &
1.public class OperatorExample{
2.public static void main(String args[]){
3.int a=10;
4.int b=5;
5.int c=20;
6.System.out.println(a<b&&a++<c);//false && true = false
7.System.out.println(a);//10 because second condition is not checked
8.System.out.println(a<b&a++<c);//false && true = false
9.System.out.println(a);//11 because second condition is checked
10.}}
Output:
False
10
False
11
Java OR Operator Example: Logical ||
and Bitwise |
•The logical || operator doesn't check the second condition if the first condition is true.
It checks the second condition only if the first one is false.
The bitwise | operator always checks both conditions whether first condition is true or
false.
1.public class OperatorExample{
2.public static void main(String args[]){
3.int a=10;
4.int b=5;
5.int c=20;
6.System.out.println(a>b||a<c);//true || true = true
7.System.out.println(a>b|a<c);//true | true = true
8.//|| vs |
9.System.out.println(a>b||a++<c);//true || true = true
10.System.out.println(a);//10 because second condition is not checked
11.System.out.println(a>b|a++<c);//true | true = true
12.System.out.println(a);//11 because second condition is checked
13.}}
Output:
True
True
True
10
True
11
Java Ternary Operator
Java ternary operator is the only conditional operator that takes three operands. Java Ternary operator is used as one
line replacement for if-then-else statement and used a lot in Java programming. It is the only conditional
operator which takes three operands.
Java Ternary Operator Example
1.public class OperatorExample{ Output:
2.public static void main(String args[]){ 2
3.int a=2;
4.int b=5;
5.int min=(a<b)?a:b;
6.System.out.println(min);
7.}}
Another Example:
1.public class OperatorExample{ Output:
2.public static void main(String args[]){ 5
3.int a=10;
4.int b=5;
5.int min=(a<b)?a:b;
6.System.out.println(min);
7.}}
Java Assignment Operator
Java assignment operator is one of the most common operators. It is used to assign
the value on its right to the operand on its left.
Java Assignment Operator Example
1.public class OperatorExample{ Output:
2.public static void main(String args[]){ 14
3.int a=10; 16
4.int b=20;
5.a+=4;//a=a+4 (a=10+4)
6.b-=4;//b=b-4 (b=20-4)
7.System.out.println(a);
8.System.out.println(b);
9.}}
Control Statements in Java
•Java compiler executes the code from top to bottom.
•The statements in the code are executed according to the order in which they appear.
• However, Java provides statements that can be used to control the flow of Java code.
•Such statements are called control flow statements.
•It is one of the fundamental features of Java, which provides a smooth flow of
program.
Java provides three types of control flow statements.
1.Decision Making statements
1. if statements
2. switch statement
2.Loop statements
1. do while loop
2. while loop
3. for loop
4. for-each loop
3.Jump statements
1. break statement
2. continue statement
Decision-Making statements:
•As the name suggests, decision-making statements decide which statement to execute
and when.
•Decision-making statements evaluate the Boolean expression and control the program
flow depending upon the result of the condition provided.
• There are two types of decision-making statements in Java, i.e., If statement and
switch statement.
If Statement:
In Java, the "if" statement is used to evaluate a condition. The control of the program is diverted
depending upon the specific condition. The condition of the If statement gives a Boolean value,
either true or false.
Syntax: if (test expression)
In Java, there are four types of if-statements given below.
1.Simple if statement
2.if-else statement
3.if-else-if ladder
4.Nested if-statement
Simple if statement:
It is the most basic statement among all control flow statements in Java. It evaluates a Boolean
expression and enables the program to enter a block of code if the expression evaluates to true.
Syntax of if statement is given below.
1.if(condition) {
2.statement 1; //executes when condition is true
3.}
4.}
Consider the following example in which we have used the if statement in the java code.
Student.java
Student.java Output:
1.public class Student { x+y is greater than 20
2.public static void main(String[] args) {
3.int x = 10;
4.int y = 12;
5.if(x+y > 20) {
6.System.out.println("x + y is greater than 20");
7.}
8.}
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:
1.if(condition) {
2.statement 1; //executes when condition is true
3.}
4.else{
5.statement 2; //executes when condition is false
6.}
Consider the following example.
Student.java Output:
1.public class Student { x+y is greater than 20
2.public static void main(String[] args) {
3.int x = 10;
4.int y = 12;
5.if(x+y < 10) {
6.System.out.println("x + y is less than 10");
7.} else {
8.System.out.println("x + y is greater than 20");
9.}
10.}
11.}
if-else-if ladder:
The if-else-if statement contains the if-statement followed by multiple else-if statements. In other
words, we can say that it is the chain of if-else statements that create a decision tree where the
program may enter in the block of code where the condition is true. We can also define an else
statement at the end of the chain.
Syntax of if-else-if statement is given below.
1.if(condition 1) {
2.statement 1; //executes when condition 1 is true
3.}
4.else if(condition 2) {
5.statement 2; //executes when condition 2 is true
6.}
7.else {
8.statement 2; //executes when all the conditions are false
9.}
1.public class Student { Output:
2.public static void main(String[] args) { Delhi
3.String city = "Delhi";
4.if(city == "Meerut") {
5.System.out.println("city is meerut");
6.}else if (city == "Noida") {
7.System.out.println("city is noida");
8.}else if(city == "Agra") {
9.System.out.println("city is agra");
10.}else {
11.System.out.println(city);
12.}
13.}
14.}
Nested if-statement
In nested if-statements, the if statement can contain a if or if-else statement
inside another if or else-if statement.
Syntax of Nested if-statement is given below.
1.if(condition 1) {
2.statement 1; //executes when condition 1 is true
3.if(condition 2) {
4.statement 2; //executes when condition 2 is true
5.}
6.else{
7.statement 2; //executes when condition 2 is false
8.}
9.}
1.public class Student { Output:
2.public static void main(String[] args) { Delhi
3.String address = "Delhi, India";
4.if(address.endsWith("India")) {
5.if(address.contains("Meerut")) {
6.System.out.println("Your city is Meerut");
7.}else if(address.contains("Noida")) {
8.System.out.println("Your city is Noida");
9.}else {
10.System.out.println(address.split(",")[0]);
11.}
12.}else {
13.System.out.println("You are not living in India");
14.}
15.}
16.}
Switch Statement:
In Java, Switch statements are similar to if-else-if statements. The switch statement
contains multiple blocks of code called cases and a single case is executed based on
the variable which is being switched. The switch statement is easier to use instead of
if-else-if statements. It also enhances the readability of the program.
Points to be noted about switch statement:
•The case variables can be int, short, byte, char, or enumeration. String type is also
supported since version 7 of Java
•Cases cannot be duplicate
•Default statement is executed when any of the case doesn't match the value of expression.
It is optional.
•Break statement terminates the switch block when the condition is satisfied.
It is optional, if not used, next case is executed.
•While using switch statements, we must notice that the case expression will be of the
same type as the variable. However, it will also be a constant value.
The syntax to use the switch statement is given below.
1.switch (expression){
2. case value1:
3. statement1;
4. break;
5. .
6. .
7. .
8. case valueN:
9. statementN;
10. break;
11. default:
12. default statement;
13.}
1.public class Student implements Cloneable {
2.public static void main(String[] args) { Output:
3.int num = 2; 2
4.switch (num){
5.case 0:
6.System.out.println("number is 0");
7.break;
8.case 1:
9.System.out.println("number is 1");
10.break;
11.default:
12.System.out.println(num);
13.}
14.}
15.}
•While using switch statements, we must notice that the case expression will be of the
same type as the variable.
• However, it will also be a constant value.
•The switch permits only int, string, and Enum type variables to be used.
Loop Statements
•Loop statements are used to execute the set of instructions in a repeated order. The
execution of the set of instructions depends upon a particular condition.
In Java, we have three types of loops that execute similarly. However, there are
differences in their syntax and condition checking time.
1.for loop
2.while loop
3.do-while loop
For Loop
•In Java, for loop is similar to C and C++.
•It enables us to initialize the loop variable, check the condition, and
increment/decrement in a single line of code. We use the for loop only when we
exactly know the number of times, we want to execute the block of code.
1.for(initialization, condition, increment/decrement) {
2.//block of statements
3.}
The flow chart for the for-loop is given below.
1.public class Calculation {
2.public static void main(String[] args) {
3.// TODO Auto-generated method stub
4.int sum = 0;
5.for(int j = 1; j<=10; j++) {
6.sum = sum + j;
7.}
8.System.out.println("The sum of first 10 natural numbers is " + sum);
9.}
10.}
Output:
The sum of first 10 natural numbers is 55
for-each loop
•Java provides an enhanced for loop to traverse the data structures like array or collection.
•In the for-each loop, we don't need to update the loop variable.
•The syntax to use the for-each loop in java is given below.
1.for(data_type var : array_name/collection_name){
2.//statements
3.}
1.public class Calculation {
2.public static void main(String[] args) {
3.// TODO Auto-generated method
4.String[] names = {"Java","C","C++","Python","JavaScript"};
5.System.out.println("Printing the content of the array names:n");
6.for(String name:names) {
7.System.out.println(name);
8.}
9.}
10.}
Output:
Printing the array of content names:
Java
C
C++
Python
JavaScript
while loop
•The while loop is also used to iterate over the number of statements multiple times. However, if
we don't know the number of iterations in advance, it is recommended to use a while loop.
•Unlike for loop, the initialization and increment/decrement doesn't take place inside the loop
statement in while loop.
•It is also known as the entry-controlled loop since the condition is checked at the start of the loop.
If the condition is true, then the loop body will be executed; otherwise, the statements after the
loop will be executed.
The syntax of the while loop:
while(condition){
1.//looping statements
2.}
1.public class Calculation {
2.public static void main(String[] args) {
3.// TODO Auto-generated method stub
4.int i = 0;
5.System.out.println("Printing the list of first 10 even numbers n");
6.while(i<=10) {
7.System.out.println(i);
8.i = i + 2;
9.}
10.}
11.}
Printing the list of first 10 even numbers
0
2
4
6
8
10
do-while loop
•The do-while loop checks the condition at the end of the loop after executing the loop
statements.
•When the number of iteration is not known and we have to execute the loop at least
once, we can use do-while loop.
•It is also known as the exit-controlled loop since the condition is not checked in
advance. The syntax of the do-while loop is given below.
1.do
2.{
3.//statements
4.} while (condition);
The flow chart of do-while loop
1.public class Calculation {
2.public static void main(String[] args) {
3.// TODO Auto-generated method stub
4.int i = 0;
5.System.out.println("Printing the list of first 10 even numbers n");
6.do {
7.System.out.println(i);
8.i = i + 2;
9.}while(i<=10);
10.}
11.}
Printing the list of first 10 even numbers
0
2
4
6
8
10
Jump Statements
•Jump statements are used to transfer the control of the program to the specific
statements.
•In other words, jump statements transfer the execution control to the other part of the
program.
•There are two types of jump statements in Java, i.e., break and continue.
Break Statement
•As the name suggests, the break statement is used to break the current flow of the
program and transfer the control to the next statement outside a loop or switch
statement.
•However, it breaks only the inner loop in the case of the nested loop.
•The break statement cannot be used independently in the Java program, i.e., it can only
be written inside the loop or switch statement.
The break statement example with for loop
1.public class BreakExample {
2.public static void main(String[] args) {
3.// TODO Auto-generated method stub
4.for(int i = 0; i<= 10; i++) {
5.System.out.println(i);
6.if(i==6) {
7.break;
8.}
9.}
10.}
11.}
Output:
0
1
2
3
4
5
6
break statement example with labeled for loop
1.public class Calculation {
2.public static void main(String[] args) { Output:
3.// TODO Auto-generated method stub 0
4.a: 1
5.for(int i = 0; i<= 10; i++) { 2
6.b: 3
7.for(int j = 0; j<=15;j++) { 4
8.c: 5
9.for (int k = 0; k<=20; k++) {
10.System.out.println(k);
11.if(k==5) {
12.break a;
13.}
14.}
15.}
16.}
Continue Statement
Unlike break statement, the continue statement doesn't break the loop, whereas, it
skips the specific part of the loop and jumps to the next iteration of the loop
immediately.
1.public class ContinueExample {
2.
3.public static void main(String[] args) {
4.// TODO Auto-generated method stub
5.for(int i = 0; i<= 2; i++) {
6.for (int j = i; j<=5; j++) {
7.if(j == 4) {
8.continue;
9.}
10.System.out.println(j);
11.}
12.}
13.}
14.}
Output:
0
1
2
3
5
1
2
3
5
2
3
5
Classes and Objects
•In object-oriented programming technique, we design a program using objects and
classes.
•An object in Java is the physical as well as a logical entity, whereas, a class in Java is a
logical entity only.
Object in Java
•An entity that has state and behavior is known as an object e.g., chair, bike, marker, pen,
table, car, etc.
•It can be physical or logical (tangible and intangible). The example of an intangible
object is the banking system.
An object has three characteristics:
State: represents the data (value) of an object.
•Behavior: represents the behavior (functionality) of an object such as deposit, withdraw,
etc.
•Identity: An object identity is typically implemented via a unique ID. The value of the ID
is not visible to the external user. However, it is used internally by the JVM to identify
each object uniquely.
• ForExample,Penisanobject.ItsnameisReynolds;coloriswhite,knownasitsstate.Itisusedtowrite,sowritingis
itsbehavior.
Anobjectisaninstanceofaclass.Aclassisatemplateorblueprintfromwhichobjectsarecreated.So,anobjectis
theinstanceofaclass.
Object Definitions:
•An object is a real-world entity.
•An object is a runtime entity.
•The object is an entity which has state and behavior.
•The object is an instance of a class.
Class in Java
A class is a group of objects which have common properties. It is a template or
blueprint from which objects are created. It is a logical entity. It can't be physical.
A class in Java can contain:
•Fields
•Methods
•Constructors
•Blocks
•Nested class and interface
Syntax to declare a class:
1.class <class_name>{
2. field;
3. method;
4.}
Instance variable in Java
•A variable which is created inside the class but outside the method is known as an instance
variable.
• Instance variable doesn't get memory at compile time. It gets memory at runtime when an object
or instance is created. That is why it is known as an instance variable.
Method in Java
In Java, a method is like a function which is used to expose the behavior of an object.
Advantage of Method
•Code Reusability
•Code Optimization
New keyword in Java
The new keyword is used to allocate memory at runtime. All objects get memory in Heap memory
area.
Object and Class Example: main within the class
In this example, we have created a Student class which has two data members id and name. We are
creating the object of the Student class by new keyword and printing the object's value.
Here, we are creating a main() method inside the class.
1.//Java Program to illustrate how to define a class and fields
2.//Defining a Student class. Output:
3.class Student{ 0
4. //defining fields null
5. int id;//field or data member or instance variable
6. String name;
7. //creating main method inside the Student class
8. public static void main(String args[]){
9. //Creating an object or instance
10. Student s1=new Student();//creating an object of Student
11. //Printing values of the object
12. System.out.println(s1.id);//accessing member through reference variable
13. System.out.println(s1.name);
14. }
15.}
Object and Class Example: main outside the class
•In real time development, we create classes and use it from another class. It is a better
approach than previous one. Let's see a simple example, where we are having main()
method in another class.
•We can have multiple classes in different Java files or single Java file. If you define
multiple classes in a single Java source file, it is a good idea to save the file name with
the class name which has main() method.
1.//Java Program to demonstrate having the main method in
2.//another class Output:
3.//Creating Student class. 0
4.class Student{ null
5. int id;
6. String name;
7.}
8.//Creating another class TestStudent1 which contains the main method
9.class TestStudent1{
10. public static void main(String args[]){
11. Student s1=new Student();
12. System.out.println(s1.id);
13. System.out.println(s1.name);
14. }
15.}
3 Ways to initialize object
There are 3 ways to initialize object in Java.
1.By reference variable
2.By method
3.By constructor
1) Object and Class Example: Initialization through reference
Initializing an object means storing data into the object. Let's see a simple example
where we are going to initialize the object through a reference variable.
1.class Student{ Output:
2. int id; 101 Sonoo
3. String name;
4.}
5.class TestStudent2{
6. public static void main(String args[]){
7. Student s1=new Student();
8. s1.id=101;
9. s1.name="Sonoo";
10. System.out.println(s1.id+" "+s1.name);//printing members with a white spac
e
11. }
12.}
We can also create multiple objects and store information in it through reference variable.
1.class Student{ Output:
2. int id; 101 Sonoo
3. String name; 102 Amit
4.}
5.class TestStudent3{
6. public static void main(String args[]){
7. //Creating objects
8. Student s1=new Student();
9. Student s2=new Student();
10. //Initializing objects
11. s1.id=101;
12. s1.name="Sonoo";
13. s2.id=102;
14. s2.name="Amit";
15. //Printing data
16. System.out.println(s1.id+" "+s1.name);
17. System.out.println(s2.id+" "+s2.name);
18. }
19.}
2) Object and Class Example: Initialization through method
•In this example, we are creating the two objects of Student class and initializing the
value to these objects by invoking the insertRecord method.
•Here, we are displaying the state (data) of the objects by invoking the
displayInformation() method.
1.class Student{
2. int rollno; Output
3. String name; 111 Karan
4. void insertRecord(int r, String n){ 222 Aryan
5. rollno=r;
6. name=n;
7. }
8. void displayInformation(){System.out.println(rollno+" "+name);}
9.}
10.class TestStudent4{
11. public static void main(String args[]){
12. Student s1=new Student();
13. Student s2=new Student();
14. s1.insertRecord(111,"Karan");
15. s2.insertRecord(222,"Aryan");
16. s1.displayInformation();
17. s2.displayInformation();
18. }
19.}
•As you can see in the above figure, object gets the memory in heap memory area.
•The reference variable refers to the object allocated in the heap memory area.
• Here, s1 and s2 both are reference variables that refer to the objects allocated in memory.
3)ObjectandClassExample:Initializationthroughaconstructor
1.class Employee{ Output:
2. int id; 101 Ajeet 45000.0
3. String name; 102 Irfan 25000.0
4. float salary; 103 nakul 55000.0
5. void insert(int i, String n, float s) {
6. id=i;
7. name=n;
8. salary=s;
9. }
10. void display(){System.out.println(id+" "+name+" "+salary);}
11.}
12.public class TestEmployee {
13.public static void main(String[] args) {
14. Employee e1=new Employee();
15. Employee e2=new Employee();
16. Employee e3=new Employee();
17. e1.insert(101,"ajeet",45000);
18. e2.insert(102,"irfan",25000);
19. e3.insert(103,"nakul",55000);
20. e1.display();
21. e2.display();
22. e3.display();
23.}
JAVA PROGRAMMING-Unit I - Final PPT.pptx
Anonymous object
Anonymous simply means nameless. An object which has no reference is known
as an anonymous object. It can be used at the time of object creation only.
If you have to use an object only once, an anonymous object is a good approach.
For example:
1.new Calculation();//anonymous object
Calling method through a reference:
1.Calculation c=new Calculation();
2.c.fact(5);
Calling method through an anonymous object
1.new Calculation().fact(5);
Let's see the full example of an anonymous object in Java.
1.class Calculation{ Output:
2. void fact(int n){ factorial is 120
3. int fact=1;
4. for(int i=1;i<=n;i++){
5. fact=fact*i;
6. }
7. System.out.println("factorial is "+fact);
8.}
9.public static void main(String args[]){
10. new Calculation().fact(5);//calling method with anonymous object
11.}
12.}
Creating multiple objects by one type only
We can create multiple objects by one type only as we do in case of primitives.
Initialization of primitive variables:
1.int a=10, b=20;
Initialization of reference variables:
1.Rectangle r1=new Rectangle(), r2=new Rectangle();//creating two objects
1.//Java Program to illustrate the use of Rectangle class which
2.//has length and width data members Output:
3.class Rectangle{ 55
4. int length; 45
5. int width;
6. void insert(int l,int w){
7. length=l;
8. width=w;
9. }
10. void calculateArea(){System.out.println(length*width);}
11.}
12.class TestRectangle2{
13. public static void main(String args[]){
14. Rectangle r1=new Rectangle(),r2=new Rectangle();//creating two objects
15. r1.insert(11,5);
16. r2.insert(3,15);
17. r1.calculateArea();
18. r2.calculateArea();
19.}
20.}
Instance Variables
In any programming language, the program needs identifiers for storing different values
that can be used throughout the program. These identifiers are variables.
Variable in Java
•A variable is a name assigned to a value that is stored inside the system memory. The value
can be updated during the program execution.
•In Java programming, the variables used for the program need to declare them first.
•The variable is declared using a data type followed by the identifier name. The variable can
be initialized at the time of declaration or it can be assigned a value taken from the user
during the program execution.
•There are basically three types of variables in Java,
• Java Local variable
• Java Instance variable
• Java Static variable / Java class variable
Instance Variable
•The variables that are declared inside the class but outside the scope of any method are
called instance variables in Java.
•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.
•Instance variables of different types have default values that are specified in the next point.
Features
1.To use an instance variable an object of the class must be created.
2.An instance variable is destroyed when the object it is associated with is destroyed.
3.An instance variable does not compulsory need to be initialized.
4.Instance variables are accessible inside the same class that declares them.
Limitations of Instance Variable
1.It cannot be declared static, abstract, striftp, synchronized, and native.
2.It can be declared final and transient.
3.It can be of any of the four access modifiers available in Java (private, public, protected,
and default).
Default values of Instance Variables
Instance variable type Default values
boolean false
byte (byte) 0
short (short) 0
int 0
double 0.0d
float 0.0
long 0L
Object null
char u0000
Using Instance Variable in Java Program
1.public class Studentsrecords
2.{
3. /* declaration of instance variables. */
4. public String name; //public instance
5. String division; //default instance
6. private int age; //private instance
7. /* Constructor that initialize an instance variable. */
8. public Studentsrecords(String sname)
9. {
10. name = sname;
11. }
12. /* Method to intialize an instance variable. */
13. public void printstud()
1. {
2. System.out.println("Student Name: " + name );
3. System.out.println("Student Division: " + division);
4. System.out.println("Student Age: " + age);
5. }
6. /* Driver Code */
7. public static void main(String args[])
8. {
9. Studentsrecords s = new Studentsrecords("Monica");
10. s.setAge(14);
11. s.setDiv("B");
12. s.printstud();
13. }
14.}
Output:
Student Name: Monica
Student Division: B
Student Age: 14
•The above Java program initializes the instance variables by declaring an object of the
class Studentsrecords.
•The values of instance variables name, division, and age are displayed
using printstud() method.
Difference between Local, Instance and Static variables in
Java
Sr.
No.
Local variables Instance variables Static variables
1. Variables declared within a
method are local variables.
An instance variable is declared inside a
class but outside of any method or block.
Static variables are declared inside a class but
outside of a method starting with a keyword
static.
2. The scope of the local variable is
limited to the method it is
declared inside.
An instance variable is accessible
throughout the class.
The static variable is accessible throughout the
class.
3. A local variable starts its lifetime
when the method is invoked.
The object associated with the instance
variable decides its lifetime.
The static variable has the same lifetime as the
program.
4. Local variable is accessible to all
the objects of the class.
Instance variable has different copies for
different objects.
Static variables only have one single copy of
the entire class.
5. Used to store values that are
required for a particular method.
Used to store values that are needed to be
accessed by different methods of the class.
Used for storing constants.
Set Methods in Java
•The set is an interface available in the java.util package.
•The set interface extends the Collection interface.
• An unordered collection or list in which duplicates are not allowed is referred to as
a collection interface.
•The set interface is used to create the mathematical set. The set interface use collection
interface's methods to avoid the insertion of the same elements.
•SortedSet and NavigableSet are two interfaces that extend the set implementation.
Classes that implement Set
Since Set is an interface, we cannot create objects from it.
In order to use functionalities of the Set interface, we can use these classes:
•Hashset
•LinkedHashSet
•EnumSet
•TreeSet
These classes are defined in the Collections framework and implement
the Set interface.
JAVA PROGRAMMING-Unit I - Final PPT.pptx
Interfacesthat extendSet
TheSet interfaceisalsoextendedbythesesubinterfaces:
SortedSet
NavigableSet
•In the above diagram, the NavigableSet and SortedSet are both the interfaces.
The NavigableSet extends the SortedSet, so it will not retain the insertion order and
store the data in a sorted way.
1.import java.util.*;
2.public class setExample{
3. public static void main(String[] args)
4. {
5. // creating LinkedHashSet using the Set
6. Set<String> data = new LinkedHashSet<String>();
7. data.add("JavaTpoint");
8. data.add("Set");
9. data.add("Example");
10. data.add("Set");
11. System.out.println(data);
12. }
13.}
Note: Throughout the section, we have compiled the program with file name and run
the program with class name. Because the file name and the class name are different.
Operations on the set interface
On the Set, we can perform all the basic mathematical operations like intersection, union and
difference.Suppose, we have two sets, i.e., set1 = [22, 45, 33, 66, 55, 34, 77] and set2 = [33, 2,
83, 45, 3, 12, 55]. We can perform the following operation on the Set:
•Intersection: The intersection operation returns all those elements which are present in both
the set. The intersection of set1 and set2 will be [33, 45, 55].
•Union: The union operation returns all the elements of set1 and set2 in a single set, and that set
can either be set1 or set2. The union of set1 and set2 will be [2, 3, 12, 22, 33, 34, 45, 55, 66, 77,
83].
•Difference: The difference operation deletes the values from the set which are present in
another set. The difference of the set1 and set2 will be [66, 34, 22, 77].
•In set, addAll() method is used to perform the union, retainAll() method is used to
perform the intersection and removeAll() method is used to perform difference.
•Let's take an example to understand how these methods are used to perform the
intersection, union, and difference operations.
1.import java.util.*;
2.public class SetOperations
3.{
4. public static void main(String args[])
5. {
6. Integer[] A = {22, 45,33, 66, 55, 34, 77};
7. Integer[] B = {33, 2, 83, 45, 3, 12, 55};
8. Set<Integer> set1 = new HashSet<Integer>();
9. set1.addAll(Arrays.asList(A));
10. Set<Integer> set2 = new HashSet<Integer>();
11. set2.addAll(Arrays.asList(B));
12.
13. // Finding Union of set1 and set2
14. Set<Integer> union_data = new HashSet<Integer>(set1);
15. union_data.addAll(set2);
16. System.out.print("Union of set1 and set2 is:");
17. System.out.println(union_data);
18. // Finding Intersection of set1 and set2
19. Set<Integer> intersection_data = new HashSet<Integer>(set1);
1. intersection_data.retainAll(set2);
2. System.out.print("Intersection of set1 and set2 is:");
3. System.out.println(intersection_data);
4. // Finding Difference of set1 and set2
5. Set<Integer> difference_data = new HashSet<Integer>(set1);
6. difference_data.removeAll(set2);
7. System.out.print("Difference of set1 and set2 is:");
8. System.out.println(difference_data);
9. }
10.}
Initializing objects with Constructors
•A Java class defines the data (attributes) and behavior (methods) of a set of similar
objects.
•Each class has a special type of method called a constructor that is used to initialize the
attributes in a newly created object.
•A constructor is a special method that has the same name as the class and is used to
initialize attributes of a new object.
•A new object is created with new keyword followed by the class name.
•Object initialization means, initializing class fields. Suppose there is a Person class having a
field “name”.
•When we create objects like Peter , John and Linda etc. of the class Person, the name field
should contain their name.
•We can initialize class fields in a constructor of a class. In the constructor ,we can write
hard code value like name =”Peter”; as simple as that.
•Also, earthier you hard code values of all fields or receive values in the constructor
parameter and initialize.
• First lets see the output of a simple class when we don’t initialize an object of the class.
Below is the class Person having a field name, that is not initialized in constructor.
class Person { Output:
String name; Person:null
// Constructor
public Person() {
}
public String getName() {
return this.name;
}
}
public class TestPerson {
public static void main(String[] args) {
Person john = new Person();
john.getName();
System.out.println("Person:" + john.getName());
} }
Now, see the example, where we have initialized field “name” in the constructor of the Person class
as “this.name = “Peter”;”
Output will be now as : Person:Peter
class Person {
String name;
// Constructor
public Person() {
this.name = "Peter";
}
public String getName() {
return this.name;
}
}
Object Initialization through Parameterized Constructor
•We need to create a parameterized constructor in the class that can accept arguments.
The class fields will be initialized with these parameters in the constructor.
•When you create an object with arguments, the class constructor in java program will
be automatically called and fields will be initialized.
class Person {
// properties of a person
private String name;
private int Age;
private String gender;
// Constructor : initialize all class fields
public Person(String name, int age, String gender) {
this.name = name;
this.Age = age;
this.gender = gender;
}
public String getName() {
return name;
}
public int getAge() {
return Age;
}
public String getGender() {
return gender;
}
}
/* * Test objects initialization. */
public class Sample {
public static void main(String[] args) {
Person scott = new Person("Scott", 30, "M");
System.out.println("Name: " + scott.getName());
System.out.println("Age: " + scott.getAge());
System.out.println("Gender: " + scott.getName());
}
}
Output:
Name: Scott
Age: 30
Gender: Scott

More Related Content

What's hot (20)

PPTX
Google android Activity lifecycle
University of Potsdam
 
PPTX
Presentation on Core java
mahir jain
 
PPTX
Android studio ppt
Swapanpreet Kaur
 
PPTX
Introduction to android
zeelpatel0504
 
PPTX
System Software and Programming.pptx
VanshikaPatel41
 
PDF
Flutter tutorial for Beginner Step by Step
Chandramouli Biyyala
 
PPTX
Mobile application development ppt
tirupathinews
 
PDF
Introduction to the Dart language
Jana Moudrá
 
PDF
Android Data Persistence
Jussi Pohjolainen
 
PDF
Location-Based Services on Android
Jomar Tigcal
 
PPTX
Operating system 32 logical versus physical address
Vaibhav Khanna
 
PDF
ADO.NET difference faqs compiled- 1
Umar Ali
 
PPTX
Restful web services ppt
OECLIB Odisha Electronics Control Library
 
PPTX
JSON: The Basics
Jeff Fox
 
PPTX
Quick introduction to zeplin
Axilis
 
PPTX
Swift programming language
Nijo Job
 
PPTX
HTML Introduction, HTML History, HTML Uses, HTML benifits
Pro Guide
 
PPT
Disk scheduling
J.T.A.JONES
 
PPTX
What and Why Flutter? What is a Widget in Flutter?
MohammadHussain595488
 
PPTX
VIRTUAL MEMORY
Kamran Ashraf
 
Google android Activity lifecycle
University of Potsdam
 
Presentation on Core java
mahir jain
 
Android studio ppt
Swapanpreet Kaur
 
Introduction to android
zeelpatel0504
 
System Software and Programming.pptx
VanshikaPatel41
 
Flutter tutorial for Beginner Step by Step
Chandramouli Biyyala
 
Mobile application development ppt
tirupathinews
 
Introduction to the Dart language
Jana Moudrá
 
Android Data Persistence
Jussi Pohjolainen
 
Location-Based Services on Android
Jomar Tigcal
 
Operating system 32 logical versus physical address
Vaibhav Khanna
 
ADO.NET difference faqs compiled- 1
Umar Ali
 
JSON: The Basics
Jeff Fox
 
Quick introduction to zeplin
Axilis
 
Swift programming language
Nijo Job
 
HTML Introduction, HTML History, HTML Uses, HTML benifits
Pro Guide
 
Disk scheduling
J.T.A.JONES
 
What and Why Flutter? What is a Widget in Flutter?
MohammadHussain595488
 
VIRTUAL MEMORY
Kamran Ashraf
 

Similar to JAVA PROGRAMMING-Unit I - Final PPT.pptx (20)

PPTX
What is Java, JDK, JVM, Introduction to Java.pptx
kumarsuneel3997
 
PPTX
Java
seenak
 
PPTX
1 .java basic
Indu Sharma Bhardwaj
 
PDF
TechSearchWeb.pdf
TechSearchWeb
 
PDF
Technology Tutorial.pdf
TechSearchWeb
 
PDF
Java Basic.pdf
TechSearchWeb
 
PPTX
Module1_htryjtjhkrhdegtfhsfhrdgfhpart1.pptx
aashrithsai7dkm
 
PDF
what is java.pdf
XanGwaps
 
PPTX
Java technology is widely used currently. Let's start learning of java from b...
aliblackcat76
 
PPTX
Java
Harry Potter
 
PPTX
Java
James Wong
 
PPTX
Java
Tony Nguyen
 
PPTX
Java
Fraboni Ec
 
PPTX
Java
Luis Goldster
 
PPTX
Java
Young Alista
 
DOCX
Srgoc java
Gaurav Singh
 
PPTX
Chapter 1 (1).pptx
krishnashah277578
 
PPTX
JAVA PROGRAM CONSTRUCTS OR LANGUAGE BASICS.pptx
AALIM MUHAMMED SALEGH COLLEGE OF ENGINEERING
 
PPTX
UNIT 1.pptx
EduclentMegasoftel
 
PPTX
Java fundamentals
Om Ganesh
 
What is Java, JDK, JVM, Introduction to Java.pptx
kumarsuneel3997
 
Java
seenak
 
1 .java basic
Indu Sharma Bhardwaj
 
TechSearchWeb.pdf
TechSearchWeb
 
Technology Tutorial.pdf
TechSearchWeb
 
Java Basic.pdf
TechSearchWeb
 
Module1_htryjtjhkrhdegtfhsfhrdgfhpart1.pptx
aashrithsai7dkm
 
what is java.pdf
XanGwaps
 
Java technology is widely used currently. Let's start learning of java from b...
aliblackcat76
 
Srgoc java
Gaurav Singh
 
Chapter 1 (1).pptx
krishnashah277578
 
JAVA PROGRAM CONSTRUCTS OR LANGUAGE BASICS.pptx
AALIM MUHAMMED SALEGH COLLEGE OF ENGINEERING
 
UNIT 1.pptx
EduclentMegasoftel
 
Java fundamentals
Om Ganesh
 
Ad

Recently uploaded (20)

PPT
Talk on Critical Theory, Part II, Philosophy of Social Sciences
Soraj Hongladarom
 
PPTX
Capitol Doctoral Presentation -July 2025.pptx
CapitolTechU
 
PDF
CEREBRAL PALSY: NURSING MANAGEMENT .pdf
PRADEEP ABOTHU
 
PPTX
PPT on the Development of Education in the Victorian England
Beena E S
 
PPTX
How to Configure Access Rights of Manufacturing Orders in Odoo 18 Manufacturing
Celine George
 
PDF
'' IMPORTANCE OF EXCLUSIVE BREAST FEEDING ''
SHAHEEN SHAIKH
 
PPTX
How to Manage Promotions in Odoo 18 Sales
Celine George
 
PDF
People & Earth's Ecosystem -Lesson 2: People & Population
marvinnbustamante1
 
PPSX
HEALTH ASSESSMENT (Community Health Nursing) - GNM 1st Year
Priyanshu Anand
 
PPTX
How to Configure Prepayments in Odoo 18 Sales
Celine George
 
PDF
IMP NAAC-Reforms-Stakeholder-Consultation-Presentation-on-Draft-Metrics-Unive...
BHARTIWADEKAR
 
PPTX
Soil and agriculture microbiology .pptx
Keerthana Ramesh
 
PPTX
Unit 2 COMMERCIAL BANKING, Corporate banking.pptx
AnubalaSuresh1
 
PDF
IMP NAAC REFORMS 2024 - 10 Attributes.pdf
BHARTIWADEKAR
 
PDF
community health nursing question paper 2.pdf
Prince kumar
 
PPTX
Views on Education of Indian Thinkers Mahatma Gandhi.pptx
ShrutiMahanta1
 
PDF
Federal dollars withheld by district, charter, grant recipient
Mebane Rash
 
PPTX
How to Create Rental Orders in Odoo 18 Rental
Celine George
 
PPTX
A PPT on Alfred Lord Tennyson's Ulysses.
Beena E S
 
PPTX
Quarter1-English3-W4-Identifying Elements of the Story
FLORRACHELSANTOS
 
Talk on Critical Theory, Part II, Philosophy of Social Sciences
Soraj Hongladarom
 
Capitol Doctoral Presentation -July 2025.pptx
CapitolTechU
 
CEREBRAL PALSY: NURSING MANAGEMENT .pdf
PRADEEP ABOTHU
 
PPT on the Development of Education in the Victorian England
Beena E S
 
How to Configure Access Rights of Manufacturing Orders in Odoo 18 Manufacturing
Celine George
 
'' IMPORTANCE OF EXCLUSIVE BREAST FEEDING ''
SHAHEEN SHAIKH
 
How to Manage Promotions in Odoo 18 Sales
Celine George
 
People & Earth's Ecosystem -Lesson 2: People & Population
marvinnbustamante1
 
HEALTH ASSESSMENT (Community Health Nursing) - GNM 1st Year
Priyanshu Anand
 
How to Configure Prepayments in Odoo 18 Sales
Celine George
 
IMP NAAC-Reforms-Stakeholder-Consultation-Presentation-on-Draft-Metrics-Unive...
BHARTIWADEKAR
 
Soil and agriculture microbiology .pptx
Keerthana Ramesh
 
Unit 2 COMMERCIAL BANKING, Corporate banking.pptx
AnubalaSuresh1
 
IMP NAAC REFORMS 2024 - 10 Attributes.pdf
BHARTIWADEKAR
 
community health nursing question paper 2.pdf
Prince kumar
 
Views on Education of Indian Thinkers Mahatma Gandhi.pptx
ShrutiMahanta1
 
Federal dollars withheld by district, charter, grant recipient
Mebane Rash
 
How to Create Rental Orders in Odoo 18 Rental
Celine George
 
A PPT on Alfred Lord Tennyson's Ulysses.
Beena E S
 
Quarter1-English3-W4-Identifying Elements of the Story
FLORRACHELSANTOS
 
Ad

JAVA PROGRAMMING-Unit I - Final PPT.pptx

  • 2. UNIT - I Introduction to Java – Naming conventions and data types – Literals – operators in Java – Control statements in Java – Classes and Objects – Instance Variables, set Methods – Initializing objects with constructors.
  • 3. INTRODUCTION TO JAVA • JAVA was developed by James Gosling at Sun Microsystems in the year 1991, later acquired by Oracle Corporation. • Java is a programming language and a platform. • Java is a high level, robust, object-oriented and secure programming language. • Java makes writing, compiling, and debugging programming easy. • It helps to create reusable code and modular programs.
  • 4. • 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++.
  • 5. Why named as JAVA? •Java is the name of an island in Indonesia where the first coffee (named java coffee) was produced. •And this name was chosen by James Gosling while having coffee near his office. Note that Java is just a name, not an acronym.
  • 6. Why we use Java? • Java works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc.) • It is one of the most popular programming language in the world • It is easy to learn and simple to use • It is open-source and free • It is secure, fast and powerful • It has a huge community support (tens of millions of developers) • Java is an object oriented language which gives a clear structure to programs and allows code to be reused, lowering development costs • As Java is close to C++ and C#, it makes it easy for programmers to switch to Java or vice versa
  • 7. Java Applications • Mobile applications (specially Android apps) • Desktop Applications such as acrobat reader, media player, antivirus, etc. • Enterprise Applications such as banking applications. • Web applications such as irctc.co.in • Web servers and application servers • Embedded System • Smart Card • Robotics • Games • Database connection • And much, much more!
  • 8. Types of Java Applications There are mainly 4 types of applications that can be created using Java programming: 1) Standalone Application Standalone applications are also known as desktop applications or window-based applications. These are traditional software that we need to install on every machine. Examples of standalone application are Media player, antivirus, etc. AWT and Swing are used in Java for creating standalone applications.
  • 9. 2) Web Application An application that runs on the server side and creates a dynamic page is called a web application. Currently, Servlet, JSP, Struts, Spring, Hibernate, JSF, etc. technologies are used for creating web applications in Java. 3) Enterprise Application An application that is distributed in nature, such as banking applications, etc. is called an enterprise application. It has advantages like high-level security, load balancing, and clustering. In Java, EJB is used for creating enterprise applications. 4) Mobile Application An application which is created for mobile devices is called a mobile application. Currently, Android and Java ME are used for creating mobile applications.
  • 10. Java Platforms / Editions There are 4 platforms or editions of Java: 1) Java SE (Java Standard Edition) It is a Java programming platform. It includes Java programming APIs such as java.lang, java.io, java.net, java.util, java.sql, java.math etc. It includes core topics like OOPs, String, Regex, Exception, Inner classes, Multithreading, I/O Stream, Networking, AWT (Abstract Window Toolkit), Swing, Reflection, Collection, etc.
  • 11. 2) Java EE (Java Enterprise Edition) It is an enterprise platform that is mainly used to develop web and enterprise applications. It is built on top of the Java SE platform. It includes topics like Servlet, JSP, Web Services, EJB, JPA, etc. 3) Java ME (Java Micro Edition) It is a micro platform that is dedicated to mobile applications. 4) JavaFX It is used to develop rich internet applications. It uses a lightweight user interface API.
  • 12. Main Features of Java 1. Platform Independent: Compiler converts source code to bytecode and then the JVM executes the bytecode generated by the compiler. •This bytecode can run on any platform be it Windows, Linux, macOS which means if we compile a program on Windows, then we can run it on Linux and vice versa. •Each operating system has a different JVM, but the output produced by all the OS is the same after the execution of bytecode. •That is why we call java a platform-independent language.
  • 13. 2. Object-Oriented Programming Language: Organizing the program in the terms of collection of objects is a way of object-oriented programming, each of which represents an instance of the class. The four main concepts of Object-Oriented programming are: •Abstraction •Encapsulation •Inheritance •Polymorphism 3. Simple: Java is one of the simple languages as it does not have complex features like pointers, operator overloading, multiple inheritances, Explicit memory allocation.
  • 14. 4. Robust: Java language is robust that means reliable. It is developed in such a way that it puts a lot of effort into checking errors as early as possible, that is why the java compiler is able to detect even those errors that are not easy to detect by another programming language. The main features of java that make it robust are garbage collection, Exception Handling, and memory allocation. 5. Secure: In java, we don’t have pointers, and so we cannot access out-of-bound arrays i.e it shows ArrayIndexOutOfBound Exception if we try to do so. That’s why several security flaws like stack corruption or buffer overflow is impossible to exploit in Java.
  • 15. 6. Distributed: We can create distributed applications using the java programming language. Remote Method Invocation and Enterprise Java Beans are used for creating distributed applications in java. The java programs can be easily distributed on one or more systems that are connected to each other through an internet connection. 7. Multithreading: Java supports multithreading. It is a Java feature that allows concurrent execution of two or more parts of a program for maximum utilization of CPU. 8. Portable: As we know, java code written on one machine can be run on another machine. The platform-independent feature of java in which its platform-independent bytecode can be taken to any platform for execution makes java portable.
  • 16. 9. High Performance: Java architecture is defined in such a way that it reduces overhead during the runtime and at some time java uses Just In Time (JIT) compiler where the compiler compiles code on-demand basics where it only compiles those methods that are called making applications to execute faster. 10. Dynamic flexibility: Java being completely object-oriented gives us the flexibility to add classes, new methods to existing classes and even creating new classes through sub- classes. Java even supports functions written in other languages such as C, C++ which are referred to as native methods.
  • 17. 11. Sandbox Execution: Java programs run in a separate space that allows user to execute their applications without affecting the underlying system with help of a bytecode verifier. Bytecode verifier also provides additional security as it’s role is to check the code for any violation access. 12. Write Once Run Anywhere: As discussed above java application generates ‘.class’ file which corresponds to our applications(program) but contains code in binary format. It provides architecture-neutral ease as bytecode is not dependent on any machine architecture. It is the primary reason java is used in the enterprising IT industry globally worldwide. 13. Power of compilation and interpretation: Most languages are designed with purpose either they are compiled language or they are interpreted language. But java integrates arising enormous power as Java compiler compiles the source code to bytecode and JVM executes this bytecode to machine OS-dependent executable code.
  • 18. Example // Demo Java program // Importing classes from packages Out Put: import java.io.*; Welcome // Main class public class GFG { // Main method public static void main(String[] args) { // Print statement System.out.println("Welcome"); } }
  • 19. Explanation: 1. Comments: Comments are used for explaining code and are used in a similar manner in Java or C or C++. Compilers ignore the comment entries and do not execute them. Comments can be of a single line or multiple lines. Single Line Comments: Syntax: // Single line comment Multi-line Comments: Syntax: /* Multi line comments*/
  • 20. 2. Import java.io*: This means all the classes of io package can be imported. Java io package provides a set of input and output streams for reading and writing data to files or other input and output streams for reading and writing data to files or other input or output sources. 3. Class: The class contains the data and methods to be used in the program. Methods define the behaviour of the class. Class GFG has only one method main in Java. 4. Static void main(); Static keyword tells us that this method is accessible without instantiating the class. 5. void: keywords tell that this method will not return anything. The main() method is the entry point of our application.
  • 21. 6. System.in: This is the standard input stream that is used to read characters from the keyboard or any other standard input device. 7. System.out: This is the standard output stream that is used to produce the result of a program on an output device like the computer screen. 8. println(): This method in Java is also used to display text on the console. It prints the text on the console and the cursor moves to the start of the next line at the console. The next printing takes place from the next line.
  • 22. Java Naming Convention •Java naming convention is a rule to follow as you decide what to name your identifiers such as class, package, variable, constant, method, etc. Advantage of Naming Conventions in Java •Readability of Java program is very important. •It indicates that less time is spent to figure out what the code does.
  • 23. Naming Conventions of the Different Identifiers Identifiers Type Naming Rules Examples Class It should start with the uppercase letter. It should be a noun such as Color, Button, System, Thread, etc. Use appropriate words, instead of acronyms. public class Employee { //code snippet } Interface It should start with the uppercase letter. It should be an adjective such as Runnable, Remote, ActionListener. Use appropriate words, instead of acronyms. interface Printable { //code snippet } Method It should start with lowercase letter. It should be a verb such as main(), print(), println(). If the name contains multiple words, start it with a lowercase letter followed by an uppercase letter such as actionPerformed(). class Employee { // method void draw() { //code snippet } }
  • 24. Variable It should start with a lowercase letter such as id, name. It should not start with the special characters like & (ampersand), $ (dollar), _ (underscore). If the name contains multiple words, start it with the lowercase letter followed by an uppercase letter such as firstName, lastName. class Employee { // variable int id; //code snippet } Package It should be a lowercase letter such as java, lang. If the name contains multiple words, it should be separated by dots (.) such as java.util, java.lang. //package package com.example.mypackage; class Employee { //code snippet } Constant It should be in uppercase letters such as RED, YELLOW. If the name contains multiple words, it should be separated by an underscore(_) such as MAX_PRIORITY. It may contain digits but not as the first letter. class Employee { //constant static final int MIN_AGE = 18; //code snippet }
  • 25. CamelCase in Java naming conventions •Java follows camel-case syntax for naming the class, interface, method, and variable. •If the name is combined with two words, the second word will start with uppercase letter always such as actionPerformed(), firstName, ActionEvent, ActionListener, etc.
  • 26. Data Types in Java Data types specify the different sizes and values that can be stored in the variable.
  • 27. 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, Interfaces, and Arrays.
  • 28. Java Primitive Data Types In Java language, primitive data types are the building blocks of data manipulation. These are the most basic data types available in Java Language. There are 8 types of primitive data types: •boolean data type •byte data type •char data type •short data type •int data type •long data type •float data type •double data type
  • 29. Integer Types: Size and Range of Integer Types
  • 30. Floating point Types •Floating point type will hold numbers containing fractional parts such as 27.59 and - 1.375. •There are two types of floating point •The float types values are single precision numbers •Double type values are double precision numbers Type Size Minimum Value Maximum Value Float 4 bytes 3.4e-038 1.7e+0.38 Double 8 bytes 3.4e-038 1.7e+308
  • 31. CharacterType •The character type assumes a size of two bytes •But it can hold only a single character Boolean Type •Boolean types is used when we want to test a particular condition during the execution of the program. •There are only two values true or false •Boolean type is denoted with the keyword Boolean and uses 1 bit of storage.
  • 32. LITERALS • Literal in Java is a synthetic representation of boolean, numeric, character, or string data. • Literals are the constant values that appear directly in the program. •It can be assigned directly to a variable. It is a means of expressing particular values in the program, such as an integer variable named “/count is assigned an integer value in the following statement. int count = 0; • A literal ‘0’ represents the value zero. •Thus, a constant value assigned to the variable can be referred to as literal.
  • 33. Literals in Java can be classified into six types, as below: •Integral Literals •Floating-point Literals •Char Literals •String Literals •Boolean Literals •Null Literals
  • 34. 1. Integral Literals Integral literals are specified in four different ways, as follows: Decimal: It has base ten, and digits from 0 to 9. For example, Int x = 108; Octal: It has base eight and allows digits from 0 to 7. While assigning an octal literal in the Java code, a number must have a prefix 0. For example, int x = 0745;
  • 35. Hexadecimal: It has base 16. Hexadecimal allows digits from 0 to 9, and characters from A to F. Even though Java is case sensitive, and it also provides an exception for using either uppercase or lowercase characters in the code for hexadecimal literals. For example, int x = 0X123Fadd; Binary: It can be specified in binary literals, that is 0 and 1 with a prefix 0b or 0B. For example, int x = 0b1011;
  • 36. 2. Floating-Point Literals Floating-point literals can be expressed using only decimal fractions or as exponential notation. For example, decimalNumber = 89d; decimalNumber = 3.14159e0; decimalNumber = 1.0e-6D; Floating-point literals can indicate a positive or negative value, leading + or – sign respectively. If not specified, the value is always considered positive. It can be represented in the following formats: -Integer digits (representing digits 0 through 9) followed by either a suffix or an exponent to distinguish it from an integral literal. -/integer digit. - integer digit.integer digit
  • 37. An optional exponent of the form might be as below: -an optional exponent sign + or – -the exponent indicator e or E –integer digit representing the integer exponent value An optional floating-point suffix might be as below: Single precision (4 bytes) floating-point number indicating either for F Double precision (8 bytes) floating-point number indicating d or D
  • 38. 3. Char Literals • Character (Char) literals have the type char and are an unsigned integer primitive type. •They are constant value character expressions in the Java program. •These are sixteen-bit Unicode characters that range from 0 to 65535. •Char literals are expressed as a single quote, a single closing quote, and the character in Java. • Char literals are specified in four different ways, as given below: •Single quote: Java literal is specified to a char data type as a single character enclosed in a single quote. •For example, •char ch = ‘a’;
  • 39. Char Literal: Java literal is specified as an integer literal representing the Unicode value of a char. This integer can be specified in octal, decimal, and hexadecimal, ranging from 0 to 65535. For example, char ch = 062; Escape Sequence: Every escape char can be specified as char literal. For example, char ch = ‘n’; Unicode Representation: Java literal is specified in Unicode representation ‘uzzz’, where zzzz are four hexadecimal numbers. For example, char ch = ‘u0061’;
  • 40. 4. String Literals •A sequence of (zero or more including Unicode characters) characters within double quotes is referred to as string literals. For example, String s = “Hello”; •String literals may not have unescaped line feed or newline characters, but the Java compiler always evaluates compile-time expressions. • Unicode escape sequences or special characters can be used within the string and character literal as backlash characters to escape special characters, as shown in the table below:
  • 42. 5. Boolean Literals Boolean literals allow only two values and thus are divided into two literals: True: it represents a real boolean value False: it represents a false boolean value For example, boolean b = true; boolean d = false; 6. Null Literals •Null literal is a particular literal in Java representing a null value. This value refers to no object. Java throws NullPointerException. • Null often describe the uninitialized state in the program. It is an error to attempt to dereference the null value.
  • 43. Operators in Java Operator in Java is a symbol that is used to perform operations. For example: +, -, *, / etc. There are many types of operators in Java which are given below: •Unary Operator, •Arithmetic Operator, •Shift Operator, •Relational Operator, •Bitwise Operator, •Logical Operator, •Ternary Operator and •Assignment Operator.
  • 44. Operator Type Category Precedence Unary postfix expr++ expr-- prefix ++expr --expr +expr -expr ~ ! Arithmetic multiplicative * / % additive + - Shift shift << >> >>> Relational comparison < > <= >= instanceof equality == != Bitwise bitwise AND & bitwise exclusive OR ^ bitwise inclusive OR | Logical logical AND && logical OR || Ternary ternary ? : Assignment assignment = += -= *= /= %= &= ^= |= <<= >>= >>>=
  • 45. Java Unary Operator The Java unary operators require only one operand. Unary operators are used to perform various operations i.e.: •incrementing/decrementing a value by one •negating an expression •inverting the value of a boolean
  • 46. Java Unary Operator Example: ++ and -- 1.public class OperatorExample{ 2.public static void main(String args[]){ 3.int x=10; 4.System.out.println(x++);//10 (11) 5.System.out.println(++x);//12 6.System.out.println(x--);//12 (11) 7.System.out.println(--x);//10 8.}}
  • 48. Java Unary Operator Example 2: ++ and -- 1.public class OperatorExample{ 2.public static void main(String args[]){ Output: 3.int a=10; 22 4.int b=10; 21 5.System.out.println(a++ + ++a);//10+12=22 6.System.out.println(b++ + b++);//10+11=21 7. 8.}}
  • 49. Java Unary Operator Example: ~ and ! 1.public class OperatorExample{ Output: 2.public static void main(String args[]){ -11 3.int a=10; 9 4.int b=-10; false 5.boolean c=true; true 6.boolean d=false; 7.System.out.println(~a);//-11 (minus of total positive value which starts from 0) 8.System.out.println(~b);//9 (positive of total minus, positive starts from 0) 9.System.out.println(!c);//false (opposite of boolean value) 10.System.out.println(!d);//true 11.}}
  • 50. Java Arithmetic Operators Java arithmetic operators are used to perform addition, subtraction, multiplication, and division. They act as basic mathematical operations.
  • 51. Java Arithmetic Operator Example 1.public class OperatorExample{ Output: 2.public static void main(String args[]){ 15 3.int a=10; 5 4.int b=5; 50 5.System.out.println(a+b);//15 2 6.System.out.println(a-b);//5 0 7.System.out.println(a*b);//50 8.System.out.println(a/b);//2 9.System.out.println(a%b);//0 10.}}
  • 52. Java Arithmetic Operator Example: Expression 1.public class OperatorExample{ 2.public static void main(String args[]){ 3.System.out.println(10*10/5+3-1*4/2); 4.}} Output: 21
  • 53. Java Left Shift Operator The Java left shift operator << is used to shift all of the bits in a value to the left side of a specified number of times. Java Left Shift Operator Example 1.public class OperatorExample{ 2.public static void main(String args[]){ 3.System.out.println(10<<2);//10*2^2=10*4=40 4.System.out.println(10<<3);//10*2^3=10*8=80 5.System.out.println(20<<2);//20*2^2=20*4=80 6.System.out.println(15<<4);//15*2^4=15*16=240 7.}}
  • 55. Java Right Shift Operator The Java right shift operator >> is used to move the value of the left operand to right by the number of bits specified by the right operand. Java Right Shift Operator Example 1.public OperatorExample{ 2.public static void main(String args[]){ 3.System.out.println(10>>2);//10/2^2=10/4=2 4.System.out.println(20>>2);//20/2^2=20/4=5 5.System.out.println(20>>3);//20/2^3=20/8=2 6.}}
  • 57. Java Shift Operator Example: >> vs >>> 1.public class OperatorExample{ 2.public static void main(String args[]){ 3. //For positive number, >> and >>> works same 4. System.out.println(20>>2); 5. System.out.println(20>>>2); 6. //For negative number, >>> changes parity bit (MSB) to 0 7. System.out.println(-20>>2); 8. System.out.println(-20>>>2); 9.}}
  • 59. Java AND Operator Example: Logical && and Bitwise & •The logical && operator doesn't check the second condition if the first condition is false. It checks the second condition only if the first one is true. •The bitwise & operator always checks both conditions whether first condition is true or false.
  • 60. 1.public class OperatorExample{ Output: 2.public static void main(String args[]){ false 3.int a=10; false 4.int b=5; 5.int c=20; 6.System.out.println(a<b&&a<c);//false && true = false 7.System.out.println(a<b&a<c);//false & true = false 8.}}
  • 61. Java AND Operator Example: Logical && vs Bitwise & 1.public class OperatorExample{ 2.public static void main(String args[]){ 3.int a=10; 4.int b=5; 5.int c=20; 6.System.out.println(a<b&&a++<c);//false && true = false 7.System.out.println(a);//10 because second condition is not checked 8.System.out.println(a<b&a++<c);//false && true = false 9.System.out.println(a);//11 because second condition is checked 10.}}
  • 63. Java OR Operator Example: Logical || and Bitwise | •The logical || operator doesn't check the second condition if the first condition is true. It checks the second condition only if the first one is false. The bitwise | operator always checks both conditions whether first condition is true or false.
  • 64. 1.public class OperatorExample{ 2.public static void main(String args[]){ 3.int a=10; 4.int b=5; 5.int c=20; 6.System.out.println(a>b||a<c);//true || true = true 7.System.out.println(a>b|a<c);//true | true = true 8.//|| vs | 9.System.out.println(a>b||a++<c);//true || true = true 10.System.out.println(a);//10 because second condition is not checked 11.System.out.println(a>b|a++<c);//true | true = true 12.System.out.println(a);//11 because second condition is checked 13.}}
  • 66. Java Ternary Operator Java ternary operator is the only conditional operator that takes three operands. Java Ternary operator is used as one line replacement for if-then-else statement and used a lot in Java programming. It is the only conditional operator which takes three operands. Java Ternary Operator Example 1.public class OperatorExample{ Output: 2.public static void main(String args[]){ 2 3.int a=2; 4.int b=5; 5.int min=(a<b)?a:b; 6.System.out.println(min); 7.}}
  • 67. Another Example: 1.public class OperatorExample{ Output: 2.public static void main(String args[]){ 5 3.int a=10; 4.int b=5; 5.int min=(a<b)?a:b; 6.System.out.println(min); 7.}}
  • 68. Java Assignment Operator Java assignment operator is one of the most common operators. It is used to assign the value on its right to the operand on its left. Java Assignment Operator Example 1.public class OperatorExample{ Output: 2.public static void main(String args[]){ 14 3.int a=10; 16 4.int b=20; 5.a+=4;//a=a+4 (a=10+4) 6.b-=4;//b=b-4 (b=20-4) 7.System.out.println(a); 8.System.out.println(b); 9.}}
  • 69. Control Statements in Java •Java compiler executes the code from top to bottom. •The statements in the code are executed according to the order in which they appear. • However, Java provides statements that can be used to control the flow of Java code. •Such statements are called control flow statements. •It is one of the fundamental features of Java, which provides a smooth flow of program.
  • 70. Java provides three types of control flow statements. 1.Decision Making statements 1. if statements 2. switch statement 2.Loop statements 1. do while loop 2. while loop 3. for loop 4. for-each loop 3.Jump statements 1. break statement 2. continue statement
  • 71. Decision-Making statements: •As the name suggests, decision-making statements decide which statement to execute and when. •Decision-making statements evaluate the Boolean expression and control the program flow depending upon the result of the condition provided. • There are two types of decision-making statements in Java, i.e., If statement and switch statement.
  • 72. If Statement: In Java, the "if" statement is used to evaluate a condition. The control of the program is diverted depending upon the specific condition. The condition of the If statement gives a Boolean value, either true or false. Syntax: if (test expression) In Java, there are four types of if-statements given below. 1.Simple if statement 2.if-else statement 3.if-else-if ladder 4.Nested if-statement
  • 73. Simple if statement: It is the most basic statement among all control flow statements in Java. It evaluates a Boolean expression and enables the program to enter a block of code if the expression evaluates to true. Syntax of if statement is given below. 1.if(condition) { 2.statement 1; //executes when condition is true 3.} 4.}
  • 74. Consider the following example in which we have used the if statement in the java code. Student.java Student.java Output: 1.public class Student { x+y is greater than 20 2.public static void main(String[] args) { 3.int x = 10; 4.int y = 12; 5.if(x+y > 20) { 6.System.out.println("x + y is greater than 20"); 7.} 8.}
  • 75. 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: 1.if(condition) { 2.statement 1; //executes when condition is true 3.} 4.else{ 5.statement 2; //executes when condition is false 6.}
  • 76. Consider the following example. Student.java Output: 1.public class Student { x+y is greater than 20 2.public static void main(String[] args) { 3.int x = 10; 4.int y = 12; 5.if(x+y < 10) { 6.System.out.println("x + y is less than 10"); 7.} else { 8.System.out.println("x + y is greater than 20"); 9.} 10.} 11.}
  • 77. if-else-if ladder: The if-else-if statement contains the if-statement followed by multiple else-if statements. In other words, we can say that it is the chain of if-else statements that create a decision tree where the program may enter in the block of code where the condition is true. We can also define an else statement at the end of the chain. Syntax of if-else-if statement is given below. 1.if(condition 1) { 2.statement 1; //executes when condition 1 is true 3.} 4.else if(condition 2) { 5.statement 2; //executes when condition 2 is true 6.} 7.else { 8.statement 2; //executes when all the conditions are false 9.}
  • 78. 1.public class Student { Output: 2.public static void main(String[] args) { Delhi 3.String city = "Delhi"; 4.if(city == "Meerut") { 5.System.out.println("city is meerut"); 6.}else if (city == "Noida") { 7.System.out.println("city is noida"); 8.}else if(city == "Agra") { 9.System.out.println("city is agra"); 10.}else { 11.System.out.println(city); 12.} 13.} 14.}
  • 79. Nested if-statement In nested if-statements, the if statement can contain a if or if-else statement inside another if or else-if statement. Syntax of Nested if-statement is given below. 1.if(condition 1) { 2.statement 1; //executes when condition 1 is true 3.if(condition 2) { 4.statement 2; //executes when condition 2 is true 5.} 6.else{ 7.statement 2; //executes when condition 2 is false 8.} 9.}
  • 80. 1.public class Student { Output: 2.public static void main(String[] args) { Delhi 3.String address = "Delhi, India"; 4.if(address.endsWith("India")) { 5.if(address.contains("Meerut")) { 6.System.out.println("Your city is Meerut"); 7.}else if(address.contains("Noida")) { 8.System.out.println("Your city is Noida"); 9.}else { 10.System.out.println(address.split(",")[0]); 11.} 12.}else { 13.System.out.println("You are not living in India"); 14.} 15.} 16.}
  • 81. Switch Statement: In Java, Switch statements are similar to if-else-if statements. The switch statement contains multiple blocks of code called cases and a single case is executed based on the variable which is being switched. The switch statement is easier to use instead of if-else-if statements. It also enhances the readability of the program.
  • 82. Points to be noted about switch statement: •The case variables can be int, short, byte, char, or enumeration. String type is also supported since version 7 of Java •Cases cannot be duplicate •Default statement is executed when any of the case doesn't match the value of expression. It is optional. •Break statement terminates the switch block when the condition is satisfied. It is optional, if not used, next case is executed. •While using switch statements, we must notice that the case expression will be of the same type as the variable. However, it will also be a constant value.
  • 83. The syntax to use the switch statement is given below. 1.switch (expression){ 2. case value1: 3. statement1; 4. break; 5. . 6. . 7. . 8. case valueN: 9. statementN; 10. break; 11. default: 12. default statement; 13.}
  • 84. 1.public class Student implements Cloneable { 2.public static void main(String[] args) { Output: 3.int num = 2; 2 4.switch (num){ 5.case 0: 6.System.out.println("number is 0"); 7.break; 8.case 1: 9.System.out.println("number is 1"); 10.break; 11.default: 12.System.out.println(num); 13.} 14.} 15.}
  • 85. •While using switch statements, we must notice that the case expression will be of the same type as the variable. • However, it will also be a constant value. •The switch permits only int, string, and Enum type variables to be used.
  • 86. Loop Statements •Loop statements are used to execute the set of instructions in a repeated order. The execution of the set of instructions depends upon a particular condition. In Java, we have three types of loops that execute similarly. However, there are differences in their syntax and condition checking time. 1.for loop 2.while loop 3.do-while loop
  • 87. For Loop •In Java, for loop is similar to C and C++. •It enables us to initialize the loop variable, check the condition, and increment/decrement in a single line of code. We use the for loop only when we exactly know the number of times, we want to execute the block of code. 1.for(initialization, condition, increment/decrement) { 2.//block of statements 3.}
  • 88. The flow chart for the for-loop is given below.
  • 89. 1.public class Calculation { 2.public static void main(String[] args) { 3.// TODO Auto-generated method stub 4.int sum = 0; 5.for(int j = 1; j<=10; j++) { 6.sum = sum + j; 7.} 8.System.out.println("The sum of first 10 natural numbers is " + sum); 9.} 10.} Output: The sum of first 10 natural numbers is 55
  • 90. for-each loop •Java provides an enhanced for loop to traverse the data structures like array or collection. •In the for-each loop, we don't need to update the loop variable. •The syntax to use the for-each loop in java is given below. 1.for(data_type var : array_name/collection_name){ 2.//statements 3.}
  • 91. 1.public class Calculation { 2.public static void main(String[] args) { 3.// TODO Auto-generated method 4.String[] names = {"Java","C","C++","Python","JavaScript"}; 5.System.out.println("Printing the content of the array names:n"); 6.for(String name:names) { 7.System.out.println(name); 8.} 9.} 10.} Output:
  • 92. Printing the array of content names: Java C C++ Python JavaScript
  • 93. while loop •The while loop is also used to iterate over the number of statements multiple times. However, if we don't know the number of iterations in advance, it is recommended to use a while loop. •Unlike for loop, the initialization and increment/decrement doesn't take place inside the loop statement in while loop. •It is also known as the entry-controlled loop since the condition is checked at the start of the loop. If the condition is true, then the loop body will be executed; otherwise, the statements after the loop will be executed.
  • 94. The syntax of the while loop: while(condition){ 1.//looping statements 2.}
  • 95. 1.public class Calculation { 2.public static void main(String[] args) { 3.// TODO Auto-generated method stub 4.int i = 0; 5.System.out.println("Printing the list of first 10 even numbers n"); 6.while(i<=10) { 7.System.out.println(i); 8.i = i + 2; 9.} 10.} 11.}
  • 96. Printing the list of first 10 even numbers 0 2 4 6 8 10
  • 97. do-while loop •The do-while loop checks the condition at the end of the loop after executing the loop statements. •When the number of iteration is not known and we have to execute the loop at least once, we can use do-while loop. •It is also known as the exit-controlled loop since the condition is not checked in advance. The syntax of the do-while loop is given below. 1.do 2.{ 3.//statements 4.} while (condition);
  • 98. The flow chart of do-while loop
  • 99. 1.public class Calculation { 2.public static void main(String[] args) { 3.// TODO Auto-generated method stub 4.int i = 0; 5.System.out.println("Printing the list of first 10 even numbers n"); 6.do { 7.System.out.println(i); 8.i = i + 2; 9.}while(i<=10); 10.} 11.}
  • 100. Printing the list of first 10 even numbers 0 2 4 6 8 10
  • 101. Jump Statements •Jump statements are used to transfer the control of the program to the specific statements. •In other words, jump statements transfer the execution control to the other part of the program. •There are two types of jump statements in Java, i.e., break and continue.
  • 102. Break Statement •As the name suggests, the break statement is used to break the current flow of the program and transfer the control to the next statement outside a loop or switch statement. •However, it breaks only the inner loop in the case of the nested loop. •The break statement cannot be used independently in the Java program, i.e., it can only be written inside the loop or switch statement.
  • 103. The break statement example with for loop 1.public class BreakExample { 2.public static void main(String[] args) { 3.// TODO Auto-generated method stub 4.for(int i = 0; i<= 10; i++) { 5.System.out.println(i); 6.if(i==6) { 7.break; 8.} 9.} 10.} 11.}
  • 105. break statement example with labeled for loop 1.public class Calculation { 2.public static void main(String[] args) { Output: 3.// TODO Auto-generated method stub 0 4.a: 1 5.for(int i = 0; i<= 10; i++) { 2 6.b: 3 7.for(int j = 0; j<=15;j++) { 4 8.c: 5 9.for (int k = 0; k<=20; k++) { 10.System.out.println(k); 11.if(k==5) { 12.break a; 13.} 14.} 15.} 16.}
  • 106. Continue Statement Unlike break statement, the continue statement doesn't break the loop, whereas, it skips the specific part of the loop and jumps to the next iteration of the loop immediately.
  • 107. 1.public class ContinueExample { 2. 3.public static void main(String[] args) { 4.// TODO Auto-generated method stub 5.for(int i = 0; i<= 2; i++) { 6.for (int j = i; j<=5; j++) { 7.if(j == 4) { 8.continue; 9.} 10.System.out.println(j); 11.} 12.} 13.} 14.}
  • 109. Classes and Objects •In object-oriented programming technique, we design a program using objects and classes. •An object in Java is the physical as well as a logical entity, whereas, a class in Java is a logical entity only. Object in Java •An entity that has state and behavior is known as an object e.g., chair, bike, marker, pen, table, car, etc. •It can be physical or logical (tangible and intangible). The example of an intangible object is the banking system.
  • 110. An object has three characteristics: State: represents the data (value) of an object. •Behavior: represents the behavior (functionality) of an object such as deposit, withdraw, etc. •Identity: An object identity is typically implemented via a unique ID. The value of the ID is not visible to the external user. However, it is used internally by the JVM to identify each object uniquely.
  • 112. Object Definitions: •An object is a real-world entity. •An object is a runtime entity. •The object is an entity which has state and behavior. •The object is an instance of a class.
  • 113. Class in Java A class is a group of objects which have common properties. It is a template or blueprint from which objects are created. It is a logical entity. It can't be physical. A class in Java can contain: •Fields •Methods •Constructors •Blocks •Nested class and interface
  • 114. Syntax to declare a class: 1.class <class_name>{ 2. field; 3. method; 4.} Instance variable in Java •A variable which is created inside the class but outside the method is known as an instance variable. • Instance variable doesn't get memory at compile time. It gets memory at runtime when an object or instance is created. That is why it is known as an instance variable.
  • 115. Method in Java In Java, a method is like a function which is used to expose the behavior of an object. Advantage of Method •Code Reusability •Code Optimization New keyword in Java The new keyword is used to allocate memory at runtime. All objects get memory in Heap memory area. Object and Class Example: main within the class In this example, we have created a Student class which has two data members id and name. We are creating the object of the Student class by new keyword and printing the object's value. Here, we are creating a main() method inside the class.
  • 116. 1.//Java Program to illustrate how to define a class and fields 2.//Defining a Student class. Output: 3.class Student{ 0 4. //defining fields null 5. int id;//field or data member or instance variable 6. String name; 7. //creating main method inside the Student class 8. public static void main(String args[]){ 9. //Creating an object or instance 10. Student s1=new Student();//creating an object of Student 11. //Printing values of the object 12. System.out.println(s1.id);//accessing member through reference variable 13. System.out.println(s1.name); 14. } 15.}
  • 117. Object and Class Example: main outside the class •In real time development, we create classes and use it from another class. It is a better approach than previous one. Let's see a simple example, where we are having main() method in another class. •We can have multiple classes in different Java files or single Java file. If you define multiple classes in a single Java source file, it is a good idea to save the file name with the class name which has main() method.
  • 118. 1.//Java Program to demonstrate having the main method in 2.//another class Output: 3.//Creating Student class. 0 4.class Student{ null 5. int id; 6. String name; 7.} 8.//Creating another class TestStudent1 which contains the main method 9.class TestStudent1{ 10. public static void main(String args[]){ 11. Student s1=new Student(); 12. System.out.println(s1.id); 13. System.out.println(s1.name); 14. } 15.}
  • 119. 3 Ways to initialize object There are 3 ways to initialize object in Java. 1.By reference variable 2.By method 3.By constructor 1) Object and Class Example: Initialization through reference Initializing an object means storing data into the object. Let's see a simple example where we are going to initialize the object through a reference variable.
  • 120. 1.class Student{ Output: 2. int id; 101 Sonoo 3. String name; 4.} 5.class TestStudent2{ 6. public static void main(String args[]){ 7. Student s1=new Student(); 8. s1.id=101; 9. s1.name="Sonoo"; 10. System.out.println(s1.id+" "+s1.name);//printing members with a white spac e 11. } 12.}
  • 121. We can also create multiple objects and store information in it through reference variable. 1.class Student{ Output: 2. int id; 101 Sonoo 3. String name; 102 Amit 4.} 5.class TestStudent3{ 6. public static void main(String args[]){ 7. //Creating objects 8. Student s1=new Student(); 9. Student s2=new Student(); 10. //Initializing objects 11. s1.id=101; 12. s1.name="Sonoo"; 13. s2.id=102; 14. s2.name="Amit"; 15. //Printing data 16. System.out.println(s1.id+" "+s1.name); 17. System.out.println(s2.id+" "+s2.name); 18. } 19.}
  • 122. 2) Object and Class Example: Initialization through method •In this example, we are creating the two objects of Student class and initializing the value to these objects by invoking the insertRecord method. •Here, we are displaying the state (data) of the objects by invoking the displayInformation() method.
  • 123. 1.class Student{ 2. int rollno; Output 3. String name; 111 Karan 4. void insertRecord(int r, String n){ 222 Aryan 5. rollno=r; 6. name=n; 7. } 8. void displayInformation(){System.out.println(rollno+" "+name);} 9.} 10.class TestStudent4{ 11. public static void main(String args[]){ 12. Student s1=new Student(); 13. Student s2=new Student(); 14. s1.insertRecord(111,"Karan"); 15. s2.insertRecord(222,"Aryan"); 16. s1.displayInformation(); 17. s2.displayInformation(); 18. } 19.}
  • 124. •As you can see in the above figure, object gets the memory in heap memory area. •The reference variable refers to the object allocated in the heap memory area. • Here, s1 and s2 both are reference variables that refer to the objects allocated in memory.
  • 125. 3)ObjectandClassExample:Initializationthroughaconstructor 1.class Employee{ Output: 2. int id; 101 Ajeet 45000.0 3. String name; 102 Irfan 25000.0 4. float salary; 103 nakul 55000.0 5. void insert(int i, String n, float s) { 6. id=i; 7. name=n; 8. salary=s; 9. } 10. void display(){System.out.println(id+" "+name+" "+salary);} 11.} 12.public class TestEmployee { 13.public static void main(String[] args) { 14. Employee e1=new Employee(); 15. Employee e2=new Employee(); 16. Employee e3=new Employee(); 17. e1.insert(101,"ajeet",45000); 18. e2.insert(102,"irfan",25000); 19. e3.insert(103,"nakul",55000); 20. e1.display(); 21. e2.display(); 22. e3.display(); 23.}
  • 127. Anonymous object Anonymous simply means nameless. An object which has no reference is known as an anonymous object. It can be used at the time of object creation only. If you have to use an object only once, an anonymous object is a good approach. For example: 1.new Calculation();//anonymous object Calling method through a reference: 1.Calculation c=new Calculation(); 2.c.fact(5); Calling method through an anonymous object 1.new Calculation().fact(5);
  • 128. Let's see the full example of an anonymous object in Java. 1.class Calculation{ Output: 2. void fact(int n){ factorial is 120 3. int fact=1; 4. for(int i=1;i<=n;i++){ 5. fact=fact*i; 6. } 7. System.out.println("factorial is "+fact); 8.} 9.public static void main(String args[]){ 10. new Calculation().fact(5);//calling method with anonymous object 11.} 12.}
  • 129. Creating multiple objects by one type only We can create multiple objects by one type only as we do in case of primitives. Initialization of primitive variables: 1.int a=10, b=20; Initialization of reference variables: 1.Rectangle r1=new Rectangle(), r2=new Rectangle();//creating two objects
  • 130. 1.//Java Program to illustrate the use of Rectangle class which 2.//has length and width data members Output: 3.class Rectangle{ 55 4. int length; 45 5. int width; 6. void insert(int l,int w){ 7. length=l; 8. width=w; 9. } 10. void calculateArea(){System.out.println(length*width);} 11.} 12.class TestRectangle2{ 13. public static void main(String args[]){ 14. Rectangle r1=new Rectangle(),r2=new Rectangle();//creating two objects 15. r1.insert(11,5); 16. r2.insert(3,15); 17. r1.calculateArea(); 18. r2.calculateArea(); 19.} 20.}
  • 131. Instance Variables In any programming language, the program needs identifiers for storing different values that can be used throughout the program. These identifiers are variables. Variable in Java •A variable is a name assigned to a value that is stored inside the system memory. The value can be updated during the program execution. •In Java programming, the variables used for the program need to declare them first. •The variable is declared using a data type followed by the identifier name. The variable can be initialized at the time of declaration or it can be assigned a value taken from the user during the program execution. •There are basically three types of variables in Java, • Java Local variable • Java Instance variable • Java Static variable / Java class variable
  • 132. Instance Variable •The variables that are declared inside the class but outside the scope of any method are called instance variables in Java. •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. •Instance variables of different types have default values that are specified in the next point.
  • 133. Features 1.To use an instance variable an object of the class must be created. 2.An instance variable is destroyed when the object it is associated with is destroyed. 3.An instance variable does not compulsory need to be initialized. 4.Instance variables are accessible inside the same class that declares them.
  • 134. Limitations of Instance Variable 1.It cannot be declared static, abstract, striftp, synchronized, and native. 2.It can be declared final and transient. 3.It can be of any of the four access modifiers available in Java (private, public, protected, and default).
  • 135. Default values of Instance Variables Instance variable type Default values boolean false byte (byte) 0 short (short) 0 int 0 double 0.0d float 0.0 long 0L Object null char u0000
  • 136. Using Instance Variable in Java Program 1.public class Studentsrecords 2.{ 3. /* declaration of instance variables. */ 4. public String name; //public instance 5. String division; //default instance 6. private int age; //private instance 7. /* Constructor that initialize an instance variable. */ 8. public Studentsrecords(String sname) 9. { 10. name = sname; 11. } 12. /* Method to intialize an instance variable. */
  • 137. 13. public void printstud() 1. { 2. System.out.println("Student Name: " + name ); 3. System.out.println("Student Division: " + division); 4. System.out.println("Student Age: " + age); 5. } 6. /* Driver Code */ 7. public static void main(String args[]) 8. { 9. Studentsrecords s = new Studentsrecords("Monica"); 10. s.setAge(14); 11. s.setDiv("B"); 12. s.printstud(); 13. } 14.}
  • 138. Output: Student Name: Monica Student Division: B Student Age: 14 •The above Java program initializes the instance variables by declaring an object of the class Studentsrecords. •The values of instance variables name, division, and age are displayed using printstud() method.
  • 139. Difference between Local, Instance and Static variables in Java
  • 140. Sr. No. Local variables Instance variables Static variables 1. Variables declared within a method are local variables. An instance variable is declared inside a class but outside of any method or block. Static variables are declared inside a class but outside of a method starting with a keyword static. 2. The scope of the local variable is limited to the method it is declared inside. An instance variable is accessible throughout the class. The static variable is accessible throughout the class. 3. A local variable starts its lifetime when the method is invoked. The object associated with the instance variable decides its lifetime. The static variable has the same lifetime as the program. 4. Local variable is accessible to all the objects of the class. Instance variable has different copies for different objects. Static variables only have one single copy of the entire class. 5. Used to store values that are required for a particular method. Used to store values that are needed to be accessed by different methods of the class. Used for storing constants.
  • 141. Set Methods in Java •The set is an interface available in the java.util package. •The set interface extends the Collection interface. • An unordered collection or list in which duplicates are not allowed is referred to as a collection interface. •The set interface is used to create the mathematical set. The set interface use collection interface's methods to avoid the insertion of the same elements. •SortedSet and NavigableSet are two interfaces that extend the set implementation.
  • 142. Classes that implement Set Since Set is an interface, we cannot create objects from it. In order to use functionalities of the Set interface, we can use these classes: •Hashset •LinkedHashSet •EnumSet •TreeSet These classes are defined in the Collections framework and implement the Set interface.
  • 145. •In the above diagram, the NavigableSet and SortedSet are both the interfaces. The NavigableSet extends the SortedSet, so it will not retain the insertion order and store the data in a sorted way.
  • 146. 1.import java.util.*; 2.public class setExample{ 3. public static void main(String[] args) 4. { 5. // creating LinkedHashSet using the Set 6. Set<String> data = new LinkedHashSet<String>(); 7. data.add("JavaTpoint"); 8. data.add("Set"); 9. data.add("Example"); 10. data.add("Set"); 11. System.out.println(data); 12. } 13.}
  • 147. Note: Throughout the section, we have compiled the program with file name and run the program with class name. Because the file name and the class name are different.
  • 148. Operations on the set interface On the Set, we can perform all the basic mathematical operations like intersection, union and difference.Suppose, we have two sets, i.e., set1 = [22, 45, 33, 66, 55, 34, 77] and set2 = [33, 2, 83, 45, 3, 12, 55]. We can perform the following operation on the Set: •Intersection: The intersection operation returns all those elements which are present in both the set. The intersection of set1 and set2 will be [33, 45, 55]. •Union: The union operation returns all the elements of set1 and set2 in a single set, and that set can either be set1 or set2. The union of set1 and set2 will be [2, 3, 12, 22, 33, 34, 45, 55, 66, 77, 83]. •Difference: The difference operation deletes the values from the set which are present in another set. The difference of the set1 and set2 will be [66, 34, 22, 77].
  • 149. •In set, addAll() method is used to perform the union, retainAll() method is used to perform the intersection and removeAll() method is used to perform difference. •Let's take an example to understand how these methods are used to perform the intersection, union, and difference operations.
  • 150. 1.import java.util.*; 2.public class SetOperations 3.{ 4. public static void main(String args[]) 5. { 6. Integer[] A = {22, 45,33, 66, 55, 34, 77}; 7. Integer[] B = {33, 2, 83, 45, 3, 12, 55}; 8. Set<Integer> set1 = new HashSet<Integer>(); 9. set1.addAll(Arrays.asList(A)); 10. Set<Integer> set2 = new HashSet<Integer>(); 11. set2.addAll(Arrays.asList(B)); 12. 13. // Finding Union of set1 and set2 14. Set<Integer> union_data = new HashSet<Integer>(set1); 15. union_data.addAll(set2); 16. System.out.print("Union of set1 and set2 is:"); 17. System.out.println(union_data);
  • 151. 18. // Finding Intersection of set1 and set2 19. Set<Integer> intersection_data = new HashSet<Integer>(set1); 1. intersection_data.retainAll(set2); 2. System.out.print("Intersection of set1 and set2 is:"); 3. System.out.println(intersection_data); 4. // Finding Difference of set1 and set2 5. Set<Integer> difference_data = new HashSet<Integer>(set1); 6. difference_data.removeAll(set2); 7. System.out.print("Difference of set1 and set2 is:"); 8. System.out.println(difference_data); 9. } 10.}
  • 152. Initializing objects with Constructors •A Java class defines the data (attributes) and behavior (methods) of a set of similar objects. •Each class has a special type of method called a constructor that is used to initialize the attributes in a newly created object. •A constructor is a special method that has the same name as the class and is used to initialize attributes of a new object. •A new object is created with new keyword followed by the class name.
  • 153. •Object initialization means, initializing class fields. Suppose there is a Person class having a field “name”. •When we create objects like Peter , John and Linda etc. of the class Person, the name field should contain their name. •We can initialize class fields in a constructor of a class. In the constructor ,we can write hard code value like name =”Peter”; as simple as that. •Also, earthier you hard code values of all fields or receive values in the constructor parameter and initialize. • First lets see the output of a simple class when we don’t initialize an object of the class. Below is the class Person having a field name, that is not initialized in constructor.
  • 154. class Person { Output: String name; Person:null // Constructor public Person() { } public String getName() { return this.name; } } public class TestPerson { public static void main(String[] args) { Person john = new Person(); john.getName(); System.out.println("Person:" + john.getName()); } }
  • 155. Now, see the example, where we have initialized field “name” in the constructor of the Person class as “this.name = “Peter”;” Output will be now as : Person:Peter class Person { String name; // Constructor public Person() { this.name = "Peter"; } public String getName() { return this.name; } }
  • 156. Object Initialization through Parameterized Constructor •We need to create a parameterized constructor in the class that can accept arguments. The class fields will be initialized with these parameters in the constructor. •When you create an object with arguments, the class constructor in java program will be automatically called and fields will be initialized.
  • 157. class Person { // properties of a person private String name; private int Age; private String gender; // Constructor : initialize all class fields public Person(String name, int age, String gender) { this.name = name; this.Age = age; this.gender = gender; } public String getName() { return name; } public int getAge() { return Age; } public String getGender() { return gender; } }
  • 158. /* * Test objects initialization. */ public class Sample { public static void main(String[] args) { Person scott = new Person("Scott", 30, "M"); System.out.println("Name: " + scott.getName()); System.out.println("Age: " + scott.getAge()); System.out.println("Gender: " + scott.getName()); } }