0% found this document useful (0 votes)
4 views45 pages

Unit 1 Introduction to Java notes Jan 2025

Java is a high-level, object-oriented, and platform-independent programming language developed by Sun Microsystems in 1995. It has three editions: Java Standard Edition (JSE), Java Enterprise Edition (JEE), and Java Micro Edition (JME), each serving different application needs. Key features include simplicity, security, platform independence, and support for multithreading, while it also has advantages and disadvantages compared to other languages like C/C++.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
4 views45 pages

Unit 1 Introduction to Java notes Jan 2025

Java is a high-level, object-oriented, and platform-independent programming language developed by Sun Microsystems in 1995. It has three editions: Java Standard Edition (JSE), Java Enterprise Edition (JEE), and Java Micro Edition (JME), each serving different application needs. Key features include simplicity, security, platform independence, and support for multithreading, while it also has advantages and disadvantages compared to other languages like C/C++.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 45

Unit-1

What is Java?
o Java is a high-level, object-oriented, and platform-independent programming
language.
o Java was developed by Sun Microsystems in the year 1995. James Gosling is known
as the father of Java.
o Before Java, its name was Oak. Since Oak was already a registered company, so
James Gosling and his team changed the name from Oak to Java.

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: Standalone applications are also known as desktop


applications or window-based applications. Examples of standalone application are
Media player, antivirus, etc.
o Enterprise Applications: An application which is distributed in nature is called
enterprise applications.It has advantages like high-level security. Examples of
Enterprise Applications Online Banking Systems,Travel Booking and Reservation
Systems: etc
o Web Applications: An applications that run on the server is called web applications.
Examples of Web Applications are Social Media Platforms, E-commerce Platforms.
o Mobile Applications: It is a cross-platform to develop mobile applications which
run across smartphones. Examples of mobile applications are Mobile Games,
Location-Based Services, Educational and Learning Apps

Applications of JAVA
Java is currently used for

1. Desktop Applications such as acrobat reader, media player, antivirus, etc.


2. Web Applications such as irctc.co.in, javatpoint.com, etc.
3. Enterprise Applications such as banking applications.
4. Mobile
5. Embedded System
6. Smart Card
7. Robotics
8. Games, etc.

Features of Java
o Simple: Java is a simple language because its syntax is simple, clean, and easy to
understand. Complex concepts of C or C++ such as 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.
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 High Performance: Java is an interpreted language. Java enables high performance
with the use of the Just-In-Time compiler.
o Multi-threaded: Java also supports multi-threading. It means to handle more than
one job a time.
Components of Java
The programming environment of Java consists of 3 components mainly
 JDK
 JRE
 JVM
JDK(Java Development Kit)
 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.
 It physically exists. It contains JRE + development tools.
 The JDK contains a private Java Virtual Machine (JVM) and a few other resources such
as an interpreter/loader (java), a compiler (javac), an archiver (jar), a documentation
generator (Javadoc), etc. to complete the development of a Java Application.
What is JRE(Java Runtime Environment)? JRE
JRE is an acronym for Java Runtime Environment.
It is a software package that provides Java class libraries, JVM and components required
to run Java applications.
It contains a set of libraries + other files that JVM uses at runtime.

What is JVM?
JVM(Java Virtual Machine) is an abstract machine that enables you computer to run Java
program
When you run Java program, Java compiler first compilers your Java code to bytecode. Then,
the JVM translates byte code into machine code.

C/C++ vs Java

C/C++ uses compiler only. Java uses both compiler and interpreter.
C/C++ supports pointers. You can You can't write the pointer program in java.
write a pointer program in C++.

C/C++ supports structures and Java doesn't support structures and unions.
unions.

C/C++ doesn't have built-in Java has built-in thread support.


support for threads.

C/C++ supports header files Java does not support header files.It uses the import
keyword to include different classes
and methods.

C/C++ supports the goto statement Java doesn't support the goto statement

First Java Program | Hello World Example

class Simple{
public static void main(String
args[]){ System.out.println("Hello Java");
}
}

Save the above file as Simple.java. To


compile: javac Simple.java
To execute: java Simple Output:
Hello Java

Parameters used in First Java Program


 class keyword is used to declare a class in Java.
 public keyword is an access modifier that represents visibility. It means it is visible to all.
 static is a keyword. If we declare any method as static, it is known as the static
method.
The core advantage of the static method is that there is no need to create an object to
invoke the static method.
 void is the return type of the method. It means it doesn't return any value.
 main represents the starting point of the program.
 String[] args or String args[] is used for command line argument
 System.out.println() is used to print statement.

Advantages of Java:

 Platform-Independent: Java’s "Write Once, Run Anywhere" (WORA) feature allows programs to
run on any platform with a Java Virtual Machine (JVM).
 Object-Oriented: Promotes modular programming, making it easier to maintain and reuse code.
 Robust and Secure: Java manages memory well and has security features to prevent problems like
memory leaks and hacks.
 Multithreading: Allows efficient multitasking by running multiple threads simultaneously.

