0% found this document useful (0 votes)
1 views44 pages

4. 1 Java Unit 1 Notes

Uploaded by

ithod
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views44 pages

4. 1 Java Unit 1 Notes

Uploaded by

ithod
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

JAVA PROGRAMMING

UNIT-1
INTRODUCTION TO JAVA
HISTORY

James Gosling, Mike Sheridan, and Patrick Naughton initiated the Java language
project in June 1991. The small team of sun engineers called Green Team. Initially it
was designed for small, embedded systems in electronic appliances like set-top
[Link], it was called "Greentalk" by James Gosling, and the file extension was
.gt. After that, it was called Oak and was developed as a part of the Green [Link]
1995, Oak was renamed as "Java" because it was already a trademark by Oak
Technologies. In 1995, Time magazine called Java one of the Ten Best Products of
1995.

JDK 1.0 was released on January 23, 1996. After the first release of Java, there have
been many additional features added to the language. Now Java is being used in
Windows applications, Web applications, enterprise applications, mobile
applications, cards, etc. Each new version adds new features in Java.

Basic concepts of OOPs are:


1. Class
2. Object
3. Inheritance
4. Polymorphism
5. Abstraction
6. Encapsulation
1) Class
The class is one of the Basic concepts of OOPs which is a group of similar entities. It is
only a logical component and not the physical entity. Lets understand this one of the
OOPs Concepts with example, if you had a class called “Expensive Cars” it could have
objects like Mercedes, BMW, Toyota, etc. Its properties(data) can be price or speed of
these cars. While the methods may be performed with these cars are driving, reverse,
braking etc.
2) Object
An object can be defined as an instance of a class, and there can be multiple instances of
a class in a program. An Object is one of the Java OOPs concepts which contains both the
data and the function, which operates on the data. For example – chair, bike, marker,
pen, table, car, etc.
3) Inheritance
Inheritance is one of the Basic Concepts of OOPs in which one object acquires the
properties and behaviors of the parent object. It’s creating a parent-child relationship
between two classes. It offers robust and natural mechanism for organizing and
structure of any software.
4) Polymorphism
Polymorphism refers to one of the OOPs concepts in Java which is the ability of a
variable, object or function to take on multiple forms. For example, in English, the
verb run has a different meaning if you use it with a laptop, a foot race, and business.
Here, we understand the meaning of run based on the other words used along with it.
The same also applied to Polymorphism.
5) Abstraction
Abstraction is one of the OOP Concepts in Java which is an act of representing essential
features without including background details. It is a technique of creating a new data
type that is suited for a specific application. Lets understand this one of the OOPs
Concepts with example, while driving a car, you do not have to be concerned with its
internal working. Here you just need to concern about parts like steering wheel, Gears,
accelerator, etc.
6) Encapsulation
Encapsulation is one of the best Java OOPs concepts of wrapping the data and code. In
this OOPs concept, the variables of a class are always hidden from other classes. It can
only be accessed using the methods of their current class. For example – in school, a
student cannot exist without a class.

Difference Between POP & OOP


Type Procedure Oriented Programming Object Oriented Programming

Divided Into In POP, program is divided into small In OOP, program is divided into parts
parts called functions. called objects.

Importance In POP,Importance is not given to In OOP, Importance is given to the


data but to functions as well as data rather than procedures or
sequence of actions to be done. functions because it works as a real
world.

Approach POP follows Top Down approach. OOP follows Bottom Up approach.

Access POP does not have any access OOP has access specifiers named
Specifiers specifier. Public, Private, Protected, etc.

Data Moving In POP, Data can move freely from In OOP, objects can move and
function to function in the system. communicate with each other
through member functions.

Expansion To add new data and function in POP OOP provides an easy way to add new
is not so easy. data and function.
Data Access In POP, Most function uses Global In OOP, data can not move easily from
data for sharing that can be accessed function to function,it can be kept
freely from function to function in public or private so we can control
the system. the access of data.

Data Hiding POP does not have any proper way OOP provides Data Hiding so
for hiding data so it is less secure. provides more security.

Overloading In POP, Overloading is not possible. In OOP, overloading is possible in the


form of Function Overloading and
Operator Overloading.

Examples Example of POP are : C, VB, Example of OOP are : C++, JAVA,
FORTRAN, Pascal. [Link], C#.NET.

Applications of OOPs:
 Real-Time System design: Real-time system inherits complexities and makes it
difficult to build them. OOP techniques make it easier to handle those complexities.
 Hypertext and Hypermedia: Hypertext is similar to regular text as it can be stored,
searched, and edited easily. Hypermedia on the other hand is a superset of hypertext.
OOP also helps in laying the framework for hypertext and hypermedia.
 AI Expert System: These are computer application that is developed to solve complex
problems which are far beyond the human brain. OOP helps to develop such an AI
expert System
 Office automation System: These include formal as well as informal electronic
systems that primarily concerned with information sharing and communication to
and from people inside and outside the organization. OOP also help in making office
automation principle.
 Neural networking and parallel programming: It addresses the problem of
