0% found this document useful (0 votes)
20 views

Notes Unit 2 Java

Uploaded by

Sannat Kumar
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views

Notes Unit 2 Java

Uploaded by

Sannat Kumar
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 50

Unit 2

Java Fundamentals

What is Java?
Java is a high-level, general-purpose, object-oriented, and secure programming
language developed by James Gosling at Sun Microsystems, Inc. in 1991. It is formally
known as OAK. In 1995, Sun Microsystem changed the name to Java. In 2009, Sun
Microsystem takeover by Oracle Corporation.

Editions of Java
Each edition of Java has different capabilities. There are three editions of Java:

o Java Standard Editions (JSE): It is used to create programs for a desktop


computer.
o Java Enterprise Edition (JEE): It is used to create large programs that run on the
server and manages heavy traffic and complex transactions.
o Java Micro Edition (JME): It is used to develop applications for small devices
such as set-top boxes, phone, and appliances.

Types of Java Applications


There are four types of Java applications that can be created using Java programming:

o Standalone Applications: Java standalone applications uses GUI components


such as AWT, Swing, and JavaFX. These components contain buttons, list, menu,
scroll panel, etc. It is also known as desktop alienations.
o Enterprise Applications: An application which is distributed in nature is called
enterprise applications.
o Web Applications: An applications that run on the server is called web
applications. We use JSP, Servlet, Spring, and Hibernate technologies for creating
web applications.
o Mobile Applications: Java ME is a cross-platform to develop mobile applications
which run across smartphones. Java is a platform for App Development in
Android.

Java Platform
Java Platform is a collection of programs. It helps to develop and run a program written
in the Java programming language. Java Platform includes an execution engine, a
compiler and set of libraries. Java is a platform-independent language.

Features of Java
o Simple: Java is a simple language because its syntax is simple, clean, and easy to
understand. Complex and ambiguous concepts of C++ are either eliminated or
re-implemented in Java. For example, pointer and operator overloading are not
used in Java.
o Object-Oriented: In Java, everything is in the form of the object. It means it has
some data and behavior. A program must have at least one class and object.
o Robust: Java makes an effort to check error at run time and compile time. It uses
a strong memory management system called garbage collector. Exception
handling and garbage collection features make it strong.
o Secure: Java is a secure programming language because it has no explicit pointer
and programs runs in the virtual machine. Java contains a security manager that
defines the access of Java classes.
o Platform-Independent: Java provides a guarantee that code writes once and run
anywhere. This byte code is platform-independent and can be run on any
machine.
o Portable: Java Byte code can be carried to any platform. No implementation-
dependent features. Everything related to storage is predefined, for example, the
size of primitive data types.
o High Performance: Java is an interpreted language. Java enables high
performance with the use of the Just-In-Time compiler.
o Distributed: Java also has networking facilities. It is designed for the distributed
environment of the internet because it supports TCP/IP protocol. It can run over
the internet. EJB and RMI are used to create a distributed system.
o Multi-threaded: Java also supports multi-threading. It means to handle more
than one job a time.

OOPs (Object Oriented Programming


System)
Object-oriented programming is a way of solving a complex problem by breaking them
into a small sub-problem. An object is a real-world entity. It is easier to develop a
program by using an object. In OOPs, we create programs using class and object in a
structured manner.

Class: A class is a template or blueprint or prototype that defines data members and
methods of an object. An object is the instance of the class. We can define a class by
using the class keyword.

Object: An object is a real-world entity that can be identified distinctly. For example, a
desk, a circle can be considered as objects. An object has a unique behavior, identity,
and state. Data fields with their current values represent the state of an object (also
known as its properties or attributes).

Abstraction: An abstraction is a method of hiding irrelevant information from the user.


For example, the driver only knows how to drive a car; there is no need to know how
does the car run. We can make a class abstract by using the keyword abstract. In Java,
we use abstract class and interface to achieve abstraction.

Encapsulation: An encapsulation is the process of binding data and functions into a


single unit. A class is an example of encapsulation. In Java, Java bean is a fully
encapsulated class.
Inheritance: Inheritance is the mechanism in which one class acquire all the features of
another class. We can achieve inheritance by using the extends keyword. It facilitates the
reusability of the code.

Polymorphism: The polymorphism is the ability to appear in many forms. In other


words, single action in different ways. For example, a boy in the classroom behaves like
a student, in house behaves like a son. There are two types of polymorphism: run time
polymorphism and compile-time polymorphism.

Literals in Java
In Java

, literal is a notation that represents a fixed value in the source code. In lexical analysis, literals
of a given type are generally known as tokens
. In this section, we will discuss the term literals in Java.

Literals
In Java, literals are the constant values that appear directly in the program. It can be
assigned directly to a variable. Java has various types of literals. The following figure
represents a literal.

Types of Literals in Java


There are the majorly four types of literals in Java:

1. Integer Literal
2. Character Literal
3. Boolean Literal
4. String Literal
Integer Literals

Integer literals are sequences of digits. There are three types of integer literals:

Decimal Integer: These are the set of numbers that consist of digits from 0 to 9. It may have a positive
(+) or negative (-) Note that between numbers commas and non-digit characters are not permitted. For
example, 5678, +657, -89, etc.

 Octal Integer: It is a combination of number have digits from 0 to 7 with a leading 0.