Disadvantages of Java:
 Slow Performance: Java is slower than C++ because it runs through the JVM.
 High Memory Use: Java needs more memory and resources because of its built-in libraries.
 Garbage collection:Java provides automatic garbage collection that cannot be controlled by the
programmer.
 Cost:Java programming language is a bit costly due to its higher processing and memory
requirements.

Java comments
The java comments are statements that are not executed by the compiler and interpreter. The comments
can be used to provide information or explanation about the variable, method, class or any statement.
Single-Line Comments

 Syntax: //
 Used for adding a comment on a single line.
 Everything after // on the same line is treated as a comment.

.Multi-Line Comments

 Syntax: /* */
 Used to comments multiple lines.
 Everything between /* and */ is treated as a comment.

Documentation Comments

 Syntax: /** */
 Used for writing documentation for methods, classes, or programs.

Java Tokens:Tokens are the building blocks of a Java program, and they are processed by the compiler
The java has various types of tokens as follows
Identifier
Keywords
Separators(delimiters)
Constants
Variables
Operators
Java Identifiers:
All Java components require names. Names used for classes, variables and methods are
called identifiers. In Java, there are several points to remember about identifiers.
They are as follows:
All identifiers should begin with a letter (A to Z or a to z), or an underscore (_)or $.
After the first character, identifiers can have any combination of characters. A keyword
cannot be used as an identifier.
“Most importantly identifiers are case sensitive”.

Java Keywords
Java keywords are also known as reserved words.These are predefined words by Java so they cannot
be used as a variable or object name or class name.
Ex:boolean,break,if,else,while,public,private,protected etc
Separators (Delimiters)

 Seperators are symbols used to separate code elements in Java.


 Examples:
{}, (), [], ;, ,, ..

Constants
Any fixed value that does not change during the execution of a program is known as
constant.

 Integer Constant: Fixed whole numbers like 25 (e.g., int age = 25;).
 Real Constant: Fixed decimal numbers like 3.14 (e.g., double pi = 3.14;).
 Character Constant: Single characters like 'A' (e.g., char grade = 'A';).
 String Constant: Text in double quotes like "Hello" (e.g., String message = "Hello";).

Data Types in Java


Data types specify the different sizes and values that can be stored in the variable. There are
two types
1. Primitive data types: The primitive data types include boolean, char, byte, short, int, long,
float and double.

There are 8 types of primitive data types:

Type Default Size

boolean false 1 byte

char '\u0000' 2 byte

byte 0 1 byte

short 0 2 byte

int 0 4 byte

long 0 8 byte

float 0.0 4 byte

double 0.0 8 byte

 Boolean - This group includes boolean. It can have only one of two possible values, true or false.
 Characters- This group includes char, which represents symbols in a character set, like letters and
numbers. char is a 16-bit type.
 Integers - This group includes byte, short, int, and long. All of these are signed, positive and negative
values.
 Floating-point numbers– They are also known as real numbers. This group includes float and
double, which represent single and double precision numbers, respectively.

Non-Primitive data types


The non-primitive data types include Strings, Arrays etc
String:
A string represents a sequence of characters for example "Javatpoint", "Hello world", etc.
String is the class of Java.
One of the ways to create a string and store a value in it is shown below:
Example: String str = "You're the best";

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

Declaring a Variable

 A variable is declared by specifying its data type and name.

dataType variableName;

Initializing a Variable

 Initialization means assigning a value to the variable.

Syntax:

variableName = value;

Example:

age = 25; // Assigning a value to the variable

Variable is a name of memory location.There are three types of variables in Java:

o local variable
o instance variable
o static variable
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.
Accessing of instance variable is done through object.
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.
Difference between local,instance and static variables

Example to understand the types of variables in java

Aspect Local Variables Instance Variables Static Variables

Instance variable A variable that is


declared inside a class declared as static and
Local variables declared
Declaration but outside a method, defined outside any
inside a method.
constructor or any method. It cannot be
block. local.

Initialized each time an Initialized only once at


A local variable must be
Initialization instance of the class is the start of the
initialized before use.
created. execution.

The local variable's


scope is restricted to
the procedure in which Its scope is throughout Its scope is throughout
Scope
it is defined the class definition. the class definition.
(throughout its
method).

Its lifetime is whenever Its lifetime is throughout Its lifetime is throughout


Lifetime
method is invoked. the object life. the program life.

A local variable must be


They can be called using They can be called using
Accessibility to initialized before you try
any of the object class name or using any
Objects to use it, else compiler
instances. of the object instances.
will complain.

Usage in Static It cannot be defined It is not declared as


It is declared as static.
Context with static keyword. static.
public class A
{
static int m=100;//static variable
int data=50;//instance variable
public static void main(String args[])
{
int n=90;//local variable
}}//end of class

Structure of Java Program


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

2. Package Declaration

The package declaration is optional. It is placed just after the documentation section.You
can create a package with any name. A package is a group of classes that are defined by a
name. It is declared as:
package package_name;

3. Import Statements