prediction and approximation of complex-time varying systems. OOP simplifies the
entire process by simplifying the approximation and prediction ability of the network.
 Stimulation and modeling system: It is difficult to model complex systems due to
varying specifications of variables. Stimulating complex systems require modeling and
understanding interaction explicitly. OOP provides an appropriate approach for
simplifying these complex models.
 Object-oriented database: The databases try to maintain a direct correspondence
between the real world and database object in order to let the object retain it identity
and integrity.
 Client-server system: Object-oriented client-server system provides the IT
infrastructure creating object-oriented server internet(OCSI) applications.
 CIM/CAD/CAM systems: OOP can also be used in manufacturing and designing
applications as it allows people to reduce the efforts involved. For instance, it can be
used while designing blueprints and flowcharts. So it makes it possible to produce
these flowcharts and blueprint accurately.
JAVA FEATURES

Simple

Java is very easy to learn, and its syntax is simple, clean and easy to understand. According
to Sun Microsystem, Java language is a simple programming language because:
o Java syntax is based on C++ (so easier for programmers to learn it after C++).
o Java has removed many complicated and rarely-used features, for example, explicit
pointers, operator overloading, etc.
o There is no need to remove unreferenced objects because there is an Automatic
Garbage Collection in Java.

Object-oriented

Java is an object-oriented programming language. Everything in Java is an object. Object-


oriented means we organize our software as a combination of different types of objects
that incorporate both data and behavior.

Object-oriented programming (OOPs) is a methodology that simplifies software


development and maintenance by providing some rules.

Platform Independent
There are two types of platforms software-based and hardware-based. Java provides a
software-based platform.
The Java platform differs from most other platforms in the sense that it is a software-based
platform that runs on top of other hardware-based platforms. It has two components:
1. Runtime Environment
2. API(Application Programming Interface)

Java code can be executed on multiple platforms, for example, Windows, Linux, Sun Solaris,
Mac/OS, etc. Java code is compiled by the compiler and converted into bytecode. This
bytecode is a platform-independent code because it can be run on multiple platforms, i.e.,
Write Once and Run Anywhere (WORA).

Secured
Java is best known for its security. With Java, we can develop virus-free systems. Java is
secured because:
o No explicit pointer
o Java Programs run inside a virtual machine sandbox
o Classloader: Classloader in Java is a part of the Java Runtime Environment (JRE)
which is used to load Java classes into the Java Virtual Machine dynamically. It adds
security by separating the package for the classes of the local file system from those
that are imported from network sources.
o Bytecode Verifier: It checks the code fragments for illegal code that can violate
access rights to objects.
o Security Manager: It determines what resources a class can access such as reading
and writing to the local disk.

Java language provides these securities by default. Some security can also be provided by
an application developer explicitly through SSL, JAAS, Cryptography, etc.

Robust
The English mining of Robust is strong. Java is robust because:
o It uses strong memory management.
o There is a lack of pointers that avoids security problems.
o Java provides automatic garbage collection which runs on the Java Virtual Machine
to get rid of objects which are not being used by a Java application anymore.
o There are exception handling and the type checking mechanism in Java. All these
points make Java robust.

Architecture-neutral
Java is architecture neutral because there are no implementation dependent features, for
example, the size of primitive types is fixed.

In C programming, int data type occupies 2 bytes of memory for 32-bit architecture and 4
bytes of memory for 64-bit architecture. However, it occupies 4 bytes of memory for both
32 and 64-bit architectures in Java

Portable
Java is portable because it facilitates you to carry the Java bytecode to any platform. It
doesn't require any implementation.

High-performance
Java is faster than other traditional interpreted programming languages because Java
bytecode is "close" to native code. It is still a little bit slower than a compiled language (e.g.,
C++). Java is an interpreted language that is why it is slower than compiled languages, e.g.,
C, C++, etc.

Distributed
Java is distributed because it facilitates users to create distributed applications in Java. RMI
and EJB are used for creating distributed applications. This feature of Java makes us able to
access files by calling the methods from any machine on the internet.
Multi-threaded

A thread is like a separate program, executing concurrently. We can write Java programs
that deal with many tasks at once by defining multiple threads. The main advantage of
multi-threading is that it doesn't occupy memory for each thread. It shares a common
memory area. Threads are important for multi-media, Web applications, etc.

Dynamic
Java is a dynamic language. It supports the dynamic loading of classes. It means classes are
loaded on demand. It also supports functions from its native languages, i.e., C and C++. Java
supports dynamic compilation and automatic memory management (garbage collection).

JDK

JDK is an acronym for Java Development Kit. The Java Development Kit (JDK) is a software
development environment which is used to develop Java applications and applets. It
physically exists. It contains JRE + development tools.

JDK is an implementation of any one of the below given Java Platforms released by Oracle
Corporation:
o Standard Edition Java Platform
o Enterprise Edition Java Platform
o Micro Edition Java Platform

JRE