For example, 045, 026,
 Hexa-Decimal: The sequence of digits preceded by 0x or 0X is considered as
hexadecimal integers. It may also include a character from a to f or A to F that represents
numbers from 10 to 15, respectively. For example, 0xd, 0xf,

Binary Integer: Base 2, whose digits consists of the numbers 0 and 1 (you can create binary literals in
Java SE 7 and later). Prefix 0b represents the Binary system. For example, 0b11010.

Real Literals

The numbers that contain fractional parts are known as real literals. We can also represent real
literals in exponent form. For example, 879.90, 99E-3, etc.

Backslash Literals

Java supports some special backslash character literals known as backslash literals. They are
used in formatted output. For example:

\n: It is used for a new line

\t: It is used for horizontal tab


\b: It is used for blank space

\v: It is used for vertical tab

\a: It is used for a small beep

\r: It is used for carriage return

Character Literals

A character literal is expressed as a character or an escape sequence, enclosed in a single quote


('') mark. It is always a type of char. For example, 'a', '%', '\u000d', etc.

String Literals

String literal is a sequence of characters that is enclosed between double quotes ("") marks. It
may be alphabet, numbers, special characters, blank space, etc. For example, "Jack", "12345",
"\n", etc.

Floating Point Literals

The vales that contain decimal are floating literals. In Java, float and double primitive types fall
into floating-point literals. Keep in mind while dealing with floating-point literals.

Data Types in Java


Data types specify the different sizes and values that can be stored in the variable. There are two
types of data types in Java:

1. Primitive data types: The primitive data types include boolean, char, byte, short, int,
long, float and double.
2. Non-primitive data types: The non-primitive data types include Classes, 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.

 boolean data type


 byte data type
 char data type
 short data type
 int data type
 long data type
 float data type
 double data type

Data Type Default Value Default size


boolean false 1 bit
char '\u0000' 2 byte
byte 0 1 byte
short 0 2 byte
int 0 4 byte
long 0L 8 byte
float 0.0f 4 byte
double 0.0d 8 byte

Boolean Data Type


The Boolean data type is used to store only two possible values: true and false. This data type is
used for simple flags that track true/false conditions.

The Boolean data type specifies one bit of information, but its "size" can't be defined precisely.

Byte Data Type


The byte data type is an example of primitive data type. It isan 8-bit signed two's complement
integer. Its value-range lies between -128 to 127 (inclusive). Its minimum value is -128 and
maximum value is 127. Its default value is 0.

The byte data type is used to save memory in large arrays where the memory savings is most
required. It saves space because a byte is 4 times smaller than an integer. It can also be used in
place of "int" data type.

Short Data Type


The short data type is a 16-bit signed two's complement integer. Its value-range lies between -
32,768 to 32,767 (inclusive). Its minimum value is -32,768 and maximum value is 32,767. Its
default value is 0.

The short data type can also be used to save memory just like byte data type. A short data type is
2 times smaller than an integer.

Int Data Type


The int data type is a 32-bit signed two's complement integer. Its value-range lies between -
2,147,483,648 (-2^31) to 2,147,483,647 (2^31 -1) (inclusive). Its minimum value is -
2,147,483,648and maximum value is 2,147,483,647. Its default value is 0.

The int data type is generally used as a default data type for integral values unless if there is no
problem about memory.

Example:

1. int a = 100000, int b = -200000

Long Data Type

The long data type is a 64-bit two's complement integer. Its value-range lies between -
9,223,372,036,854,775,808(-2^63) to 9,223,372,036,854,775,807(2^63 -1)(inclusive). Its
minimum value is - 9,223,372,036,854,775,808and maximum value is
9,223,372,036,854,775,807. Its default value is 0. The long data type is used when you
need a range of values more than those provided by int.

1. long a = 100000L, long b = -200000L


Wrapper classes in Java
The wrapper class in Java provides the mechanism to convert primitive into object and object
into primitive.

Since J2SE 5.0, autoboxing and unboxing feature convert primitives into objects and objects
into primitives automatically. The automatic conversion of primitive into an object is known as
autoboxing and vice-versa unboxing.

Use of Wrapper classes in Java


Java is an object-oriented programming language, so we need to deal with objects many times
like in Collections, Serialization, Synchronization, etc. Let us see the different scenarios, where
we need to use the wrapper classes.

 Change the value in Method: Java supports only call by value. So, if we pass a
primitive value, it will not change the original value. But, if we convert the primitive
value in an object, it will change the original value.
 Serialization: We need to convert the objects into streams to perform the serialization. If
we have a primitive value, we can convert it in objects through the wrapper classes.
 Synchronization: Java synchronization works with objects in Multithreading.
 java.util package: The java.util package provides the utility classes to deal with objects.
 Collection Framework: Java collection framework works with objects only. All classes
of the collection framework (ArrayList, LinkedList, Vector, HashSet, LinkedHashSet,
TreeSet, PriorityQueue, ArrayDeque, etc.) deal with objects only.

The eight classes of the java.lang package are known as wrapper classes in Java. The list of eight
wrapper classes are given below:

Primitive Type Wrapper class


boolean Boolean
char Character
byte Byte
short Short
int Integer
long Long
float Float
double Double