import keyword is used to import built-in and user-defined packages into java source file. So
that the class can refer to a class that is in another package by directly using its name.

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

5. Class Definition

In this section, we define the class without the class, we cannot create any Java program. A
Java program may conation more than one class definition. We use the class keyword to
define the class. It contains information about user-defined methods, variables, and constants.
Every Java program has at least one class that contains the main() method

6. Main Method Class

Every Java stand-alone program requires the main method as the starting point of the
program. This is an essential part of a Java program. There may be many classes in a Java
program, and only one class defines the main method.

Input and output statements in Java:


Java Input Statement
The Scanner class is used to get user input, and it is found in the java.util package.To use
the Scanner class, create an object of the class and use any of the available methods found in
the Scanner class documentation.
Methods of Scanner Class in Java
Below is a table listing the commonly used methods of the Scanner class in Java and their descriptions.
Method Description
nextBoolean() Reads a boolean value from the user.
nextByte() Reads a byte value from the user.
nextDouble() Reads a double value from the user.
nextFloat() Reads a float value from the user.
nextInt() Reads an integer value from the user.
nextLine() Reads a String value from the user.
nextLong() Reads a long value from the user.
nextShort() Reads a short value from the user.

Java output statements


The System.out stream, is used together with different methods to output values or print text
to the console:
Methods for Printing in Java
Below is a table listing the commonly used methods for printing in Java and their descriptions.

Method Description
print() Prints text or values to the console.
println() Prints text or values to the console,
followed by a new line.

Type Casting in Java


Type casting in Java is the process of converting a value from one data type to another. It is used when
you want to store a value of one type in a variable of another type.

Implicit Casting (Widening):

Widening conversion takes place when two data types are automatically converted.
This happens when:
The two data types are compatible.
When we assign a value of a smaller data type to a bigger data type.

Example:

int num = 10;

double result = num; // int to double (widening)

System.out.println(result); // Output: 10.0

Explicit casting(Narrowing):
Explicit casting is required when larger data types are converted to smaller data types, which may result
in data loss or loss of precision.This is useful for incompatible data types where automatic conversion
cannot be done.

Example

double num = 10.5;

int result = (int) num; // double to int (narrowing)

System.out.println(result); // Output: 10

Operators in Java

Operator in Java is a symbol that is used to perform operations.


There are many types of operators in Java which are given below:
o Unary Operator,
o Binary Operator
Arithmetic Operator,
Relational Operator,
Assignment Operator,
Logical Operator,
Bitwise Operator,
o Ternary Operator

 Java Unary Operator


The Java unary operators require only one operand.
Increment
The increment operator ( ++ ) is used to increment the value of the variable by 1. The
increment can be done in two ways:
• Prefix increment(pre increment):
In this method, the operator precedes the operand (e.g., ++a). The value of the operand will
be altered before it is used.
Example:
int a = 1;
int b = ++a; // b = 2
• Postfix increment(post increment)
In this method, the operator follows the operand (e.g., a++). The value operand will be
altered after it is used.
Example:
int a = 1;
int b = a++; // b = 1
int c = a; // c = 2
Decrement

The decrement operator ( -- ) is used to decrement the value of the variable by 1. The
decrement can be done in two ways:
• Prefix decrement(pre decrement)
In this method, the operator precedes the operand (e.g., --a). The value of the operand will be
altered before it is used.
Example:
int a = 1;
int b = --a; // b = 0
• Postfix decrement(post decrement)
In this method, the operator follows the operand (e.g., a- -). The value of the operand will be
altered after it is used.
Example:
int a = 1;
int b = a--; // b = 1
int c = a; // c = 0

 Java Binary Operator


The Java binary operators require two operand.
Java Arithmetic Operators
Java arithmetic operators are used to perform addition, subtraction, multiplication, and
division. They act as basic mathematical operations.
Assume integer variable A holds 10 and variable B holds 20, then
The Relational Operators
There are following relational operators supported by Java language.
Assume variable A holds 10 and variable B holds 20, then

Example
public class Test {
public static void main(String args[])
{ int a = 10;
int b = 20;
System.out.println("a == b = " + (a == b) );
System.out.println("a != b = " + (a != b) );
System.out.println("a > b = " + (a > b) );
System.out.println("a < b = " + (a < b) );
System.out.println("b >= a = " + (b >= a) );
System.out.println("b <= a = " + (b <= a) );
}
}
Output
a == b = false
a != b = true
a > b = false
a < b = true
b >= a = true
b <= a = false
Assignment Operators:Assignment operators are used to assign a value (or) an
expression(or) a value of a variable to another variable.
Syntax : variable name=expression (or) value (or) variable
Ex : x=10;
y=a+b;
z=p;

Compound assignment operator:


In Java, compound assignment operators let you perform an operation and assign the result
back to the variable in a single step.

Example
public class OperatorExample{
public static void main(String
args[]){ int a=10;
int b=20;
a+=4;//a=a+4 (a=10+4)
b-=4;//b=b-4 (b=20-4)
System.out.println(a);
System.out.println(b);

}}
Output: 14
16