JRE is an acronym for Java Runtime Environment. It is also written as Java RTE. The Java
Runtime Environment is a set of software tools which are used for developing Java
applications. It is used to provide the runtime environment. It is the implementation of
JVM. It physically exists. It contains a set of libraries + other files that JVM uses at runtime.

JVM

JVM (Java Virtual Machine) is an abstract machine. It is called a virtual machine because it
doesn't physically exist. It is a specification that provides a runtime environment in which
Java bytecode can be executed. It can also run those programs which are written in other
languages and compiled to Java bytecode.

JVMs are available for many hardware and software platforms. JVM, JRE, and JDK are
platform dependent because the configuration of each OS is different from each other.
However, Java is platform independent. There are three notions of the
JVM: specification, implementation, and instance.
The JVM performs the following main tasks:
o Loads code
o Verifies code
o Executes code
o Provides runtime environment

PROGRAM STRUCTURE

Documentation Section

The documentation section is an important section but optional for a Java program. It
includes basic information about a Java program. The information includes the author's
name, date of creation, version, program name, company name, and description of
the program

Package Declaration

The package declaration is optional. It is placed just after the documentation section. In this
section, we declare the package name in which the class is placed. Note that there can
be only one package statement in a Java program. It must be defined before any class and
interface declaration.

Import Statements

We use the import keyword to import the class. It is written before the class declaration
and after the package statement. We use the import statement in two ways, either import a
specific class or import all classes of a particular package. In a Java program, we can use
multiple import statements.

Interface Section

It is an optional section. We can create an interface in this section if required. We use


the interface keyword to create an interface. An interface is a slightly different from the
class. It contains only constants and method declarations

Class Definition

It is vital part of a Java program. The class is a blueprint of a Java program. It contains
information about user-defined methods, variables, and constants. Every Java program has
at least one class that contains the main() method.

Creating And Executing a Java program

Step 1:Write a program on the notepad and save it with .java (for example, [Link])
extension.
1. class DemoFile
2. {
3. public static void main(String args[])
4. {
5. [Link]("Hello!");
6. [Link]("Java");
7. }
8. }
Step 2:Open Command Prompt.
Step 3:

9. Set the directory in which the .java file is saved. In our case, the .java file is saved in
C:\\demo.

10.

Step 4:

Use the following command to compile the Java program. It generates a .class file in the
same folder. It also shows an error if any
1. javac [Link]

Step 5:
Use the following command to run the Java program:
1. java DemoFile
Java Tokens

The Java compiler breaks the line of code into text (words) is called Java tokens. These are
the smallest element of the Java program. The Java compiler identified these words as
tokens. These tokens are separated by the delimiters. It is useful for compilers to detect
errors. Remember that the delimiters are not part of the Java tokens.
1. token <= identifier | keyword | separator | operator | literal | comment
Java Variables

A variable is a container which holds the value while the Java program is executed. A
variable is assigned with a data type.

Variable is a name of memory location. There are three types of variables in java: local,
instance and static.

There are two types of data types in Java: primitive and non-primitive.

Types of Variables

There are three types of variables in Java

1) Local Variable

A variable declared inside the body of the method is called local variable. You can use this
variable only within that method and the other methods in the class aren't even aware that
the variable exists.

A local variable cannot be defined with "static" keyword.

2) Instance Variable

A variable declared inside the class but outside the body of the method, is called an
instance variable. It is not declared as static
.

It is called an instance variable because its value is instance-specific and is not shared
among instances.

3) Static variable

A variable that is declared as static is called a static variable. It cannot be local. You can
create a single copy of the static variable and share it among all the instances of the class.
Memory allocation for static variables happens only once when the class is loaded in the
memory.
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.

Types of Array in java

There are two types of array.


o Single Dimensional Array
One Dimensional Array in java is always used with only one subscript([]). A one-
dimensional array behaves likes a list of variables. You can access the variables of an
array by using an index in square brackets preceded by the name of that array. Index value
should be an integer.
Steps:
 Declaration of Array
 Construction of Array
 Initialization of Array
public class MyExample
{
public static void main(String[] args)
{
// Declaration of Array
int[] number;
// Construction of Array with given size
// Here we are giving size 10 it mean it can hold 10 values of int type
number = new int[10];
// Initialization of Array
number[0] = 11;
number[1] = 22;
number[2] = 33;
number[3] = 44;
number[4] = 55;
number[5] = 66;
number[6] = 77;
number[7] = 88;
number[8] = 99;
number[9] = 100;
//Print the values from Array
for(int i = 0; i < [Link]; i++)
[Link](number[i]);
}
}
Output: 11
22
33
44
55
66
77
88
99
100

o Multidimensional Array
Multidimensional Arrays can be defined in simple words as array of arrays. Data in
multidimensional arrays are stored in tabular form (in row major order).
Syntax:
data_type[1st dimension][2nd dimension][]..[Nth
dimension] array_name = new data_type[size1][size2]….[sizeN];
where:
 data_type: Type of data to be stored in the array. For example: int, char, etc.
 dimension: The dimension of the array created.
For example: 1D, 2D, etc.
 array_name: Name of the array
 size1, size2, …, sizeN: Sizes of the dimensions respectively.