Java Arrays
Normally, an array is a collection of similar type of elements which has contiguous memory
location.
Java array is an object which contains elements of a similar data type. Additionally, The
elements of an array are stored in a contiguous memory location. It is a data structure where we
store similar elements. We can store only a fixed set of elements in a Java array.

Array in Java is index-based, the first element of the array is stored at the 0th index, 2nd element
is stored on 1st index and so on.

Unlike C/C++, we can get the length of the array using the length member. In C/C++, we need to
use the sizeof operator.

In Java, array is an object of a dynamically generated class. Java array inherits the Object class,
and implements the Serializable as well as Cloneable interfaces. We can store primitive values or
objects in an array in Java. Like C/C++, we can also create single dimentional or
multidimentional arrays in Java.

Moreover, Java provides the feature of anonymous arrays which is not available in C/C++.

Advantages

 Code Optimization: It makes the code optimized, we can retrieve or sort the data
efficiently.
 Random access: We can get any data located at an index position.

Disadvantages

 Size Limit: We can store only the fixed size of elements in the array. It doesn't grow its
size at runtime. To solve this problem, collection framework is used in Java which grows
automatically.

Types of Array in java

There are two types of array.

 Single Dimensional Array


 Multidimensional Array
Single Dimensional Array in Java

Syntax to Declare an Array in Java

1. dataType[] arr; (or)


2. dataType []arr; (or)
3. dataType arr[];

Instantiation of an Array in Java

1. arrayRefVar=new datatype[size];

Example of Java Array

Let's see the simple example of java array, where we are going to declare, instantiate, initialize
and traverse an array.

1. //Java Program to illustrate how to declare, instantiate, initialize


2. //and traverse the Java array.
3. class Testarray{
4. public static void main(String args[]){
5. int a[]=new int[5];//declaration and instantiation
6. a[0]=10;//initialization
7. a[1]=20;
8. a[2]=70;
9. a[3]=40;
10. a[4]=50;
11. //traversing array
12. for(int i=0;i<a.length;i++)//length is the property of array
13. System.out.println(a[i]);
14. }}

Output
10
20
70
40
50

OPERATORS
Programming in Computer Science requires some arithmetical or logical operations. In such
circumstances, we need operators to perform these tasks. Thus, an Operator is basically a symbol
or token, which performs arithmetical or logical operations and gives us meaningful result. The
values involved in the operation are called Operands.

Here is a basic Pictorial representation of Operators.

Now, let us discuss the types of Operators available.

TYPES OF OPERATORS
There are three types of Operators in Java which are −

 Arithmetical Operators
 Relational Operators
 Logical Operators
 ARITHMETICAL OPERATORS

 The operators which are applied to perform arithmetical calculations in a program, are
known as Arithmetical operators. Some basic calculations like addition, subtraction,
multiplication, division, modulus are often used during programming. One can apply
arithmetic operators like +, -, *, / and % respectively to carry out these calculations. For
example, A + B, A – B, A % B are all examples of arithmetical operator usage.
 Do you know what Arithmetical Expressions are? A + B is considered an Arithmetical
Expression. Basically, an Arithmetical expression may contain variables, constants and
arithmetical operators together to produce a meaningful result. A + B, A – B, A % B are
all examples of arithmetical expressions.
 Now what happens if we assign an arithmetical expression to a variable? For example,
what do we call X = A + B? Is it an arithmetical expression or is it something else? Well
this is called an Arithmetical Statement. If an arithmetical expression is assigned to a
variable then it is known as Arithmetical Statement. Syntax of Arithmetical Statement is
− X = A + B, Y = A % B etc.
 Now we need to know who to write expression in Java Program.

EXPRESSIONS IN JAVA

When you write a program in Java, it is necessary to represent the arithmetical expressions into
Java expressions. Given below are few examples of how to illustrate a mathematical expression
in JAVA.

 Mathematical Expression: abc

Java Expression: a * b * c

 Mathematical Expression: ab + bc + ca

Java Expression: a * b + b * c + c * a

 Mathematical Expression: a2 + b2

Java Expression: a * a + b * b

 Mathematical Expression: (1/3)ab + (2/5)ba

Java Expression: 1.0/3.0 * a * b + 2.0/5.0 * b * a

Now there exist three different types of Arithmetical Operators. They are −

 Unary Operator
 Binary Operator
 Ternary Operator
Let us understand each of them individually.

UNARY OPERATOR

An Arithmetical operator, which is applied with a single operand is known as Unary Operator.
Example: +, -, ++, --, etc. Details of each types of operators are given below.

Unary (+) Operator

This operator is applied before the operand. It is just applied as a pointer to a variable which
results in the same value of a variable. Example: If a = 10, then +a will result in 10. If a = -10,
then +a will result in -10.

import java.io.*; // importing java.io package


public class UnaryTest { // class declaration
public static void main(String[] args) { // main function declaration

int number = 10; // initializing variable


System.out.println("Original Number = "+number); // displaying
original number
number = +number; // applying unary (+) operator
System.out.println("Updated Number = "+number); // displaying number
after applying unary (+) operator
}
}

Unary (-) Operator