The Logical Operators

Example
public class Test {
public static void main(String args[])
{ boolean a = true;
boolean b = false;
System.out.println("a && b = " + (a&&b));
System.out.println("a || b = " + (a||b) );
System.out.println("!(a && b) = " + !(a && b));
}
}
Output
a && b = false
a || b = true
!(a && b) = true
Bitwise Operators:
Bitwise operators are used to manipulate the data at bit level.

Operator Meaning

<< Left Shift


>> Right Shift
& Bitwise AND
| Bitwise OR
^ Bitwise XOR

Shift Operators
Java Left Shift Operator
The Java left shift operator << is used to shift all of the bits in a value to the left side of a
specified number of times.
Java Left Shift Operator Example
public class OperatorExample{
public static void main(String args[])
{ System.out.println(10<<2);
System.out.println(10<<3);
}}
Output:
40
80
Java Right Shift Operator
The Java right shift operator >> is used to move the value of the left operand to right by
the number of bits specified by the right operand.
Java Right Shift Operator Example
public OperatorExample{
public static void main(String
args[]){ System.out.println(10>>2);
}}
Output:
2

Bitwise AND operator &


The output of bitwise AND is 1 if the corresponding bits of two operands is 1. If either bit of
an operand is 0, the result of corresponding bit is evaluated to 0.
Bit Operation of 12 and 25
00001100
&00011001
00001000 = 8 (In decimal)

Bitwise OR operator |
The output of bitwise OR is 1 if at least one corresponding bit of two operands is 1. In
Programming, bitwise OR operator is denoted by |.
Bitwise OR Operation of 12 and 25
00001100
| 00011001
00011101 = 29 (In decimal)

Bitwise XOR (exclusive OR) operator ^


The result of bitwise XOR operator is 1 if the corresponding bits of two operands are
opposite. It is denoted by ^.
Bitwise XOR Operation of 12 and 25
00001100
| 00011001
00010101 = 21 (In decimal)

 Java Ternary Operator


Java Ternary operator is used as one line replacement for if-then-else statement and used a
lot in Java programming. It is the only conditional operator which takes three operands.
Example
public class OperatorExample{
public static void main(String args[]){ int
a=2;
int b=5;
int min=(a<b)?a:b; System.out.println(min);
}}
Output: 2

Precedence refers to the priority of operators. Operators with higher precedence are evaluated before those
with lower precedence. For example, in the expression 1 + 5 * 3, the multiplication operator * has higher
precedence than the addition operator +, so the expression is evaluated as 1 + (5 * 3), resulting in 16
Associativity determines the order of evaluation for operators with the same precedence. For instance both
* and / have the same precedence, and their associativity is left-to-right.
Ex:(8 / 2) * 4 = 4 * 4 = 16

Object-Oriented Programming (OOP) in Java is a fundamental concept that helps in designing and organizing
software.The OOPs concepts java are as follows:
1. Object
2. Class
3. Abstraction
4. Encapsulation
5. Inheritance
6. Polymorphism

a) Objects:
The Object is the real-time entity having some state and behaviour. In Java, Object is an
instance of the class having the instance variables like the state of the object and the methods
as the behaviour of the object. The object of a class can be created by using the new keyword
in Java Programming language.
Key points about object
1. An object is a real-world entity.
2. An object is a runtime entity.
3. The object is an entity which has state and behaviour.
4. The object is an instance of a class.
example
19
Car is a object which has state (name, color, model, number) and behaviour (speed, etc).
Creating the Object
Using the new keyword is the most popular way to create an object or instance of the class.
When we create an instance of the class by using the new keyword, it allocates memory for
the newly created object and also returns the reference of that object to that memory.
The syntax for creating an object is:

ClassName objectname= new ClassName();

Example: Student S1 = new Student();

Methods and objects


Methods are declared inside the body of the class immediately after the declaration
of instance variables.
Members of a class are accessible by objects depending upon their accessibility conditions. If the
members are private they cannot be accessed outside the class.To access class members we
must use the concerned “object” and the “dot”operator.

The general syntax is

objectname.variablename = value;
objectname.methodname(parameter-list);

Example:
s1.stdname=10;
 Here “s1” is the “object name” ,variable name is “stdname”.
s1.display( );
 “s1” object name and “display” is the method name.

b) Class
It is a template/Blueprint from which objects are created.
There are two types of class
 Pre-defined class
Some of the predefined classes in java are
 Object Class: Object class is the root of Java class hierarchy.
 Math Class: Math class is present in java.

20
 String Class: String class is present in java.
 System Class: System class is present in java.
 Scanner Class: Scanner class is present in java

 User defined class


A class which is created by java programmer is called user defined
class. Some of the user-defined classes are used in java i.e., car, furniture,
student.

Example
Class Student
{

------------------------ // data or fields or variables


// methods
}
Difference between object and class
Object Class
Class is a blueprint or template
Object is an instance of a class.
from which objects are created.
Object is a physical entity. Class is a logical entity.
Class is declared using class keyword e.g.
class Student
Object is created through new
keyword mainly e.g. {
Student s1=new Student();
}