Examples:
Two dimensional array:
int[][] twoD_arr = new int[10][20];

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.

There are 8 types of primitive data types:


o boolean data type
o byte data type
o char data type
o short data type
o int data type
o long data type
o float data type
o 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

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:
 Arithmetic Operators
 Unary Operators
 Assignment Operator
 Relational Operators
 Logical Operators
 Ternary Operator
 Bitwise Operators
 Shift Operators
 instance of operator
 Arithmetic Operators: They are used to perform simple arithmetic operations on
primitive data types.
 * : Multiplication
 / : Division
 % : Modulo
 + : Addition
 – : Subtraction
 Unary Operators: Unary operators need only one operand. They are used to
increment, decrement or negate a value.
 – :Unary minus, used for negating the values.
 + :Unary plus, indicates positive value (numbers are positive without this,
however). It performs an automatic conversion to int when the type of its
operand is byte, char, or short. This is called unary numeric promotion.
 ++ :Increment operator, used for incrementing the value by 1. There are
two varieties of increment operator.
 Post-Increment: Value is first used for computing the result and
then incremented.
 Pre-Increment: Value is incremented first and then result is
computed.
-- : Decrement operator, used for decrementing the value by 1. There are
two varieties of decrement operator.
 Post-decrement : Value is first used for computing the result
and then decremented.
 Pre-Decrement : Value is decremented first and then result is
computed.
 Assignment Operator : ‘=’ Assignment operator is used to assign a value to any
variable. It has a right to left associativity, i.e value given on right hand side of
operator is assigned to the variable on the left and therefore right hand side value
must be declared before using it or should be a constant.
General format of assignment operator is, variable = value;.
 Relational Operators : These operators are used to check for relations like equality,
greater than, less than. They return boolean result after the comparison and are
extensively used in looping statements as well as conditional if else statements.
General format is,
variable relation_operator value
 Some of the relational operators are-
 ==, Equal to : returns true if left hand side is equal to right hand side.
 !=, Not Equal to : returns true if left hand side is not equal to right hand
side.
 <, less than : returns true if left hand side is less than right hand side.
 <=, less than or equal to : returns true if left hand side is less than or equal
to right hand side.
 >, Greater than : returns true if left hand side is greater than right hand
side.
 >=, Greater than or equal to: returns true if left hand side is greater than
or equal to right hand side.
 Logical Operators : These operators are used to perform “logical AND” and “logical
OR” operation, i.e. the function similar to AND gate and OR gate in digital electronics.
One thing to keep in mind is the second condition is not evaluated if the first one is
false, i.e. it has a short-circuiting effect. Used extensively to test for several conditions
for making a decision.
Conditional operators are-
 &&, Logical AND : returns true when both conditions are true.
 ||, Logical OR : returns true if at least one condition is true.
 ! : Logical not operator, used for inverting a boolean value
 Ternary operator : Ternary operator is a shorthand version of if-else statement. It
has three operands and hence the name ternary. General format is- condition ? if
true : if false
The above statement means that if the condition evaluates to true, then execute the
statements after the ‘?’ else execute the statements after the ‘:’.
 Bitwise Operators : These operators are used to perform manipulation of individual
bits of a number. They can be used with any of the integer types. They are used when
performing update and query operations of Binary indexed tree.
 &, Bitwise AND operator: returns bit by bit AND of input values.
 |, Bitwise OR operator: returns bit by bit OR of input values.
 ^, Bitwise XOR operator: returns bit by bit XOR of input values.
 ~, Bitwise Complement Operator: This is a unary operator which returns
the one’s complement representation of the input value, i.e. with all bits
inversed.
 Shift Operators : These operators are used to shift the bits of a number left or right
thereby multiplying or dividing the number by two respectively. They can be used
when we have to multiply or divide a number by two. General format- number
shift_op number_of_places_to_shift;
 <<, Left shift operator: shifts the bits of the number to the left and fills 0
on voids left as a result. Similar effect as of multiplying the number with
some power of two.
 >>, Signed Right shift operator: shifts the bits of the number to the right
and fills 0 on voids left as a result. The leftmost bit depends on the sign of
initial number. Similar effect as of dividing the number with some power of
two.
 >>>, Unsigned Right shift operator: shifts the bits of the number to the
right and fills 0 on voids left as a result. The leftmost bit is set to 0.
 instance of operator : Instance of operator is used for type checking. It can be used
to test if an object is an instance of a class, a subclass or an interface. General format-
object instance of class/subclass/interface

Expressions
Expressions perform the work of a Java program. Among other things, expressions are used
to compute and assign values to variables and to help control the execution flow of a
program. The job of an expression is two-fold: perform the computation indicated by the
elements of the expression and return some value.
Precedence and Associativity of Operators
Precedence and associative rules are used when dealing with hybrid equations involving
more than one type of operator. In such cases, these rules determine which part of the
equation to consider first as there can be many different valuations for the same
equation. The below table depicts the precedence of operators in decreasing order as
magnitude with the top representing the highest precedence and bottom shows the
lowest precedence.