This operator is applied before the operand, same as that of Unary (+) operator. Unary (-) reverts
the sign of an operand. Example: If a = 10, then –a will result in -10. If a = 0, then –a will result
in 0. If a = -10, then –a will result in 10.

Unary (++) Operator

This operator increases the value of an operand by one. Example: a = a + 1, by applying


increment operator it can be written as a++ or ++a.

Unary (--) Operator

This operator decreases the value of an operand by one. Example: a = a - 1, by applying


decrement operator it can be written as a-- or --a.

Prefix Operator (++a)


When increment or decrement operators are applied before the operant, it is known as prefix
operators. This operator works on the principle “CHANGE BEFORE ACTION”. It means the
value of the variable changes before the operation takes place.

Example − Increment Prefix Operator

a = 10;
a = ++a * 2;

Before the operation, value of a was 10. Then in the next arithmetical statement, ++a increases
a’s value by 1. So the new value of a is 11. Then the arithmetical operation a * 2 takes place,
after which value of a becomes 22.

Example: Decrement Prefix Operator

a = 10;
a = --a * 2;

Before the operation, value of a was 10. Then in the next arithmetical statement, --a decreases a’s
value by 1. So the new value of a is 9. Then the arithmetical operation a * 2 takes place, after
which value of a becomes 18.

Code − Prefix increment and decrement operator

import java.io.*; // importing java.io package


public class PrefixTest { // class declaration
public static void main(String[] args) { // main function declaration
int number = 10; // initializing variable
System.out.println("Original Number = "+number); // displaying original
number
++number; // applying increment perfix operator
System.out.println("Updated Number after increment = "+number); //
displaying number after increment
--number; // applying decrement prefix operator
System.out.println("Updated Number after decrement = "+number); //
displaying number after decrement
}
}

Postfix Operator (a++)

When increment or decrement operators are applied after the operant, it is known as postfix
operators. This operator works on the principle “CHANGE AFTER THE ACTION”. It means
the value of the variable changes after the operation takes place.

Example − Increment Postfix Operator

a = 10;
a = a++ * 2;

Before the operation, value of a was 10. Then the arithmetical operator a * 2 takes place, after
which value of a become 20. This value is then stored in a. Hence the new value of a becomes
20.

Example − Decrement Postfix Operator

a = 10;
a = a-- * 2;

Before the operation, value of a was 10. Then the arithmetical operator a * 2 takes place, after
which value of a become 20. This value is then stored in a. Hence the new value of a becomes
20.

BINARY OPERATOR

An arithmetic operator which deals with two operands, is known as Binary Arithmetic Operator.

Example

Addition (+): a = 10, b = 7, a + b = 17


Subtraction (-): a = 10, b = 7, a – b = 3
Multiplication (*): a = 10, b = 7, a * b = 70
Division (/): a = 10, b = 7, a / b = 1
Modulus (&): a = 10, b = 7, a & b = 3

TERNARY OPERATOR

Ternary Operators deal with three operands. It is also called conditional assignment statement
because the value assigned to a variable depends upon a logical expression.

Syntax: variable = (test expression)? Expression 1: Expression 2

Example: a = 10, b = 7;

Max = (a>b)? a:b;

Here, the value 10 is stored in Max as a>b is true.

Min = (b>a)? a:b;

Here, the value 7 is stored in Min as b>a is false.

Code: Ternary Operator Example


import java.io.*; // importing java.io package
public class TernaryTest { // class declaration
public static void main(String[] args) { // main function declaration
int a = 10, b = 7; // variable initialization
System.out.println("Value of a = "+a); // displaying value of a and b
System.out.println("Value of b = "+b);
int max = (a>b)? a:b; // here value of a will be stored in max as a>b is
true in this example
int min = (b>a)? a:b; // here value of b will be stored in min as b>a is
false in this example
System.out.println("Maximum of a and b = "+max);
System.out.println("Minimum of a and b = "+min);
}
}

Logical OPERATORS
Java uses logical operators AND (&&), OR (||) or NOT (!). These operators yield 1 or 0
depending upon the outcome of different expressions. The different types of logical operators
along with their format are as shown below −

Logical Operators Symbol Syntax


AND && (a > b) && (a > c)
OR || (a == b) || (a == c)
NOT ! !(a == b)

Precedence of logical operators is NOT (!), AND (&&) and OR (||) i.e., if a statement contains
all the three logical operators then NOT operator will perform first. Here are the details of each
logical operator.

Logical NOT (!)

Logical NOT operator is applied when you want to revert the outcome of an expression. It is a
unary operator because it uses a single operand.

Example

!(8 > 3) − False, because 8>3 is True, !(3 > 8) − True, because 3>8 is False.

public class LogicalNOT { // public class declaration


public static void main(String[] args) { // main function declaration
int a = 10, b = 5; // variable initialization
if (!(a == b)){ // if checking whether a is not equal to b
System.out.println("a is not equal to b"); // Printing output if a
and b aren't equal
} else {
}
}
}

Output

a is not equal to b

Logical OR (||)

This operator is used to combine two conditional expressions. It will result in true if either of two
conditions (expressions) is true otherwise false.

Example

(5 > 4) || (8 > 12) : True, because 5>4 is True, (5 < 4) || (8 > 12) : False, because both the
expressions are false.