Object is created many times as per requirement.


Class is declared once.
Object allocates memory when it is created. Class doesn't allocated memory when it is
created.

a) Data Abstraction
Data abstraction is the process of hiding certain details and showing only essential information to
the user. Abstraction can be achieved with either abstract classes or interfaces.

b) Data Encapsulation
Encapsulation in Java is a mechanism of wrapping the data (variables) and code acting on the
data (methods) together as a single unit is called as data encapsulation. In encapsulation, the
variables of a class will be hidden from other classes, and can be accessed only through the methods

21
of their current class.

c) Inheritance
Inheritance in Java is a mechanism in which one object acquires all the properties and behaviors
of a parent object is called as inheritance. 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.

d) Polymorphism
The term "polymorphism" means "many forms". In object-oriented programming, polymorphism is
useful when you want to create multiple forms with the same name of a single entity. To implement
polymorphism in Java, we use two concepts method overloading and method overriding.

The method overloading is performed in the same class where we have multiple methods with the
same name but different parameters, whereas,method overriding requires the same method name and
parameters in both the parent and child classes. However, the child class can modify the method's
behavior.

Java Control Statements | Control Flow in Java


Java provides statements that can be used to control the flow of Java code. Such
22
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
 if statements
 if else statements
 else if ladder
 Nested if
 switch statement
2. Loop statements
 while loop
 do while loop
 for loop
 for each loop
3. Jump statements
 break statement
 continue statement

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.
if(condition)
{
statement 1; //executes when condition is true
}

23
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:
if(condition) {
statement 1; //executes when condition is true
}
else{
statement 2; //executes when condition is false
}
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.
if(condition 1) {
statement 1; //executes when condition 1 is true
}
else if(condition 2) {
statement 2; //executes when condition 2 is true
}
else {
statement 2; //executes when all the conditions are false
}

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.
if(condition 1) {

24
statement 1; //executes when condition 1 is true
if(condition 2) {
statement 2; //executes when condition 2 is true
}
else{
statement 2; //executes when condition 2 is false
}
}

5. 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 ifelse-if statements. It also enhances the
readability of the program.
The syntax to use the switch statement is given below.
switch (expression){
case value1:
statement1;
break;
.
.
.
case valueN:
statementN;
break; default:
default statement;
}

Loop Statements
In programming, sometimes we need to execute the block of code repeatedly while some
condition evaluates to true.

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

Types of Loops
1. while loop
2. do-while loop
3. for loop
4. for each loop/Enhanced for loop

while Loop in java


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.
while(condition){
//looping statements
}

do-while loop in Java


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.
do
{
//statements
} while (condition);

for loop in Java


In Java, for loop is similar to C and C++. It enables us to initialize the loop variable, check
26
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.
The syntax of the do-while loop is given below.
for(initialization;condition;increment/decrement) {
//block of statements
}

for each loop/Enhanced for loop:


In Java, the for-each loop (also called the enhanced for loop) is used to iterate through
elements of arrays as well as collections like ArrayList, HashSet, etc.
for (type variableName : arrayName) {

// code block to be executed}

Example:
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};

for (String i : cars)

{System.out.println(i);}

Output:
Volvo
BMW
Ford
Mazda

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.

27
BreakExample.java
public class BreakExample {
public static void main(String[] args)
{
for(int i = 0; i<= 10; i++)

if(i==6)
{
break;
}
System.out.println(i);
}
}
}

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.
Consider the following example to understand the functioning of the continue statement in
Java.
public class ContinueExample { public
static void main(String[] args) { for(int i
= 0; i<= 10; i++) {
if(i==6)
{
continue;
}
System.out.println(i);
}
}
}

28
Java Methods
Java Methods are blocks of code that perform a specific task. A method allows us to reuse code,
improving both efficiency and organization. All methods in Java must belong to a class. The method
is executed only when we call or invoke it.

Types of Method
There are two types of methods in Java:

o Predefined Method
o User-defined Method

Predefined Method

In Java, predefined methods are the method that is already defined in the Java class libraries is
known as predefined methods. It is also known as the standard library method or built- in
method. We can directly use these methods just by calling them in the program at any point.
Some pre-defined methods are length(), equals(), compareTo(), sqrt(), etc.

User-defined Method

The method written by the user or programmer is known as a user-defined method. These
methods are modified according to the requirement.

Syntax:

<access_modifier> <return_type> <method_name>( list_of_parameters)


{
//body
}

29
In general, method declarations has five components :
1. Modifier: It defines the access type of the method i.e. from where it can be accessed in your
application. In Java, there 4 types of access specifiers.
 public: It is accessible in all classes in your application.
 protected: It is accessible within the class in which it is defined and in its subclasses.
 private: It is accessible only within the class in which it is defined.
 default: It is declared/defined without using any modifier. It is accessible within the same class