Control Statements

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.

[Link]

[Link]
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. [Link]("x + y is greater than 20");
7. }
8. }
9. }

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

Consider the following example.

[Link]
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. [Link]("x + y is less than 10");
7. } else {
8. [Link]("x + y is greater than 20");
9. }
10. }
11. }

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

Consider the following example.

[Link]
1. public class Student {
2. public static void main(String[] args) {
3. String city = "Delhi";
4. if(city == "Meerut") {
5. [Link]("city is meerut");
6. }else if (city == "Noida") {
7. [Link]("city is noida");
8. }else if(city == "Agra") {
9. [Link]("city is agra");
10. }else {
11. [Link](city);
12. }
13. }
14. }

Output:
Delhi
4. 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. }

Consider the following example.

[Link]
1. public class Student {
2. public static void main(String[] args) {
3. String address = "Delhi, India";
4.
5. if([Link]("India")) {
6. if([Link]("Meerut")) {
7. [Link]("Your city is Meerut");
8. }else if([Link]("Noida")) {
9. [Link]("Your city is Noida");
10. }else {
11. [Link]([Link](",")[0]);
12. }
13. }else {
14. [Link]("You are not living in India");
15. }
16. }
17. }

Output:
Delhi

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:


o The case variables can be int, short, byte, char, or enumeration. String type is also
supported since version 7 of Java
o Cases cannot be duplicate
o Default statement is executed when any of the case doesn't match the value of
expression. It is optional.
o Break statement terminates the switch block when the condition is satisfied.
It is optional, if not used, next case is executed.
o 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. }

Consider the following example to understand the flow of the switch statement.

[Link]
1. public class Student implements Cloneable {
2. public static void main(String[] args) {
3. int num = 2;
4. switch (num){
5. case 0:
6. [Link]("number is 0");
7. break;
8. case 1:
9. [Link]("number is 1");
10. break;
11. default:
12. [Link](num);
13. }
14. }
15. }

Output:
2

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

The flow chart for the for-loop is given below.


Consider the following example to understand the proper functioning of the for loop in
java.

[Link]
1. public class Calculattion {
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. [Link]("The sum of first 10 natural numbers is " + sum);
9. }
10. }

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

Consider the following example to understand the functioning of the for-each loop in Java.
[Link]
1. public class Calculation {
2. public static void main(String[] args) {
3. // TODO Auto-generated method stub
4. String[] names = {"Java","C","C++","Python","JavaScript"};
5. [Link]("Printing the content of the array names:\n");
6. for(String name:names) {
7. [Link](name);
8. }
9. }
10. }

Output:
Printing the content of the array names:

Java
C
C++
Python
JavaScript

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.


1. while(condition){
2. //looping statements
3. }

The flow chart for the while loop is given in the following image.
Consider the following example.

Calculation .java
1. public class Calculation {
2. public static void main(String[] args) {
3. // TODO Auto-generated method stub
4. int i = 0;
5. [Link]("Printing the list of first 10 even numbers \n");
6. while(i<=10) {
7. [Link](i);
8. i = i + 2;
9. }
10. }
11. }

Output:
Printing the list of first 10 even numbers

0
2
4
6
8
10
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.
1. do
2. {
3. //statements
4. } while (condition);

The flow chart of the do-while loop is given in the following image.

Consider the following example to understand the functioning of the do-while loop in Java.

[Link]
1. public class Calculation {
2. public static void main(String[] args) {
3. // TODO Auto-generated method stub
4. int i = 0;
5. [Link]("Printing the list of first 10 even numbers \n");
6. do {
7. [Link](i);
8. i = i + 2;
9. }while(i<=10);
10. }
11. }
Output:
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.
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.
Type Casting/type conversion
Converting one primitive datatype into another is known as type casting (type conversion)
in Java. You can cast the primitive datatypes in two ways namely, Widening and,
Narrowing.
Widening − Converting a lower datatype to a higher datatype is known as widening. In this
case the casting/conversion is done automatically therefore, it is known as implicit type
casting. In this case both datatypes should be compatible with each other.

Example
public class WideningExample {
public static void main(String args[]){
char ch = 'C';
int i = ch;
[Link](i);
}
}
Output
Integer value of the given character: 67
Narrowing − Converting a higher datatype to a lower datatype is known as narrowing. In
this case the casting/conversion is not done automatically, you need to convert explicitly
using the cast operator “( )” explicitly. Therefore, it is known as explicit type casting. In this
case both datatypes need not be compatible with each other.

Example
import [Link];
public class NarrowingExample {
public static void main(String args[]){
Scanner sc = new Scanner([Link]);
[Link]("Enter an integer value: ");
int i = [Link]();
char ch = (char) i;
[Link]("Character value of the given integer: "+ch);
}
}
Output
Enter an integer value:
67
Character value of the given integer: C
CLASSES AND OBJECTS
Object -- an encapsulation of data along with functions that act upon that data.

An object consists of:


Name -- the variable name we give it
Member data -- the data that describes the object
Member functions -- behavior aspects of the object (functions related to the object itself)