public class LogicalOR { // public class declaration


public static void main(String[] args){ // main function declaration
int a = 10, b = 5, c = 13; // variable initialization
if ((a > b) || (a > c)){ // if checking whether a is maximum element or
not
System.out.println("Max Element is "+ a); // Printing output
}
else if ((b > a) || (b > c)) { // if checking whether b is maximum
element or not
System.out.println("Max Element is "+ b); // Printing output
}
else if ((c > a) || (c > b)) { // if checking whether c is maximum
element or not
System.out.println("Max Element is "+ c); // Printing output
}
}
}

Output

Max Element is 10

Logical AND (&&)

The AND operator results in true if both the expressions (comprising its operands) are true.

Example

(5 > 3) && (4 > 3) : True, because both the expressions are True, ( 5 > 3) && ( 3 > 5) : False,
because 3 > 5 is False.

public class LogicalAND { // public class declaration


public static void main(String[] args){ // main function declaration
int a = 10, b = 5, c = 13; // variable initialization
if ((a > b) && (a > c)){ // if checking whether a is maximum element or
not
System.out.println("Max Element is "+ a); // Printing output
}
else if ((b > a) && (b > c)) { // if checking whether b is maximum
element or not
System.out.println("Max Element is "+ b); // Printing output
}
else if ((c > a) && (c > b)){ // if checking whether c is maximum
element or not
System.out.println("Max Element is "+ c); // Printing output
}
}
}

Output

Max Element is 13

Java Control Statements | Control Flow 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


o if statements
o switch statement
2. Loop statements
o do while loop
o while loop
o for loop
o for-each loop
3. Jump statements
o break statement
o 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.

1) 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. 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

Let's understand the if-statements one by one.

1) 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. }

Consider the following example in which we have used the if statement in the java code.

Student.java

Student.java

1. public class Student {


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. }
9. }
10.
11.
12. Output:
13. x + y is greater than 20

2) 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. }

Student.java

1. public class Student {


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. }

x + y is greater than 20

3) 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. }

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.

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.

 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.

Student.java

1. public class Student implements Cloneable {


2. public static void main(String[] args) {
3. int num = 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. }

Loop Statements

In programming, sometimes we need to execute the block of code repeatedly while some
condition evaluates to true. However, 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

Let's understand the loop statements one by one.

Java 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. }
4. public class Calculattion {
5. public static void main(String[] args) {
6. // TODO Auto-generated method stub
7. int sum = 0;
8. for(int j = 1; j<=10; j++) {
9. sum = sum + j;
10. }
11. System.out.println("The sum of first 10 natural numbers is " + sum);
12. }
13. }

Output:

The sum of first 10 natural numbers is 55

Java 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. }
4. public class Calculation {
5. public static void main(String[] args) {
6. // TODO Auto-generated method stub
7. String[] names = {"Java","C","C++","Python","JavaScript"};
8. System.out.println("Printing the content of the array names:\n");
9. for(String name:names) {
10. System.out.println(name);
11. }
12. }
13. }

Java 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 is given below

Java 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.

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.
Java 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

Consider the following example in which we have used the break statement with the for loop.

BreakExample.java

BreakExample.java

1. public class BreakExample {


2.
3. public static void main(String[] args) {
4. // TODO Auto-generated method stub
5. for(int i = 0; i<= 10; i++) {
6. System.out.println(i);
7. if(i==6) {
8. break;
9. }
10. }
11. }
12. }

Output:

0
1
2
3
4
5
6

Java 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.
Objects and Classes in Java
An object in Java is the physical as well as a logical entity, whereas, a class in Java is a logical entity only.

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.
For Example, Pen is an object. Its name is Reynolds; color is white, known as its state. It is used
to write, so writing is its behavior.

An object is an instance of a class. A class is a template or blueprint from which objects are
created. So, an object is the instance(result) of a class.

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.

What is a 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.

File: Student.java

1. //Java Program to illustrate how to define a class and fields


2. //Defining a Student class.
3. class Student{
4. //defining fields
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. }

Output:

0
null

3 Ways to initialize object


There are 3 ways to initialize object in Java.

1. By reference variable
2. By method
3. By constructor
4. 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.

5. class Student{
6. int id;
7. String name;
8. }
9. class TestStudent2{
10. public static void main(String args[]){
11. Student s1=new Student();
12. s1.id=101;
13. s1.name="Sonoo";
14. System.out.println(s1.id+" "+s1.name);//printing members with a white space
15. }
16. }

Output:

101 Sonoo

Class Modifiers in java


There are two types of modifiers in Java: access modifiers and non-access modifiers.

The access modifiers in Java specifies the accessibility or scope of a field, method, constructor,
or class. We can change the access level of fields, constructors, methods, and class by applying
the access modifier on it.

There are four types of Java access modifiers:

1. Private: The access level of a private modifier is only within the class. It cannot be
accessed from outside the class.
2. Default: The access level of a default modifier is only within the package. It cannot be
accessed from outside the package. If you do not specify any access level, it will be the
default.
3. Protected: The access level of a protected modifier is within the package and outside the
package through child class. If you do not make the child class, it cannot be accessed
from outside the package.
4. Public: The access level of a public modifier is everywhere. It can be accessed from
within the class, outside the class, within the package and outside the package.