and package within which its class is defined.
2. Return Type: Return type is a data type that the method returns.
3. Method Name: It is a unique name that is used to define the name of a method.
4. Parameter List: It is the list of parameters separated by a comma and enclosed in the pair of
parentheses. It contains the data type and variable name. If the method has no parameter, left the
parentheses blank.

5. Method Body: It is a part of the method declaration. It contains all the actions to be
performed. It is enclosed within the pair of curly braces.

class Method
{
int add(int x,int y)
{
return x+y;
}
int sub(int x,int y)
{
return x-y;
}
}
class Method1
{
public static void main(String args[])
{
Method m=new Method(); System.out.println(m.add(3,4));
System.out.println(m.sub(5,7));
}
}
30
Output:
7
-2

Method Overloading in Java


If a class has multiple methods having same name but different in parameters, it is known
as Method Overloading

Different ways to overload the method


There are two ways to overload the method in java
1. By changing number of arguments
2. By changing the data type
1) Method Overloading: changing no. of arguments
In this example, we have created two methods, first add() method performs addition of two
numbers and second add method performs addition of three numbers.
In this example, we are creating static methods so that we don't need to create instance for
calling methods.
class Adder{
int add(int a,int b){return a+b;}
int add(int a,int b,int c){return a+b+c;}
}
class TestOverloading1{
public static void main(String[]
args){ Adder a=new Adder();
System.out.println(a.add(11,11));
System.out.println(a.add(11,11,11));
}}
Output: 22
33

2) Method Overloading: changing data type of arguments


In this example, we have created two methods that differs in data type. The first add method
receives two integer arguments and second add method receives two double arguments.
class Adder{

31
int add(int a, int b){return a+b;}
double add(double a, double b){return a+b;}
}
class TestOverloading2{
public static void main(String[]
args){ Adder a=new Adder();
System.out.println(a.add(11,11));
System.out.println(a.add(12.3,12.6));
}}
Output: 22

24.9
Math class:
The Math class in Java is a built-in class that provides many mathematical functions, such as finding
square roots, powers, absolute values, maximum, minimum, trigonometric functions, and more. It is part
of the java.lang package
Math Class Methods in Java
Method Description Example
Math.abs(x) Returns the absolute Math.abs(-5) → 5
(positive) value of x
Math.sqrt(x) Returns the square root of x Math.sqrt(16) → 4.0
Math.pow(x, y) Returns x raised to the power Math.pow(2, 3) → 8.0
y
Math.max(x, y) Returns the larger value Math.max(10, 20) → 20
between x and y
Math.min(x, y) Returns the smaller value Math.min(10, 20) → 10
between x and y
Math.round(x) Rounds x to the nearest whole Math.round(4.7) → 5
number
Math.floor(x) Rounds x down to the nearest Math.floor(4.9) → 4.0
integer
Math.ceil(x) Rounds x up to the nearest Math.ceil(4.1) → 5.0
integer

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

The general syntax of an array is datatype arrayName [arraySize];

Example: int num[5];

Types of array There are two types of an array

32
a) one Dimentional array
b) Two DImentional array

One Dimensional array:

The creation of an array may involve three steps:

a) Declaring the array


b) Creating memory locations
c) Putting values into the memory locations

a) Declaring the array:- Arrays in java may be declared in two forms:

Type1: The general syntax is Datatype arrayname[size];

Example: int a[10];

Type2: The general syntax is Datatype[size] arrayname; Example:

int[10] a;

b) Creating a memory locations: After declaring an array, we need to create it in the


memory . java allows us to create arrays using new operator.

After declaring an array, we need to create it in the memory . java allows us to create arrays
using new operator.

The general form of one-Dimentional array is data_type

arrayname[ ];

arrayname = new data_type[size];

Or

data_type arrayname[ ] = new data_type[size];

data_type: declares the type of elements to be stored in the array such as int, float, char or
double.

arrayname: is the name of the array which follows the rules of constructing an identifier name.

size: specifies the maximum number of elements that can be stored in the array. Example:

int a[ ] = new a[4]; 4 memory locations are reserved

33
C) Putting values into the memory locations (initialising values of 1D array)

The elements of an array can be initialized in the declaration itself. The general form of
initialisation is:

data_type arrayname[ ] = { list of values};

int a[ ] = {10,20,30,40,50}; the array “a” reserve 5 storage locations

Two Dimentional array:

Two Dimentional array: The group of logically related data items of same data type which
share a common name it contain two subscript. The general syntax is
Datatype arrayname[row][column];

The general syntax is Datatype arrayname[row][column];

Creation of two dimensional arrays The creation of an array may involve three steps:

a) Declaring the array


b) Creating memory locations
c) Putting values into the memory locations

a) ) Declaring the array:- Arrays in java may be declared in two forms:

Type1:
The general syntax is
Datatype arrayname[row][column];
Example:
int arrayname[3][3];
Type2:
The general syntax is
Datatype[row][column] arrayname;
Example:

int[4][4] arrayname;

b) ) Creating a memory locations

After declaring an array, we need to create it in the memory . java allows us to create arrays using
34
new operator.
The general form of one-Dimentional array is
data_type arrayname[row][column];