Class -- a blueprint for objects. A class is a user-defined type that describes what a certain
type of object will look like. A class description consists of a declaration and a definition.
Usually these pieces are split into separate files.

An object is a single instance of a class. You can create many objects from the same class
type.

Class Declaration Format:


class <className>
{
public:
(public member data and functions go here)
private:
(private member data and functions go here)

};
Create Object

Java provides five ways to create an object.


o Using new Keyword
o Using clone() method
o Using newInstance() method of the Class class
o Using newInstance() method of the Constructor class
o Using Deserialization

The syntax for creating an object is:


1. ClassName object = new ClassName();

[Link]
1. public class CreateObjectExample1
2. {
3. void show()
4. {
5. [Link]("Welcome to java");
6. }
7. public static void main(String[] args)
8. {
9. //creating an object using new keyword
10. CreateObjectExample1 obj = new CreateObjectExample1();
11. //invoking method using the object
12. [Link]();
13. }
14. }

Output:
Welcome to java
Constructors in Java

In Java, a constructor is a block of codes similar to the method. It is called when an instance
of the class is created. At the time of calling constructor, memory for the object is allocated
in the memory.

It is a special type of method which is used to initialize the object.

Rules for creating Java constructor

There are two rules defined for the constructor.


1. Constructor name must be the same as its class name
2. A Constructor must have no explicit return type
3. A Java constructor cannot be abstract, static, final, and synchronized

Types of Java constructors

There are two types of constructors in Java:


1. Default constructor (no-arg constructor)
2. Parameterized constructor

Java Default Constructor

A constructor is called "Default Constructor" when it doesn't have any parameter.

Syntax of default constructor:


1. <class_name>(){}

Example of default constructor


In this example, we are creating the no-arg constructor in the Bike class. It will be invoked at the
time of object creation.
1. //Java Program to create and call a default constructor
2. class Bike{
3. //creating a default constructor
4. Bike(){[Link]("Bike is created");}
5. //main method
6. public static void main(String args[]){
7. //calling a default constructor
8. Bike b=new Bike1();
9. }
10. }

Output:
Bike is created

Java Parameterized Constructor

A constructor which has a specific number of parameters is called a parameterized


constructor.

Why use the parameterized constructor?

The parameterized constructor is used to provide different values to distinct objects.


However, you can provide the same values also.

Example of parameterized constructor

In this example, we have created the constructor of Student class that have two parameters.
We can have any number of parameters in the constructor.
1. //Java Program to demonstrate the use of the parameterized constructor.
2. class Student{
3. int id;
4. String name;
5. //creating a parameterized constructor
6. Student(int i,String n){
7. id = i;
8. name = n;
9. }
10. //method to display the values
11. void display(){[Link](id+" "+name);}
12.
13. public static void main(String args[]){
14. //creating objects and passing values
15. Student s1 = new Student(111,"Karan");
16. Student s2 = new Student(222,"Aryan");
17. //calling method to display the values of object
18. [Link]();
19. [Link]();
20. }
21. }

Output:
111 Karan
222 Aryan

Constructor Overloading in Java

In Java, a constructor is just like a method but without return type. It can also be
overloaded like Java methods.

Constructor overloading in Java is a technique of having more than one constructor with
different parameter lists. They are arranged in a way that each constructor performs a
different task. They are differentiated by the compiler by the number of parameters in the
list and their types.

Example of Constructor Overloading


1. //Java program to overload constructors
2. class Student{
3. int id;
4. String name;
5. int age;
6. //creating two arg constructor
7. Student(int i,String n){
8. id = i;
9. name = n;
10. }
11. //creating three arg constructor
12. Student(int i,String n,int a){
13. id = i;
14. name = n;
15. age=a;
16. }
17. void display(){[Link](id+" "+name+" "+age);}
18.
19. public static void main(String args[]){
20. Student s1 = new Student(111,"Karan");
21. Student s2 = new Student(222,"Aryan",25);
22. [Link]();
23. [Link]();
24. }
25. }

Output:
111 Karan 0
222 Aryan 25

Method
A method is a block of code or collection of statements or a set of code grouped together to
perform a certain task or operation. It is used to achieve the reusability of code.
Method Overloading in Java
Method Overloading is a feature that allows a class to have more than one method having
the same name, if their argument lists are different. It is similar to constructor
overloading in Java, that allows a class to have more than one constructor having different
argument lists.
There are two ways to overload the method in java.

Example 1: Overloading – Different Number of parameters in argument list

class DisplayOverloading
{
public void disp(char c)
{
[Link](c);
}
public void disp(char c, int num)
{
[Link](c + " "+num);
}
}
class Sample
{
public static void main(String args[])
{
DisplayOverloading obj = new DisplayOverloading();
[Link]('a');
[Link]('a',10);
}
}
Output:
a
a 10

Example 2: Overloading – Difference in data type of parameters


class DisplayOverloading2
{
public void disp(char c)
{
[Link](c);
}
public void disp(int c)
{
[Link](c );
}
}