There are many non-access modifiers, such as static, abstract, synchronized, native, volatile,
transient, etc. Here, we are going to learn the access modifiers only.

Understanding Java Access Modifiers

Let's understand the access modifiers in Java by a simple table.

1) Private

The private access modifier is accessible only within the class.

Simple example of private access modifier


1. In this example, we have created two classes A and Simple. A class contains private data
member and private method. We are accessing these private members from outside the
class, so theclass A{
2. private int data=40;
3. private void msg(){System.out.println("Hello java");}
4. }
5.
6. public class Simple{
7. public static void main(String args[]){
8. A obj=new A();
9. System.out.println(obj.data);//Compile Time Error
10. obj.msg();//Compile Time Error
11. }
12. }

re is a compile-time error.

Role of Private Constructor

If you make any class constructor private, you cannot create the instance of that class from
outside the class. For example:

1. class A{
2. private A(){}//private constructor
3. void msg(){System.out.println("Hello java");}
4. }
5. public class Simple{
6. public static void main(String args[]){
7. A obj=new A();//Compile Time Error
8. }
9. }

2) Default

If you don't use any modifier, it is treated as default by default. The default modifier is
accessible only within package. It cannot be accessed from outside the package. It provides more
accessibility than private. But, it is more restrictive than protected, and public.

Example of default access modifier

In this example, we have created two packages pack and mypack. We are accessing the A class
from outside its package, since A class is not public, so it cannot be accessed from outside the
package.
In this example, we have created two packages pack and mypack. We are accessing the A class
from outside its package, since A class is not public, so it cannot be accessed from outside the
package.

1. //save by A.java
2. package pack;
3. class A{
4. void msg(){System.out.println("Hello");}
5. }

1. //save by B.java
2. package mypack;
3. import pack.*;
4. class B{
5. public static void main(String args[]){
6. A obj = new A();//Compile Time Error
7. obj.msg();//Compile Time Error
8. }
9. }

Java Anonymous inner class


Java anonymous inner class is an inner class without a name and for which only a single object is
created. An anonymous inner class can be useful when making an instance of an object with
certain "extras" such as overloading methods of a class or interface, without having to actually
subclass a class.

In simple words, a class that has no name is known as an anonymous inner class in Java. It
should be used if you have to override a method of class or interface. Java Anonymous inner
class can be created in two ways:

1. Class (may be abstract or concrete).


2. Interface

Java anonymous inner class example using class

TestAnonymousInner.java

1. abstract class Person{


2. abstract void eat();
3. }
4. class TestAnonymousInner{
5. public static void main(String args[]){
6. Person p=new Person(){
7. void eat(){System.out.println("nice fruits");}
8. };
9. p.eat();
10. }
11. }

Output:

nice fruits

1. A class is created, but its name is decided by the compiler, which extends the Person
class and provides the implementation of the eat() method.
2. An object of the Anonymous class is created that is referred to by 'p,' a reference variable
of Person type.

Internal class generated by the compiler

1. import java.io.PrintStream;
2. static class TestAnonymousInner$1 extends Person
3. {
4. TestAnonymousInner$1(){}
5. void eat()
6. {
7. System.out.println("nice fruits");
8. }
9. }

Java anonymous inner class example using interface

1. interface Eatable{
2. void eat();
3. }
4. class TestAnnonymousInner1{
5. public static void main(String args[]){
6. Eatable e=new Eatable(){
7. public void eat(){System.out.println("nice fruits");}
8. };
9. e.eat();
10. }
11. }

12.
13. Abstract class in Java
A class which is declared with the abstract keyword is known as an abstract class in
Java. It can have abstract and non-abstract methods (method with the body).
Abstraction in Java

Abstraction is a process of hiding the implementation details and showing only functionality to
the user.

Another way, it shows only essential things to the user and hides the internal details, for
example, sending SMS where you type the text and send the message. You don't know the
internal processing about the message delivery.

Abstraction lets you focus on what the object does instead of how it does it.

Ways to achieve Abstraction

There are two ways to achieve abstraction in java

1. Abstract class (0 to 100%)


2. Interface (100%)

Abstract class in Java

A class which is declared as abstract is known as an abstract class. It can have abstract and non-
abstract methods. It needs to be extended and its method implemented. It cannot be instantiated.

Points to Remember

 An abstract class must be declared with an abstract keyword.


 It can have abstract and non-abstract methods.
 It cannot be instantiated.
 It can have constructors and static methods also.
 It can have final methods which will force the subclass not to change the body of the method.
Inheritance in Java
Inheritance in Java is a mechanism in which one object acquires all the properties and
behaviors of a parent object. It is an important part of OOPs (Object Oriented programming
system).

The idea behind inheritance in Java is that you can create new classes that are built upon existing
classes. When you inherit from an existing class, you can reuse methods and fields of the parent
class. Moreover, you can add new methods and fields in your current class also.

Inheritance represents the IS-A relationship which is also known as a parent-child relationship.
Why use inheritance in java

 For Method Overriding (so runtime polymorphism can be achieved).


 For Code Reusability.
 Class: A class is a group of objects which have common properties. It is a template or
blueprint from which objects are created.
 Sub Class/Child Class: Subclass is a class which inherits the other class. It is also called