arrayname = new data_type[row][column];

data_type: declares the type of elements to be stored in the array such as int, float, char or double.
arrayname: is the name of the array which follows the rules of constructing an identifier name.

size: specifies the maximum number of elements that can be stored in the array.

C)) Putting values into the memory locations (initialising values of 2D array)
The elements of an array can be initialized in the declaration itself. The general form of initialization is:
data_type arrayname[ ][ ]= { list of values};
int arrayname[3][3] = {10,20,30,40,50,60,70,80,90};

Constructor
Every class has a constructor. If the constructor is not defined in the class, the Java
compiler builds a default constructor for that class. While a new object is created, at
least one constructor will be invoked. The main rule of constructors is that they should
have the same name as the class. A class can have more than one constructor.
Constructors are used for initializing new objects.

Rules for writing Constructor


1. Constructor(s) of a class must have same name as the class name in which it resides.
2. A constructor in Java cannot be abstract, final, static and synchronized.
3. Constructor does not contain return type.

Following is an example of a constructor Example:


public class student
{

public student()
{
// Constructor
}
public student(String name)
35
{
// This constructor has one parameter, name.
}
}
Types of Constructors
There are three type of constructor in Java:
1. No-argument constructor (Default contructor):
A constructor that has no parameter is known as default constructor. If the constructor is
not defined in a class, then compiler creates default constructor (with no arguments) for the
class.

2. Parameterized Constructor:
A constructor that has parameters is known as parameterized constructor.
// Java Program to illustrate calling of parameterized constructor.

class Student
{
String s;
int age;
Student(String str, int a)
{
s=str;
age=a;
System.out.println("name="+s);
System.out.println("age="+age);
}

public static void main(String args[])


{
Student ob=new Student("Aliya",21);
}
}
3. Copy constructor
In Java, a copy constructor is a special type of constructor that creates an object using another object o
f the same Java class. It returns a duplicate copy of an existing object of the class.

Note: It cannot be inherited by the subclasses. If we try to initialize a child class


object from a parent class reference, we face the casting problem when cloning
it with the copy constructor.
Example
class Student6
{
int id;
String name;
//constructor to initialize integer and string
Student6(int i,String n)
36
{
id = i;
name = n;
}
//constructor to initialize another object
Student6(Student6 s)
{
id = s.id;
name =s.name;
}
void display()
{
System.out.println(id+" "+name);
}
public static void main(String args[])
{
Student6 s1 = new Student6(111,"Karan");
Student6 s2 = new Student6(s1);
s1.display();
s2.display();
}
}
Output:
111 Karan
111 Karan

Constructor Overloading
Like methods, we can overload constructors for creating objects in different ways. Compiler differentiates
constructors on the basis of numbers of parameters, types of the parameters and order of the parameters.

// Java Program to illustrate constructor overloading


class Student
{
String s;
int age;
Student(String str, int a)
{
s=str;
age=a;
System.out.println("name="+s);
System.out.println("age="+age);
}
Student()
{
s="Sam";
age=21;
System.out.println("name="+s);
System.out.println("age="+age);
}

37
public static void main(String args[])
{
Student ob=new Student("Aliya",21);
Student ob1=new Student();
}
}

Finalizer :
Finalize is a method which is available in object super class. The purpose of the finalize() method is
to release the resources that is allocated by unused object, before removing unused object by garbage
collector.
The general syntax
Protected void finalize()
{
//finalization code here
}
Key points about finalize() method
1. It is invoked each time before the object is garbage collected.
2. This method can be used to perform cleanup processing.

Visibility Modifiers or 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.
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.
Simple table

38
Access within within outside package by outside
Modifier class package subclass only package
Private Yes No No No
Default Yes Yes No No
Protected Yes Yes Yes No
Public Yes Yes Yes Yes

Difference between Constructors & Methods


Constructors Methods
A Constructor is invoked when a object is A Method is invoked through method calls.
created using the keyword new.
A Constructor doesn’t have a return type. A Method must have a return type.
A Constructor’s name must be same as the A Method’s name can be anything.
name of the class.
A Constructor cannot be inherited by A Method can be inherited by subclasses.
subclasses.

Instance Method Static Methods


Instance methods are methods that require Static methods are the methods in Java that can
an object of its class to be created before it be called without creating an object of class.
can be called.
To invoke an instance method, we have to They are referenced by the class name itself or
create an Object of the class in which the reference to the Object of that class.
method is defined.
Static keyword is not used Static keyword is used

Inbuilt classes -String, Character, StringBuffer

String
In general, a string is a sequence of characters. However, in Java, a String is an object that represents
a sequence of characters. The String class is used to create string objects.

For example:
char[] ch={'j','a','v','a','t','p','o','i','n','t'};

String s=new String(ch);

Above code is same as: String s = "javatpoint";

There are two ways to create String object:


1. By string literal
2. By new keyword

1) String Literal
Java String literal is created by using double quotes. For Example:

39
String s="welcome";

2)By new keyword