class Sample2
{
public static void main(String args[])
{
DisplayOverloading2 obj = new DisplayOverloading2();
[Link]('a');
[Link](5);
}
}
Output:
a
5
Java Garbage Collection

In java, garbage means unreferenced objects.

Garbage Collection is process of reclaiming the runtime unused memory automatically. In


other words, it is a way to destroy the unused objects.

To do so, we were using free() function in C language and delete() in C++. But, in java it is
performed automatically. So, java provides better memory management.

Advantage of Garbage Collection


o It makes java memory efficient because garbage collector removes the
unreferenced objects from heap memory.
o It is automatically done by the garbage collector(a part of JVM) so we don't need to
make extra efforts.

finalize() method

The finalize() method is invoked each time before the object is garbage collected. This
method can be used to perform cleanup processing. This method is defined in Object class
as: protected void finalize(){}
gc() method

The gc() method is used to invoke the garbage collector to perform cleanup processing. The
gc() is found in System and Runtime classes. public static void gc(){}

Access Control
Access control is a mechanism, an attribute of encapsulation which restricts the access of
certain members of a class to specific parts of a program. Access to members of a class can
be controlled using the access modifiers. There are four access modifiers in Java. They are:

1. public
2. protected
3. default
4. private

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


Access within within outside package by outside
Modifier class package subclass only package

Private Y N N N

Default Y Y N N

Protected Y Y Y N

Public Y Y Y Y

Java static keyword


The static keyword in Java is used for memory management mainly. We can apply static
keyword with variables, methods, blocks and nested classes. The static keyword belongs to
the class than an instance of the class.
The static can be:
1. Variable (also known as a class variable)
2. Method (also known as a class method)
3. Block
4. Nested class

If you declare any variable as static, it is known as a static variable.


o The static variable can be used to refer to the common property of all objects (which
is not unique for each object), for example, the company name of employees, college
name of students, etc.
o The static variable gets memory only once in the class area at the time of class
loading.
Example of static variable
1. //Java Program to demonstrate the use of static variable
2. class Student{
3. int rollno;//instance variable
4. String name;
5. static String college ="ITS";//static variable
6. //constructor
7. Student(int r, String n){
8. rollno = r;
9. name = n;
10. }
11. //method to display the values
12. void display (){[Link](rollno+" "+name+" "+college);}
13. }
14. //Test class to show the values of objects
15. public class TestStaticVariable1{
16. public static void main(String args[]){
17. Student s1 = new Student(111,"Karan");
18. Student s2 = new Student(222,"Aryan");
19. //we can change the college of all objects by the single line of code
20. //[Link]="BBDIT";
21. [Link]();
22. [Link]();
23. }
24. }
Output:
111 Karan ITS
222 Aryan ITS

apply static keyword with any method, it is known as static method.


o A static method belongs to the class rather than the object of a class.
o A static method can be invoked without the need for creating an instance of a class.
A static method can access static data member and can change the value of it.
o
Example of static method
1. //Java Program to demonstrate the use of a static method.
2. class Student{
3. int rollno;
4. String name;
5. static String college = "ITS";
6. //static method to change the value of static variable
7. static void change(){
8. college = "BBDIT";
9. }
10. //constructor to initialize the variable
11. Student(int r, String n){
12. rollno = r;
13. name = n;
14. }
15. //method to display values
16. void display(){[Link](rollno+" "+name+" "+college);}
17. }
18. //Test class to create and display the values of object
19. public class TestStaticMethod{
20. public static void main(String args[]){
21. [Link]();//calling change method
22. //creating objects
23. Student s1 = new Student(111,"Karan");
24. Student s2 = new Student(222,"Aryan");
25. Student s3 = new Student(333,"Sonoo");
26. //calling display method
27. [Link]();
28. [Link]();
29. [Link]();
30. }
31. }

Output:111 Karan BBDIT


222 Aryan BBDIT
333 Sonoo BBDIT
Restrictions for the static method
There are two main restrictions for the static method. They are:
1. The static method can not use non static data member or call non-static method
directly.
2. this and super cannot be used in static context.
1. class A{
2. int a=40;//non static
3.
4. public static void main(String args[]){
5. [Link](a);
6. }
7. }
Output:Compile Time Error
Java static block
o Is used to initialize the static data member.
o It is executed before the main method at the time of classloading.
Example of static block
1. class A2{
2. static{[Link]("static block is invoked");}
3. public static void main(String args[]){
4. [Link]("Hello main");
5. }
6. }
Output:static block is invoked
Hello main

this keyword in Java


this keyword in Java is a reference variable that refers to the current object of a method
or a constructor. The main purpose of using this keyword in Java is to remove the
confusion between class attributes and parameters that have same names.
Following are various uses of ‘this’ keyword in Java:

 It can be used to refer instance variable of current class


 It can be used to invoke or initiate current class constructor
 It can be passed as an argument in the method call
 It can be passed as argument in the constructor call
 It can be used to return the current class instance