a derived class, extended class, or child class.
 Super Class/Parent Class: Superclass is the class from where a subclass inherits the
features. It is also called a base class or a parent class.
 Reusability: As the name specifies, reusability is a mechanism which facilitates you to
reuse the fields and methods of the existing class when you create a new class. You can
use the same fields and methods already defined in the previous class.

The syntax of Java Inheritance

1. class Subclass-name extends Superclass-name


2. {
3. //methods and fields
4. }

Java Inheritance Example


As displayed in the above figure, Programmer is the subclass and Employee is the superclass. The
relationship between the two classes is Programmer IS-A Employee. It means that Programmer is a type
of Employee.

1. class Employee{
2. float salary=40000;
3. }
4. class Programmer extends Employee{
5. int bonus=10000;
6. public static void main(String args[]){
7. Programmer p=new Programmer();
8. System.out.println("Programmer salary is:"+p.salary);
9. System.out.println("Bonus of Programmer is:"+p.bonus);
10. }
11. }

output

Programmer salary is:40000.0


Bonus of programmer is:10000

Types of inheritance in java


On the basis of class, there can be three types of inheritance in java: single, multilevel and
hierarchical.

In java programming, multiple and hybrid inheritance is supported through interface only. We
will learn about interfaces later.
Single Inheritance Example
When a class inherits another class, it is known as a single inheritance. In the example given
below, Dog class inherits the Animal class, so there is the single inheritance.
1. class Animal{
2. void eat(){System.out.println("eating...");}
3. }
4. class Dog extends Animal{
5. void bark(){System.out.println("barking...");}
6. }
7. class TestInheritance{
8. public static void main(String args[]){
9. Dog d=new Dog();
10. d.bark();
11. d.eat();
12. }}

Output:

barking...
eating.

Multilevel Inheritance Example


When there is a chain of inheritance, it is known as multilevel inheritance. As you can see in the
example given below, BabyDog class inherits the Dog class which again inherits the Animal
class, so there is a multilevel inheritance.

File: TestInheritance2.java

1. class Animal{
2. void eat(){System.out.println("eating...");}
3. }
4. class Dog extends Animal{
5. void bark(){System.out.println("barking...");}
6. }
7. class BabyDog extends Dog{
8. void weep(){System.out.println("weeping...");}
9. }
10. class TestInheritance2{
11. public static void main(String args[]){
12. BabyDog d=new BabyDog();
13. d.weep();
14. d.bark();
15. d.eat();
16. }}

Output:
weeping...
barking...
eating..

Hierarchical Inheritance Example


When two or more classes inherits a single class, it is known as hierarchical inheritance. In the
example given below, Dog and Cat classes inherits the Animal class, so there is hierarchical
inheritance.

Q) Why multiple inheritance is not supported in java?


To reduce the complexity and simplify the language, multiple inheritance is not supported in
java.

Consider a scenario where A, B, and C are three classes. The C class inherits A and B classes. If
A and B classes have the same method and you call it from child class object, there will be
ambiguity to call the method of A or B class.

Since compile-time errors are better than runtime errors, Java renders compile-time error if you
inherit 2 classes. So whether you have same method or different, there will be compile time
error.

Difference between throw and throws in Java


The throw and throws is the concept of exception handling where the throw keyword throw the
exception explicitly from a method or a block of code whereas the throws keyword is used in
signature of the method.

There are many differences between throw and throws keywords. A list of differences between
throw and throws are given below:

Sr.
Basis of Differences throw throws
no.
Java throw keyword is used Java throws keyword is used in
throw an exception the method signature to declare
1. Definition explicitly in the code, inside an exception which might be
the function or the block of thrown by the function while
code. the execution of the code.
2. Type of exception Using throw Using throws keyword, we
keyword, we can only can declare both checked
propagate unchecked exception and unchecked exceptions.
i.e., the checked exception However, the throws
cannot be propagated using keyword can be used to
throw only. propagate checked
exceptions only.
The throw keyword is The throws keyword is
3. Syntax followed by an instance of followed by class names of
Exception to be thrown. Exceptions to be thrown.
throw is used within the throws is used with the method
4. Declaration
method. signature.
We can declare multiple
We are allowed to throw exceptions using throws
only one exception at a time keyword that can be thrown by
5. Internal implementation
i.e. we cannot throw the method. For example,
multiple exceptions. main() throws IOException,
SQLException.

Java throw Example


TestThrow.java

1. public class TestThrow {


2. //defining a method
3. public static void checkNum(int num) {
4. if (num < 1) {
5. throw new ArithmeticException("\nNumber is negative, cannot calculate square")
;
6. }
7. else {
8. System.out.println("Square of " + num + " is " + (num*num));
9. }
10. }
11. //main method
12. public static void main(String[] args) {
13. TestThrow obj = new TestThrow();
14. obj.checkNum(-3);
15. System.out.println("Rest of the code..");
16. }
17. }

Output
Java Custom Exception
In Java, we can create our own exceptions that are derived classes of the Exception class.
Creating our own Exception is known as custom exception or user-defined exception. Basically,
Java custom exceptions are used to customize the exception according to user need.

Consider the example 1 in which InvalidAgeException class extends the Exception class.