The string can also be declared using new operator i.e. dynamically allocated. In case of
String are dynamically allocated they are assigned a new memory location in heap. This
string will not be added to String constant pool.
The general format is
String s=new string(“welcome”)

String :- Immutable (if you try to alter their value, another object is created).

Inbuilt classes like string(string classes)


Method Description Example
length() Returns the length (number of "Hello".length() → 5
characters) of the string.
charAt(index) Returns the character at the "Java".charAt(1) → 'a'
specified index.
toUpperCase() Converts all characters to "hello".toUpperCase() →
uppercase. "HELLO"
toLowerCase() Converts all characters to "HELLO".toLowerCase() →
lowercase. "hello"
concat(str) Joins two strings together. "Hello".concat(" World") →
"Hello World"
equals(str) Compares two strings (case- "java".equals("Java") → false
sensitive).
equalsIgnoreCase(str) Compares two strings "java".equalsIgnoreCase("Java")
(ignoring case). → true
substring(start, end) Extracts a portion of the "Programming".substring(0, 4)
string. → "Prog"

Inbuilt classes like character


Normally, when we work with characters, we use primitive data types char.
Example
char ch = 'a';
// an array of chars
char[] charArray ={ 'a', 'b', 'c', 'd', 'e' };
Following is the list of the important instance methods that all the subclasses of the
Character class implement −
Sr.No. Method & Description
isLetter()
1
Determines whether the specified char value is a letter.
40
isDigit()
2
Determines whether the specified char value is a digit.
isUpperCase()
3
Determines whether the specified char value is uppercase.
isLowerCase()
4
Determines whether the specified char value is lowercase.
toUpperCase()
5
Returns the uppercase form of the specified char value.
toLowerCase()
6
Returns the lowercase form of the specified char value.

String buffer
The java.lang.StringBuffer class is a thread-safe, mutable sequence of characters.
Following are the important points about StringBuffer −
 A string buffer is like a String, but can be modified.
 It contains some particular sequence of characters, but the length and
content of the sequence can be changed through certain method calls.
 They are safe for use by multiple threads.

StringBuffer str = new StringBuffer(“ContentWriter”);

Java StringBuffer Methods


 append()
This method will concatenate(joins) the string representation of any type of data to the end of
the StringBuffer object. append() method has several overloaded forms.
Example:
class appendclass
{
public static void main(String args[])
{
StringBuffer sb = new StringBuffer(“JVM”);
sb.append(“JDK”);
System.out.println(sb);
41
}
}

Output: JVMJDK

The string representation of each parameter is appended to StringBuffer object.

 reverse()

This method reverses the characters within a StringBuffer object.

public class Demo


{
public static void main(String[] args)
{
StringBuffer str = new StringBuffer("Hello");

str.reverse();

System.out.println(str);
}
}
Output: olleH

 insert()
Insert the character in given position of the string.

Example:
public class Demo
{
public static void main(String[] args)
{
StringBuffer str = new
StringBuffer("Hello");
str.insert(1,”Computer”);
System.out.println(str);
}
}
42
Output: HComputerello

43
Difference between string and stringBuffer

No. String StringBuffer

The StringBuffer class is mutable.


1) The String class is immutable.

String is slow and consumes more memory when StringBuffer is fast and consumes
2) we concatenate too many strings because every less memory when we concatenate
time it creates new instance. strings.
StringBuffer class is faster while
String class is slower while performing
3) performing concatenation
concatenation operation.
operation.
StringBuffer uses Heap memory
4) String class uses String constant pool.

this reference
There can be a lot of usage of Java this keyword. In Java, this is a reference variable that
refers to the current object.

Usage of Java this keyword


Here is given the usage of java this keyword.
1. this can be used to refer current class instance variable.
2. this can be used to invoke current class method (implicitly)
3. this() can be used to invoke current class constructor.
4. this can be passed as an argument in the method call.
5. this can be passed as argument in the constructor call.
6. this can be used to return the current class instance from the method. 44
File:

1. In Java, with the help of File Class, we can work with files. This File Class is inside the java.io package.
2. Java has several methods for creating, reading, updating, and deleting files.

File operations in Java

1. Create a File: In order to create a file in Java, you can use the createNewFile() method. If the file is
successfully created, it will return a Boolean value true and false if the file already exists.

2. Writing to a File Definition: To write to a file in Java, use the write() method from the Files class.
This method writes the specified bytes to the file. If the file already exists, its content is replaced.

3. Reading from a File Definition: To read content from a file in Java, use the readString() method
from the Files class. This method reads all content from the file into a String.

4. Deleting a File Definition: To delete a file in Java, use the delete() method from the File class.
This method returns true if the file is successfully deleted, and false if the file does not exist or
deletion fails.

Example

//write a java program using file.


import java.io.File;
import java.io.IOException;
public class CreateFileExample
{
public static void main(String[] args)
{ File file = new File("example.txt");
try {
boolean result = file.createNewFile();
System.out.println("File created: " + result);
}
catch (IOException e)
{
e.printStackTrace();
}
}
}

45

You might also like