Example program
1. class Student{
2. int rollno;
3. String name;
4. float fee;
5. Student(int rollno,String name,float fee){
6. [Link]=rollno;
7. [Link]=name;
8. [Link]=fee;
9. }
10. void display(){[Link](rollno+" "+name+" "+fee);}
11. }
12.
13. class TestThis2{
14. public static void main(String args[]){
15. Student s1=new Student(111,"ankit",5000f);
16. Student s2=new Student(112,"sumit",6000f);
17. [Link]();
18. [Link]();
19. }}

Output:
111 ankit 5000.0
112 sumit 6000.0
Java Command Line Arguments

The java command-line argument is an argument i.e. passed at the time of running the java
program.

The arguments passed from the console can be received in the java program and it can be
used as an [Link], it provides a convenient way to check the behavior of the program for
the different values. You can pass N (1,2,3 and so on) numbers of arguments from the
command prompt.
Example: To Learn java Command Line Arguments
Step 1) Copy the following code into an editor.
class Demo{
public static void main(String args[]){
String[] b={"apple","orange"};
[Link]("Argument one = "+b[0]);
[Link]("Argument two = "+b[1]);
}
}
Step 2) Save & Compile the code
Step 3) Run the code as java Demo apple orange.
Step 4) You must get an output as below.

Example program 2:
1. class CommandLineExample{
2. public static void main(String args[]){
3. [Link]("Your first argument is: "+args[0]);
4. }
5. }
1. compile by > javac [Link]
2. run by > java CommandLineExample sana
Output: Your first argument is: sana
Nested Classes in Java
In Java, it is possible to define a class within another class, such classes are known
as nested classes. They enable you to logically group classes that are only used in one
place, thus this increases the use of encapsulation, and creates more readable and
maintainable code.
 The scope of a nested class is bounded by the scope of its enclosing class. Thus in
below example, class NestedClass does not exist independently of class OuterClass.
 A nested class has access to the members, including private members, of the class in
which it is nested. However, the reverse is not true i.e., the enclosing class does not
have access to the members of the nested class.
 A nested class is also a member of its enclosing class.
 As a member of its enclosing class, a nested class can be
declared private, public, protected, or package private(default).
Syntax:
class OuterClass
{
...
class NestedClass
{
...
}
}
Nested classes are divided into two types −
 Non-static nested classes − These are the non-static members of a class.
 Static nested classes − These are the static members of a class.

Inner Class

We use inner classes to logically group classes and interfaces in one place to be more
readable and maintainable.

Additionally, it can access all the members of the outer class, including private data
members and methods.

Syntax of Inner class


1. class Java_Outer_class{
2. //code
3. class Java_Inner_class{
4. //code
5. }
6. }

Example
class Outer_Demo {
int num;

// inner class
private class Inner_Demo {
public void print() {
[Link]("This is an inner class");
}
}

// Accessing he inner class from the method within


void display_Inner() {
Inner_Demo inner = new Inner_Demo();
[Link]();
}
}

public class My_class {

public static void main(String args[]) {


// Instantiating the outer class
Outer_Demo outer = new Outer_Demo();

// Accessing the display_Inner() method.


outer.display_Inner();
}
}
.
If you compile and execute the above program, you will get the following result −
Output
This is an inner class.

Method-local Inner Class


A method-local inner class can be instantiated only within the method where the inner
class is defined. The following program shows how to use a method-local inner class.
Example

public class Outerclass {


// instance method of the outer class
void my_Method() {
int num = 23;

// method-local inner class


class MethodInner_Demo {
public void print() {
[Link]("This is method inner class "+num);
}
} // end of inner class

// Accessing the inner class


MethodInner_Demo inner = new MethodInner_Demo();
[Link]();
}
public static void main(String args[]) {
Outerclass outer = new Outerclass();
outer.my_Method();
}
}
If you compile and execute the above program, you will get the following result −
Output
This is method inner class 23

Anonymous Inner Class


An inner class declared without a class name is known as an anonymous inner class. In
case of anonymous inner classes, we declare and instantiate them at the same time.
Syntax
AnonymousInner an_inner = new AnonymousInner() {
public void my_method() {
........
........
}
};
The following program shows how to override the method of a class using anonymous
inner class.
Example
abstract class AnonymousInner {
public abstract void mymethod();
}

public class Outer_class {

public static void main(String args[]) {


AnonymousInner inner = new AnonymousInner() {
public void mymethod() {
[Link]("This is an example of anonymous inner class");
}
};
[Link]();
}
}
If you compile and execute the above program, you will get the following result −
Output
This is an example of anonymous inner class
Java static nested class

A static class is a class that is created inside a class, is called a static nested class in Java. It
cannot access non-static data members and methods. It can be accessed by outer class
name.
o It can access static data members of the outer class, including private.
o The static nested class cannot access non-static (instance) data members or

Java static nested class example with instance method

[Link]
1. class TestOuter1{
2. static int data=30;
3. static class Inner{
4. void msg(){[Link]("data is "+data);}
5. }
6. public static void main(String args[]){
7. [Link] obj=new [Link]();
8. [Link]();
9. }
10. }

Output:
data is 30

You might also like