Using the custom exception, we can have your own exception and message. Here, we have
passed a string to the constructor of superclass i.e. Exception class that can be obtained using
getMessage() method on the object we have created.

In this section, we will learn how custom exceptions are implemented and used in Java
programs.

Why use custom exceptions?


Java exceptions cover almost all the general type of exceptions that may occur in the
programming. However, we sometimes need to create custom exceptions.

Following are few of the reasons to use custom exceptions:

 To catch and provide specific treatment to a subset of existing Java exceptions.


 Business logic exceptions: These are the exceptions related to business logic and
workflow. It is useful for the application users or the developers to understand the exact
problem.

In order to create custom exception, we need to extend Exception class that belongs to java.lang
package.

Consider the following example, where we create a custom exception named


WrongFileNameException:

1. public class WrongFileNameException extends Exception {


2. public WrongFileNameException(String errorMessage) {
3. super(errorMessage);
4. }
5. }

java StringBuffer Class


Java StringBuffer class is used to create mutable (modifiable) String objects. The StringBuffer
class in Java is the same as String class except it is mutable i.e. it can be changed.

Important methods of StringBuffer class

Modifier and
Method Description
Type
It is used to append the specified string with this
public
string. The append() method is overloaded like
synchronized append(String s)
append(char), append(boolean), append(int),
StringBuffer
append(float), append(double) etc.
It is used to insert the specified string with this string
public
insert(int offset, String at the specified position. The insert() method is
synchronized
s) overloaded like insert(int, char), insert(int, boolean),
StringBuffer
insert(int, int), insert(int, float), insert(int, double) etc.
public
replace(int startIndex, It is used to replace the string from specified
synchronized
int endIndex, String str) startIndex and endIndex.
StringBuffer
public
delete(int startIndex, int It is used to delete the string from specified startIndex
synchronized
endIndex) and endIndex.
StringBuffer
public
synchronized reverse() is used to reverse the string.
StringBuffer
public int capacity() It is used to return the current capacity.
ensureCapacity(int It is used to ensure the capacity at least equal to the
public void
minimumCapacity) given minimum.
It is used to return the character at the specified
public char charAt(int index)
position.
It is used to return the length of the string i.e. total
public int length()
number of characters.
substring(int It is used to return the substring from the specified
public String
beginIndex) beginIndex.
substring(int
It is used to return the substring from the specified
public String beginIndex, int
beginIndex and endIndex.
endIndex)

StringTokenizer in Java
The java.util.StringTokenizer class allows you to break a String into tokens. It is simple way to
break a String. It is a legacy class of Java.

It doesn't provide the facility to differentiate numbers, quoted strings, identifiers etc. like
StreamTokenizer class. We will discuss about the StreamTokenizer class in I/O chapter.

In the StringTokenizer class, the delimiters can be provided at the time of creation or one by one
to the tokens.

Constructors of the StringTokenizer Class

There are 3 constructors defined in the StringTokenizer class.

Constructor Description
StringTokenizer(String str) It creates StringTokenizer with specified string.
StringTokenizer(String str,
It creates StringTokenizer with specified string and delimiter.
String delim)
It creates StringTokenizer with specified string, delimiter and
StringTokenizer(String str,
returnValue. If return value is true, delimiter characters are
String delim, boolean
considered to be tokens. If it is false, delimiter characters serve
returnValue)
to separate tokens.
Methods Description
boolean hasMoreTokens() It checks if there is more tokens available.
String nextToken() It returns the next token from the StringTokenizer object.
String nextToken(String delim) It returns the next token based on the delimiter.
boolean hasMoreElements() It is the same as hasMoreTokens() method.
Object nextElement() It is the same as nextToken() but its return type is Object.
int countTokens() It returns the total number of tokens.

Java Applet
Applet is a special type of program that is embedded in the webpage to generate the dynamic
content. It runs inside the browser and works at client side.

Advantage of Applet

There are many advantages of applet. They are as follows:

 It works at client side so less response time.


 Secured
 It can be executed by browsers running under many plateforms, including Linux,
Windows, Mac Os etc.

Drawback of Applet

 Plugin is required at client browser to execute applet.

Lifecycle of Java Applet

1. Applet is initialized.
2. Applet is started.
3. Applet is painted.
4. Applet is stopped.
5. Applet is destroyed.

Lifecycle methods for Applet:

The java.applet.Applet class 4 life cycle methods and java.awt.Component class provides 1 life
cycle methods for an applet.

java.applet.Applet class

For creating any applet java.applet.Applet class must be inherited. It provides 4 life cycle
methods of applet.

1. public void init(): is used to initialized the Applet. It is invoked only once.
2. public void start(): is invoked after the init() method or browser is maximized. It is used
to start the Applet.
3. public void stop(): is used to stop the Applet. It is invoked when Applet is stop or
browser is minimized.
4. public void destroy(): is used to destroy the Applet. It is invoked only once.

java.awt.Component class
The Component class provides 1 life cycle method of applet.

1. public void paint(Graphics g): is used to paint the Applet. It provides Graphics class
object that can be used for drawing oval, rectangle, arc etc.

Who is responsible to manage the life cycle of an applet?

Java Plug-in software.

How to run an Applet?

There are two ways to run an applet

1. By html file.
2. By appletViewer tool (for testing purpose).

You might also like