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

File 1743100200 4666 JavaUnit1-1

Java is a class-based, object-oriented programming language designed for cross-platform compatibility, allowing developers to 'write once, run anywhere' (WORA). Created in 1995 by James Gosling and others at Sun Microsystems, Java is known for its simplicity, security, and resilience, making it suitable for various applications. Key features include its object-oriented nature, portability, and a comprehensive version history, with the latest version being Java SE 22 released in March 2024.

Uploaded by

fungamerz787
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)
4 views54 pages

File 1743100200 4666 JavaUnit1-1

Java is a class-based, object-oriented programming language designed for cross-platform compatibility, allowing developers to 'write once, run anywhere' (WORA). Created in 1995 by James Gosling and others at Sun Microsystems, Java is known for its simplicity, security, and resilience, making it suitable for various applications. Key features include its object-oriented nature, portability, and a comprehensive version history, with the latest version being Java SE 22 released in March 2024.

Uploaded by

fungamerz787
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
You are on page 1/ 54

Introduction to Java

Java is a class-based, object-oriented programming language. The goal of this


language is to relieve developers of the burden of developing code for each platform.
This language is sometimes linked to the phrase "WORA," which stands for "write once,
run everywhere." This means that every time we compile a Java code, we obtain the byte
code (.class file), which may be run on other platforms that support Java without
requiring a new compilation. The Java language was created in 1995. Java is a widely
used computer language. Oracle owns it.
The development of desktop, mobile, and web applications is its primary use. The Java
language is renowned for its simplicity, security, and resilience.
● James Gosling, Mike Sheridan, and Patrick Naughton were the pioneer of Java
and initiated the Java language project in June 1991. The small team of
engineers called Green Team.
● Initially this language was created for tiny, embedded devices found in set-top
boxes and other electronic gadgets.
● James Gosling dubbed it "Green talk" at first, and the file extension was.gt.
● After that, name changed to Oak and was produced as a part of the Green
project.
● Why Oak? Oak is a symbol of strength and Many nations, including the United
States, France, Germany, Romania, and others, have made oak trees their
national trees because they are strong symbols.
● In 1995, Oak was changed to "Java" as Oak Technologies already owned the
trademark.
● Originally created by James Gosling at Sun Microsystems, a division of Oracle
Corporation, it was first made available in 1995.

Java Version History


1. JDK Alpha and Beta (1995)

2. JDK 1.0 (23rd Jan 1996)

3. JDK 1.1 (19th Feb 1997)

4. J2SE 1.2 (8th Dec 1998)

5. J2SE 1.3 (8th May 2000)

6. J2SE 1.4 (6th Feb 2002)

7. J2SE 5.0 (30th Sep 2004)

8. Java SE 6 (11th Dec 2006)

9. Java SE 7 (28th July 2011)

21
10. Java SE 8 (18th Mar 2014)

11. Java SE 9 (21st Sep 2017)

12. Java SE 10 (20th Mar 2018)

13. Java SE 11 (September 2018)

14. Java SE 12 (March 2019)

15. Java SE 13 (September 2019)

16. Java SE 14 (Mar 2020)

17. Java SE 15 (September 2020)

18. Java SE 16 (Mar 2021)

19. Java SE 17 (September 2021)

20. Java SE 18 (March 2022)

21. Java SE 19 (September 2022)

22. Java SE 20 (March 2023)

23. Java SE 21 (September 2023)

24. Java SE 22 (March 2024)


Features of Java
The features of Java are as under

1. Simple : Java's syntax is clear, basic, and easy to understand, making it a very
easy language to learn. According to Sun Microsystem, Java language is a
simple programming language because its grammar is based on C++ (thus
easier for programmers to learn it after C++).Many complex and little used
features, such as operator overloading and explicit pointers, have been
eliminated in Java.

2. Object-Oriented: A paradigm called object-oriented programming (OOPs) makes


software creation and maintenance easier by establishing certain guidelines.

Basic concepts of OOPs are:

21
1. Object

2. Class

3. Inheritance

4. Polymorphism

5. Abstraction

6. Encapsulation

3. Portable: Java allows you to take the Java byte code to any platform, which
makes it portable. No implementation is necessary.

4. Platform independent: 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).
5. Secured: Java's security is its most well-known feature. We can create virus-free systems
with Java. Java is safe because no explicit pointer and Java programs operate within a
sandbox virtual computer.

6. Distributed: It makes it easier for users to construct distributed applications, Java is


distributed. Distributed applications are created using RMI and EJB.

7. Dynamic: The language Java is dynamic. It allows classes to be loaded


dynamically. It indicates that classes are added as needed. Additionally, it
supports functions from C and C++, which are its native languages.

C++ vs Java
Comparison C++ Java
Index
Platform- C++ is platform specific. Java is not platform specific.

21
independent
Mainly used for The primary use of C++ is in Java is mostly used for programming
system programming.. applications. It is extensively utilized in
workplace, mobile, web-based, and Windows-
based applications.
Goto C++ is compatible with the The goto statement is not supported in Java.
goto statement
Multiple Multiple inheritance is supported Multiple inheritance through classes is not
inheritance in C++. supported in Java. Java interfaces can be used
to do this.
Operator In C++, operator overloading is In Java, operator overloading is not supported.
Overloading supported.
Pointers Pointers are supported in C++. C+ Java has limited support for pointers.
+ allows you to write pointer
programs.
Compiler and Only the compiler is used in C++. Java makes use of both an interpreter and a
Interpreter C++ is platform dependent since compiler. During compilation, Java source code
it is compiled and executed using is transformed into bytecode. At runtime, the
a compiler that transforms interpreter runs this bytecode and generates
source code into machine code. output. Java is platform-independent since it is
interpreted.
Call by Value Both call by reference and call by Java only allows call by value. Java doesn't
and Call by value are supported in C++. have call by reference.
reference
Structure and Unions and structures are Java does not support unions or structures
Union supported in C++
Thread Support C++ does not come with built-in Java supports threads by default.
thread support. It is dependent
on external libraries for thread
support.
JVM (Java Virtual Machine): The specification known as JVM makes it easier to create the
runtime environment where Java bytecode is executed. An instance of the JVM is
created each time the command java is used. The JVM makes it easier to define the
class file format, register set, memory area, and fatal error reporting. Keep in mind that
the JVM depends on the platform.
Java Development Kit (JDK): It is the whole Java Development Kit, which includes the
compiler, Java documentation, debuggers, JRE (Java Runtime Environment), and more.
To create, compile, and run a Java application, the JDK needs to be installed on the
computer.
Java Runtime Environment (JRE): The JDK includes JRE. The user can only launch the
program if the machine only has JRE installed. To put it another way, only the Java

21
command functions. A Java program cannot be compiled (the javac command will not
function).
The program Creation
The Java program can be written using a Text Editor (Notepad++ or NotePad or other
editors will also do the job.) or IDE (Eclipse, NetBeans, etc.).
FileName: TestClass.java
1. public class ExamClass
2. {
3. // main method
4. public static void main(String args [])
5. {
6. // print statement
7. System.out.println (" First Java Program.");
8. }
9. }
Write the above code and save the file with the name ExamClass. The file should have
the .java extension.
Type javac into the command prompt. The command that triggers the Java compiler to
start compiling the Java application is ExamClass.java. javac. The name of the file that
has to be compiled must be entered after the command. It is ExamClass.java in our
instance. Once you have typed, hit the enter key. A file called ExamClass.class
containing the byte code will be created if all goes according to plan. The compiler will
identify any errors in the program and prevent the creation of ExamClass.class
containing the byte code.
After the .class file is created, type java ExamClass to execute the program. The output of
the program will be displayed on the screen, which is mentioned below.

Description of Various Keywords Used in the Above Programs


main() method: The most important method of the program where the execution begins.
Therefore, all the logic must reside in the main method. If the main() method is not
containing the logic, then it will be there in some other method, but that method must be
invoked from the main() method directly or indirectly.
class: The keyword class is used for declaring class in the Java language.
void: it means that the function or method will not be returning anything.
System.out.println(): It is used to print statements, patterns, etc., on the console.
String argvs[]: It is a command line argument that is used for taking input.
public: It is an access specifier keyword. When it is applied to a method, then that method

21
is visible to all. Other access specifier keywords are, private, protected, and default.
import java.io.*: It means that all of the classes present in the package java.io is imported.
The java.io package facilitates the output and input streams for writing and reading
data to files. * means all. If one wants to import only a specific class, then replace the *
with the name of the class.
System.in: It is the input stream that is utilized for reading characters from the input-
giving device, which is usually a keyboard in our case.
static void main(): The static keyword tells that the method can be accessed without doing
the instantiation of the class.
System.out: As System.in is used for reading the characters, System.out is used to give
the result of the program on an output device such as the computer screen.
double, int: The different data types, int for the integers, double for double. Other data
types are char, boolean, float, etc.
println(): The method shows the texts on the console. The method prints the text to the
screen and then moves to the next line. For the next line, ln is used. If we do not want the
cursor to move to the next line, use the method print().

Introduction of Object Oriented Programming


Object-Oriented Programming or OOPs refers to languages that use objects in
programming. Object-oriented programming aims to implement real-world entities like
inheritance, hiding, polymorphism, etc in programming. The main aim of OOP is to bind
together the data and the functions that operate on them so that no other part of the
code can access this data except that function.
OOPs Concepts:
● Class
● Objects
● Polymorphism
● Inheritance
● Encapsulation
● Abstraction

1. Class
A class is a user-defined data type. It represents the set of properties or methods that are
common to all objects of one type. A class is like a blueprint for an object.
For Example: Consider the Class of Cars. There may be many cars with different names
and brands but all of them will share some common properties like all of them will have
4 wheels, Speed Limit, Mileage range, etc. So here, Car is the class, and wheels, speed
limits, mileage are their properties.

2. Object:

21
It is a basic unit of Object-Oriented Programming and represents the real-life entities. An
Object is an instance of a Class. When a class is defined, no memory is allocated but
when it is instantiated (i.e. an object is created) memory is allocated. An object has an
identity, state, and behavior. Each object contains data and code to manipulate the data.
For example “Dog” is a real-life Object, which has some characteristics like color, Breed,
Bark, Sleep, and Eats.

3. Polymorphism:
The word polymorphism means having many forms. In simple words, we can define
polymorphism as the ability of a message to be displayed in more than one form. For
example, A person at the same time can have different characteristics. Like a man at the
same time is a father, a husband, an employee. So the same person posses different
behavior in different situations. This is called polymorphism.

4. Inheritance:
The capability of a class to derive properties and characteristics from another class is

21
called Inheritance. When we write a class, we inherit properties from other classes. So
when we create a class, we do not need to write all the properties and functions again
and again, as these can be inherited from another class that possesses it. Inheritance
allows the user to reuse the code whenever possible and reduce its redundancy.

5. Encapsulation:
Encapsulation is defined as the wrapping up of data under a single unit. It is the
mechanism that binds together code and the data it manipulates, so it is also known
as data-hiding.

6. Data Abstraction:
Data abstraction refers to providing only essential information about the data to
the outside world, hiding the background details or implementation.
Consider a real-life example of a man driving a car. The man only knows that
pressing the accelerators will increase the speed of the car or applying brakes will

21
stop the car, but he does not know about how on pressing the accelerator the
speed is increasing, he does not know about the inner mechanism of the car or
the implementation of the accelerator, brakes, etc in the car.

Class Definition in Java


In object-oriented programming, a class is a basic building block. It can be defined as
template that describes the data and behaviour associated with the class instantiation.
A class can also be called a logical template to create the objects that share common
properties and methods.
For example, an Employee class may contain all the employee details in the form of
variables and methods. If the class is instantiated i.e. if an object of the class is created
(say e1), we can access all the methods or properties of the class.

Defining a Class in Java


Java provides a reserved keyword class to define a class. The keyword must be followed
by the class name. Inside the class, we declare methods and variables.
In general, class declaration includes the following in the order as it appears:
1. Modifiers: A class can be public or has default access.

2. class keyword: The class keyword is used to create a class.

3. Class name: The name must begin with an initial letter (capitalized by
convention).

4. Superclass (if any): The name of the class's parent (superclass), if any,
preceded by the keyword extends. A class can only extend (subclass) one parent.

5. Interfaces (if any): A comma-separated list of interfaces implemented by the


class, if any, preceded by the keyword implements. A class can implement more
than one interface.

6. Body: The class body surrounded by braces, { }.

Example 1:
Let's consider the following example to understand how to define a class in Java and
implement it with the object of class.
Calculate.java
// class definition
public class Calculate {

21
// instance variables
int a;
int b;
// constructor to instantiate
public Calculate (int x, int y) {
this.a = x;
this.b = y;
}
// method to add numbers
public int add () {
int res = a + b;
return res;
}
// method to subtract numbers
public int subtract () {
int res = a - b;
return res;
}
// method to multiply numbers
public int multiply () {
int res = a * b;
return res;
}
// method to divide numbers
public int divide () {
int res = a / b;
return res;
}
// main method
public static void main(String[] args) {
// creating object of Class
Calculate c1 = new Calculate(45, 4);

21
// calling the methods of Calculate class
System.out.println("Addition is :" + c1.add());
System.out.println("Subtraction is :" + c1.subtract());
System.out.println("Multiplication is :" + c1.multiply());
System.out.println("Division is :" + c1.divide());
}

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.
Every time an object is created using the new() keyword, at least one constructor is
called.

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

4. Used to initialize the objects.

5. In case of overloading constructor the name should be different

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.

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

//Java Program to create and call a default constructor


class Bike1
{
//creating a default constructor
Bike1()
{
System.out.println("Bike is created");
}
//main method
public static void main(String args[])
{
//calling a default constructor
Bike1 b=new Bike1();
}
}
Output: Bike is created

Java Parameterized Constructor


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

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.
//Java Program to demonstrate the use of the parameterized constructor.

21
class Student4{
int id;
String name;
//creating a parameterized constructor
Student4(int i,String n){
id = i;
name = n;
}
//method to display the values
void display(){System.out.println(id+" "+name);}

public static void main(String args[]){


//creating objects and passing values
Student4 s1 = new Student4(111,"Karan");
Student4 s2 = new Student4(222,"Aryan");
//calling method to display the values of object
s1.display();
s2.display();
}
}
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


//Java program to overload constructors

21
class Student5{
int id;
String name;
int age;
//creating two arg constructor
Student5(int i,String n){
id = i;
name = n;
}
//creating three arg constructor
Student5(int i,String n,int a){
id = i;
name = n;
age=a;
}
void display(){System.out.println(id+" "+name+" "+age);}

public static void main(String args[]){


Student5 s1 = new Student5(111,"Karan");
Student5 s2 = new Student5(222,"Aryan",25);
s1.display();
s2.display();
}
}

Output
111 Karan 0
222 Aryan 25

21
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

Method Signature: Every method has a method signature. It is a part of the method
declaration. It includes the method name and parameter list.
Access Specifier
There are four types of Java access modifiers:
1. Private: The access level of a private modifier is only within the class. It cannot
be accessed from outside the class.

2. Default: The access level of a default modifier is only within the package. It
cannot be accessed from outside the package. If you do not specify any access
level, it will be the default.

3. Protected: The access level of a protected modifier is within the package and
outside the package through child class. If you do not make the child class, it
cannot be accessed from outside the package.

4. Public: The access level of a public modifier is everywhere. It can be accessed

21
from within the class, outside the class, within the package and outside the package.
Return Type: Return type is a data type that the method returns
.
Method Name: It is a unique name that is used to define the name of a method name.
Parameter List: It is the list of parameters separated by a comma and enclosed in the
pair of parentheses.
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.

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. When we call any of the predefined methods in our program, a series of codes
related to the corresponding method runs in the background that is already stored in the
library.

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.
Public void show, public void display and so on.

Java static keyword


The static keyword in Java is mainly used for memory management. The static keyword
in Java is used to share the same variable or method of a given class. The users can
apply static keywords with variables, methods, blocks, and nested classes.
Note: To create a static member (block, variable, method, nested class), precede its
declaration with the keyword static.

Characteristics of static keyword:

Shared memory allocation: Static variables and methods are allocated memory space only

21
once during the execution of the program.
Accessible without object instantiation: Static members can be accessed without the need to
create an instance of the class
Associated with class, not objects: Static members are associated with the class, not with
individual objects.
Suppose there are 500 students in my college, now all instance data members will get
memory each time when the object is created. All students have its unique rollno and
name, so instance data member is good in such case. Here, "college" refers to the
common property of all objects. If we make it static, this field will get the memory only
once.
class Student
{
int rollno;
String name;
static String college ="ITS";//static variable
//constructor
Student(int r, String n)
{
rollno = r;
name = n;
}

void display ()
{
System.out.println(rollno+" "+name+" "+college);
}
}

public class TestStaticVariable1


{
public static void main(String args[])
{
Student s1 = new Student(111,"Karan");

21
Student s2 = new Student(222,"Aryan");
//we can change the college of all objects by the single line of code
//Student.college="BBDIT";
s1.display();
s2.display();
}
}

When a member is declared static, it can be accessed before any objects of its class are
created, and without reference to any object. For example, in the below java program, we
are accessing static method m1() without creating any object of the Test class.

class Test
{
// static method
static void m1()
{
System.out.println("from m1");
}
public static void main(String[] args)
{
// calling m1 without creating any object of class Test
m1();
}
}

Output:
From m1
final Keyword in Java
The final method in Java is used as a non-access modifier applicable only to a variable,
a method, or a class. It is used to restrict a user in Java.

21
Characteristics of final keyword in Java:
Final variables: When a variable is declared as final, its value cannot be changed once it
has been initialized.
Final methods: When a method is declared as final, it cannot be overridden by a subclass.
Final classes: When a class is declared as final, it cannot be extended by a subclass.
Initialization: Final variables must be initialized either at the time of declaration or in the
constructor of the class.
In Java, we cannot change the value of a final variable. For example,
class Main {
public static void main(String[] args)
{
// create a final variable
final int AGE = 32;
// try to change the final variable
AGE = 45;
System.out.println("Age: " + AGE);
}
}
OUTPUT:
ERROR!
/tmp/yyyEAaOvI5/Main.java:8: error: cannot assign a value to final variable AGE
AGE = 45;
^
1 error

21
Single-line Comments

Single-line comments start with two forward slashes (//).


Example:

// This is a comment

System.out.println("Hello World");

Java Multi-line Comments

Multi-line comments start with /* and ends with */.

Any text between /* and */ will be ignored by Java.

Example

/* The code below will print the words Hello World

to the screen, and it is amazing */

System.out.println("Hello World");

Data type in Java


CS – 16 Bits
IF – 32 Bits
DL – 64 Bits

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.
How to Initialize Variables in Java?
It can be perceived with the help of 3 components that are as follows:
● datatype: Type of data that can be stored in this variable.
● variable_name: Name given to the variable.
● value: It is the initial value stored in the variable.

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

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.

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.

Static variable
A variable that is declared as static is called a static variable. It cannot be local.

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:
o Unary Operator,

o Arithmetic Operator,

o Shift Operator,

o Relational Operator,

o Bitwise Operator,

o Logical Operator,

o Ternary Operator and

o Assignment Operator.

21
Java Operator Precedence
Operator Type Category Precedence

Unary postfix expr++ expr--

prefix ++expr --expr +expr -expr ~ !

Arithmetic multiplicative */%

additive +-

Shift shift << >> >>>

Relational comparison < > <= >= instanceof

equality == !=

Bitwise bitwise AND &

bitwise exclusive OR ^

bitwise inclusive OR |

Logical logical AND &&

logical OR ||

Ternary ternary ?:

Assignment assignment = += -= *= /= %= &= ^= |= <<= >>=


>>>=

public class OperatorExample{


public static void main(String args[]){
int a=10;
int b=5;
System.out.println(a+b);//15
System.out.println(a-b);//5

21
System.out.println(a*b);//50
System.out.println(a/b);//2
System.out.println(a%b);//0
}}

Java Control Statements | Control Flow in Java


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

If Statement:
In Java, the "if" statement is used to evaluate a condition.
1. Simple if statement

2. if-else statement

3. if-else-if ladder

21
4. Nested if-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.
public class Student {
public static void main(String[] args) {
int x = 10;
int y = 12;
if(x+y < 10) {
System.out.println("x + y is less than 10");
} } }
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.
public class Student {
public static void main(String[] args) {
int x = 10;
int y = 12;
if(x+y < 10) {
System.out.println("x + y is less than 10");
} else {
System.out.println("x + y is greater than 20");
}
}

21
}

3. if-else-if ladder:
public class Student {
public static void main(String[] args) {
String city = "Delhi";
if(city == "Meerut") {
System.out.println("city is meerut");
}else if (city == "Noida") {
System.out.println("city is noida");
}else if(city == "Agra") {
System.out.println("city is agra");
}else {
System.out.println(city);
} } }
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.

public class Student


{
public static void main(String[] args)
{
String address = "Delhi, India";
if(address.endsWith("India")) {
if(address.contains("Meerut")) {
System.out.println("Your city is Meerut");
}else if(address.contains("Noida")) {
System.out.println("Your city is Noida");
}else {
System.out.println(address.split(",")[0]);

21
}
}else {
System.out.println("You are not living in India");
} } }

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.
Syntax
switch (expression){
case value1:
statement1;
break;
.
.
.
case valueN:
statementN;
break;
default:
default statement;
}

Example

public class Student implements Cloneable {


public static void main(String[] args) {
int num = 2;
switch (num){
case 0:
System.out.println("number is 0");

21
break;
case 1:
System.out.println("number is 1");
break;
default:
System.out.println(num);
} } }

Output: 2

Loop Statements
In Java, we have three types of loops that execute similarly. However, there are
differences in their syntax and condition checking time.
1. for loop

2. while loop

3. do-while loop

for loop
for(initialization, condition, increment/decrement) {
//block of statements
}

public class Calculattion {


public static void main(String[] args) {
// TODO Auto-generated method stub
int sum = 0;

21
for(int j = 1; j<=10; j++) {
sum = sum + j;
}
System.out.println("The sum of first 10 natural numbers is " + sum);
}
}
Output:
The sum of first 10 natural numbers is 55

for-each loop
Java provides an enhanced for loop to traverse the data structures like array or
collection. In the for-each loop, we don't need to update the loop variable. The syntax to
use the for-each loop in java is given below.
for(data_type var : array_name/collection_name){
//statements
}
Example

public class Calculation {


public static void main(String[] args) {
// TODO Auto-generated method stub
String[] names = {"Java","C","C++","Python","JavaScript"};
System.out.println("Printing the content of the array names:\n");
for(String name:names) {
System.out.println(name);
} } }

Output:
Printing the content of the array names:

Java
C
C++
Python
JavaScript

21
while loop
The syntax of the while loop is given below.
1. while(condition){
2. //looping statements
3. }

Example:

public class Calculation {


public static void main(String[] args) {
// TODO Auto-generated method stub
int i = 0;
System.out.println("Printing the list of first 10 even numbers \n");
while(i<=10) {
System.out.println(i);
i = i + 2;
} } }
Output:
Printing the list of first 10 even numbers

0
2
4
6
8
10

do-while loop
public class Calculation {
public static void main(String[] args) {
// TODO Auto-generated method stub
int i = 0;
System.out.println("Printing the list of first 10 even numbers \n");
do {

21
System.out.println(i);
i = i + 2;
}while(i<=10);
}}

Output:
Printing the list of first 10 even numbers
0
2
4
6
8
10

Jump Statements - 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.
public class BreakExample {
public static void main(String[] args) {
// TODO Auto-generated method stub
for(int i = 0; i<= 10; i++) {
System.out.println(i);
if(i==6) {
break;
} } } }

Output:
0
1
2
3
4
21
5
6

continue statement
nlike 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) {
// TODO Auto-generated method stub
for(int i = 0; i<= 2; i++) {
for (int j = i; j<=5; j++) {
if(j == 4) {
continue;
}
System.out.println(j);
} } } }
Output:
0
1
2
3
5
1
2
3
5
2
3
5

Array and String – to be completed in next lecture

object

An entity that has state and behavior is known as an object e.g., chair, bike, marker, pen,
table, car, etc. It can be physical or logical (tangible and intangible). The example of an

21
intangible object is the banking system.
An object has three characteristics:
o State: represents the data (value) of an object.

o Behavior: represents the behavior (functionality) of an object such as deposit,


withdraw, etc.

o Identity: An object identity is typically implemented via a unique ID. The value of
the ID is not visible to the external user. However, it is used internally by the JVM
to identify each object uniquely.
An object is an instance of a class. A class is a template or blueprint from which objects
are created. So, an object is the instance(result) of a class.

class

A class is a group of objects which have common properties. It is a template or blueprint


from which objects are created. It is a logical entity. It can't be physical.

A class in Java can contain:

Fields
Methods
Constructors
Blocks
Nested class and interface

Method in Java
In Java, a method is like a function which is used to expose the behavior of an object.
new keyword in Java
The new keyword is used to allocate memory at runtime. All objects get memory in Heap
memory area.

Object and Class Example: main within the class


class Student{
int id;
String name;
public static void main(String args[]){
Student s1=new Student();
System.out.println(s1.id);
System.out.println(s1.name);

21
}
}
Output:
0
Null

Object and Class Example: main outside the class


class Student{
int id;
String name;
}
//Creating another class TestStudent1 which contains the main method
class TestStudent1{
public static void main(String args[]){
Student s1=new Student();
System.out.println(s1.id);
System.out.println(s1.name);
}
}
Output:
0
Null

Object / Class Example


class Rectangle{
int length;
int width;
void insert(int l, int w){
length=l;
width=w;
}
void calculateArea(){System.out.println(length*width);}
}

21
class TestRectangle1{
public static void main(String args[]){
Rectangle r1=new Rectangle();
Rectangle r2=new Rectangle();
r1.insert(11,5);
r2.insert(3,15);
r1.calculateArea();
r2.calculateArea();
}
}

Output:
55
45

Inheritance in Java
Inheritance in Java is a mechanism in which one object acquires all the properties and
behaviors of a parent object. It is an important part of OOPs (Object Oriented
programming system).

Terms used in Inheritance


o Class: A class is a group of objects which have common properties. It is a
template or blueprint from which objects are created.

o Sub Class/Child Class: Subclass is a class which inherits the other class. It is
also called a derived class, extended class, or child class.

o Super Class/Parent Class: Superclass is the class from where a subclass


inherits the features. It is also called a base class or a parent class.

o Reusability: As the name specifies, reusability is a mechanism which facilitates


you to reuse the fields and methods of the existing class when you create a new
class. You can use the same fields and methods already defined in the previous

21
class.

The syntax of Java Inheritance


class Subclass-name extends Superclass-name
{
//methods and fields
}
Example
class Employee{
float salary=40000;
}
class Programmer extends Employee{
int bonus=10000;
public static void main(String args[]){
Programmer p=new Programmer();
System.out.println("Programmer salary is:"+p.salary);
System.out.println("Bonus of Programmer is:"+p.bonus); } }
Programmer salary is:40000.0
Bonus of programmer is:10000

Types of inheritance in java

Single Inheritance Example


When a class inherits another class, it is known as a single inheritance. In the example
given below, Dog class inherits the Animal class, so there is the single inheritance.

21
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class TestInheritance{
public static void main(String args[]){
Dog d=new Dog();
d.bark();
d.eat();
}}

Output
barking...
eating...

Multilevel Inheritance Example


When there is a chain of inheritance, it is known as multilevel inheritance. As you can see
in the example given below, BabyDog class inherits the Dog class which again inherits
the Animal class, so there is a multilevel inheritance.
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class BabyDog extends Dog{
void weep(){System.out.println("weeping...");}
}
class TestInheritance2{
public static void main(String args[]){

21
BabyDog d=new BabyDog();
d.weep();
d.bark();
d.eat();
}}
Output
weeping...
barking...
eating...
Hierarchical Inheritance Example
When two or more classes inherits a single class, it is known as hierarchical inheritance. In
the example given below, Dog and Cat classes inherits the Animal class, so there is
hierarchical inheritance.
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class Cat extends Animal{
void meow(){System.out.println("meowing...");}
}
class TestInheritance3{
public static void main(String args[]){
Cat c=new Cat();
c.meow();
c.eat();
//c.bark();//C.T.Error
}}
Output
meowing...
eating...

Why multiple inheritance is not supported in java?

21
To reduce the complexity and simplify the language, multiple inheritance is not
supported in java.
onsider a scenario where A, B, and C are three classes. The C class inherits A and B
classes. If A and B classes have the same method and you call it from child class
object, there will be ambiguity to call the method of A or B class.
class A{
void msg(){System.out.println("Hello");}
}
class B{
void msg(){System.out.println("Welcome");}
}
class C extends A,B{//suppose if it were

public static void main(String args[]){


C obj=new C();
obj.msg();//Now which msg() method would be invoked?
}
}
Output
Compile time error
Multiple Inheritance in Java
The concept of inheritance, which enables classes to adopt features and attributes from
other classes, is fundamental to object-oriented programming. Due to Java's support for
single inheritance, a class can only descend from one superclass. However, Java offers
a method for achieving multiple inheritances through interfaces, enabling a class to
implement many interfaces. We will examine the idea of multiple inheritance in Java,
how it is implemented using interfaces, and use examples to help us understand.
Why multiple inheritance is not possible in java
The reason behind this is to prevent ambiguity.
Consider a case where class B extends class A and Class C and both class A and C have
the same method display().
Now java compiler cannot decide, which display method it should inherit. To prevent such
situation, multiple inheritances is not allowed in java.

Java interfaces

21
A Java interface is a group of abstract methods that specify the behavior that
implementing classes must follow.

interface Character {
void attack();
}
interface Weapon {
void use();
}
class Warrior implements Character, Weapon {
public void attack() {
System.out.println("Warrior attacks with a sword.");
}
public void use() {
System.out.println("Warrior uses a sword.");
}
}
class Mage implements Character, Weapon {
public void attack() {
System.out.println("Mage attacks with a wand.");
}
public void use() {
System.out.println("Mage uses a wand.");
}
}
public class MultipleInheritance {
public static void main(String[] args) {
Warrior warrior = new Warrior();
Mage mage = new Mage();

warrior.attack(); // Output: Warrior attacks with a sword.


warrior.use(); // Output: Warrior uses a sword.

21
mage.attack(); // Output: Mage attacks with a wand.
mage.use(); // Output: Mage uses a wand.
}
}
Output:
Warrior attacks with a sword.
Warrior uses a sword.
Mage attacks with a wand.
Mage uses a wand.
Explanation: The interfaces "Character" and "Weapon" in the example above specify the
behaviour that classes that implement them must have. As a result of the classes
"Warrior" and "Mage" implementing both interfaces, the necessary behaviors may be
inherited and shown. The main method shows how to instantiate these classes' objects
and call their corresponding behaviors.
Method Overloading in Java
If a class has multiple methods having same name but different in parameters, it is
known as Method Overloading.
Method Overriding in Java
If subclass (child class) has the same method as declared in the parent class, it is
known as method overriding in Java.

Usage of Java Method Overriding


o Method overriding is used to provide the specific implementation of a method
which is already provided by its superclass.

o Method overriding is used for runtime polymorphism

Rules for Java Method Overriding


1. The method must have the same name as in the parent class

2. The method must have the same parameter as in the parent class.

3. There must be an IS-A relationship (inheritance).

Example

class Vehicle{
void run(){System.out.println("Vehicle is running");}
}

21
class Bike2 extends Vehicle{
void run(){System.out.println("Bike is running safely");}

public static void main(String args[]){


Bike2 obj = new Bike2();
obj.run(); }
}
Output: Bike is running safely

Use of Super Keyword


Super Keyword in Java
The super keyword in Java is a reference variable which is used to refer immediate
parent class object.

Usage of Java super Keyword


1. super can be used to refer immediate parent class instance variable.

2. super can be used to invoke immediate parent class method.

3. super() can be used to invoke immediate parent class constructor.

class Bike2 extends Vehicle


{
void run()
{
System.out.println("Bike is running safely");

super.run();
}
public static void main(String args[])
{
Bike2 obj = new Bike2();

obj.run();

}
}
class Vehicle
{
void run()
{

21
System.out.println("Vehicle is running");

}
Encapsulation in Java
Encapsulation in Java is a process of wrapping code and data together into a single
unit, for example, a capsule which is mixed of several medicines.

We can create a fully encapsulated class in Java by making all the data members of the
class private. Now we can use setter and getter methods to set and get the data in it.
The Java Bean class is the example of a fully encapsulated class.

Advantage of Encapsulation in Java


By providing only a setter or getter method, you can make the class read-only or write-only.
It provides you the control over the data.
It is a way to achieve data hiding
The encapsulate class is easy to test

Polymorphism in Java
Polymorphism in Java is a concept by which we can perform a single action in different
ways. Polymorphism is derived from 2 Greek words: poly and morphs. The word "poly"
means many and "morphs" means forms. So polymorphism means many forms.

Runtime Polymorphism in Java


Runtime polymorphism or Dynamic Method Dispatch is a process in which a call to an
overridden method is resolved at runtime rather than compile-time.

Example of Java Runtime Polymorphism


In this example, we are creating two classes Bike and Splendor. Splendor class extends
Bike class and overrides its run() method. We are calling the run method by the
reference variable of Parent class. Since it refers to the subclass object and subclass
method overrides the Parent class method, the subclass method is invoked at runtime.
class Bike{
void run(){System.out.println("running");}
}
class Splendor extends Bike{

21
void run(){System.out.println("running safely with 60km");}

public static void main(String args[]){


Bike b = new Splendor();//upcasting
b.run();
}
}
Output:
running safely with 60km.
What is Compile-Time Polymorphism?
Compile-time polymorphism, sometimes referred to as static polymorphism or early
binding, is the capacity of a programming language to decide which method or function
to use based on the quantity, kind, and sequence of inputs at compile-time. Method
overloading, which enables the coexistence of many methods with the same name but
distinct parameter lists within a class, enables Java to accomplish compile-time
polymorphism.

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

A class which is declared with the abstract keyword is known as an abstract class
in Java. It can have abstract and non-abstract methods (method with the body).
There are two ways to achieve abstraction in java
1. Abstract class (0 to 100%)

2. Interface (100%)

Points to Remember
o An abstract class must be declared with an abstract keyword.

o It can have abstract and non-abstract methods.

o It can have constructors and static methods also.

o It can have final methods which will force the subclass not to change the body
of the method.

Abstract Method in Java


A method which is declared as abstract and does not have implementation is known as

21
an abstract method.
abstract class Bike{
abstract void run();
}
class Honda4 extends Bike{
void run(){System.out.println("running safely");}
public static void main(String args[]){
Bike obj = new Honda4();
obj.run();
}
}
Output: running safely

Java Package
A java package is a group of similar types of classes, interfaces and sub-packages.
Package in java can be categorized in two form, built-in package and user-defined
package.
There are many built-in packages such as java, lang, awt, javax, swing, net, io, util, sql
etc.

Advantage of Java Package


1) Java package is used to categorize the classes and interfaces so that they can be
easily maintained.
2) Java package provides access protection.
3) Java package removes naming collision.

21
How to access package from another package?
There are three ways to access the package from outside the package.
1. import package.*;

2. import package.classname;

3. fully qualified name.

Using packagename.*
If you use package.* then all the classes and interfaces of this package will be
accessible but not subpackages.
The import keyword is used to make the classes and interface of another package
accessible to the current package.

Example of package that import the packagename.*


//save by A.java
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}

//save by B.java

21
package mypack;
import pack.*;

class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
How to run java package program
To Compile: javac -d . B.java
To Run: java mypack.B

How to Set CLASSPATH in Java


CLASSPATH:
CLASSPATH is an environment variable which is used by Application ClassLoader to
locate and load the .class files. The CLASSPATH defines the path, to find third-party and
user-defined classes that are not extensions or part of Java platform. Include all the
directories which contain .class files and JAR files when setting the CLASSPATH.
You need to set the CLASSPATH if:
You need to load a class that is not present in the current directory or any sub-
directories.

There are two ways to ways to set CLASSPATH: through Command Prompt or by
setting Environment Variable.
Let's see how to set CLASSPATH of MySQL database:
Step 1: Click on the Windows button and choose Control Panel. Select System.
Step2: System
Step3: Advanced System Setting
Step4: Environment Variable
Step5: If the CLASSPATH already exists in System Variables, click on the Edit button
then put a semicolon (;) at the end. Paste the Path of MySQL-Connector Java.jar file.
If the CLASSPATH doesn't exist in System Variables, then click on the New button and

21
type Variable name as CLASSPATH and Variable value as C:\Program
Files\Java\jre1.8\MySQL-Connector Java.jar;.;
Remember: Put ;.; at the end of the CLASSPATH.
How to make an executable jar file in Java
The jar (Java Archive) tool of JDK provides the facility to create the executable jar file.
An executable jar file calls the main method of the class if you double click it.
To create the executable jar file, you need to create .mf file, also known as manifest file.

Creating manifest file


To create manifest file, you need to write Main-Class, then colon, then space, then
classname then enter. For example:
myfile.mf

Main-Class: First
As you can see, the mf file starts with Main-Class colon space class name. Here, class
name is First.
In mf file, new line is must after the class name.

Creating executable jar file using jar tool


The jar tool provides many switches, some of them are as follows:
1. -c creates new archive file

2. -v generates verbose output. It displays the included or extracted resource on the


standard output.

3. -m includes manifest information from the given mf file.

4. -f specifies the archive file name

5. -x extracts files from the archive file


Now, let's write the code to generated the executable jar using mf file.
You need to write jar then swiches then mf_file then jar_file then .classfile as given
below:
jar -cvmf myfile.mf myjar.jar First.class
It is shown in the image given below:

21
Now it will create the executable jar file. If you double click on it, it will call the main
method of the First class.
We are assuming that you have created any window based application using AWT or
SWING. If you don't, you can use the code given below:
First.java
import javax.swing.*;
public class First{
First(){
JFrame f=new JFrame();

JButton b=new JButton("click");


b.setBounds(130,100,100, 40);

f.add(b);

f.setSize(300,400);
f.setLayout(null);
f.setVisible(true);

f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
new First();
}

21
}

Java Create Jar Files


In Java, JAR stands for Java ARchive, The JAR files format is mainly used to aggregate
a collection of files into a single one. It is a single cross-platform archive format that
handles images, audio, and class files.
We can either download the JAR files from the browser or can write our own JAR files
using Eclipse IDE.
The steps to bundle the source code, i.e., .java files, into a JAR are given below. In this
section, we only understand how we can create JAR files using eclipse IDE. In the
following steps, we don't cover how we can create an executable JAR in Java.
1. In the first step, we will open Eclipse IDE and select the Export option from
the File When we select the Export option, the Jar File wizard opens with the
following screen:

21
2. From the open wizard, we select the Java JAR file and click on the Next The Next
button opens JAR Export for JAR File Specification.

21
3. Now, from the JAR File Specification page, we select the resources needed for
exporting in the Select the resources to export After that, we enter the JAR file name
and folder. By default, the Export generated class files and resources checkbox is
checked. We also check the Export Java source files and resources checkbox to
export the source code.

21
4. If there are other Java files or resources which we want to include and which are
available in the open project, browse to their location and ensure the file or
resource is checked in the window on the right.

5. On the same page, there are three more checkboxes, i.e., Compress the content
of the JAR file, Add directory entries, and Overwrite existing files without warning.
By default, the Compress content of the JAR file checkbox is checked.

6. Now, we have two options for proceeding next, i.e., Finish and Next. If we click
on the Next, it will immediately create a JAR file to that location which we defined
in the Select the export destination. If we click on the Next button, it will open the
Jar Packaging Option wizard for creating a JAR description, setting the advance
option, or changing the default manifest.

21
7. For now, we skip the Next and click on the Finish button.

8. Now, we go to the specified location, which we defined in the Select the export
destination, to ensure that the JAR file is created successfully or not.

Java Static Import


The static import feature of Java 5 facilitate the java programmer to access any static
member of a class directly. There is no need to qualify it by the class name.
Advantage of static import:
o Less coding is required if you have access any static member of a class oftenly.

Disadvantage of static import:


o If you overuse the static import feature, it makes the program unreadable and
unmaintainable.

Simple Example of static import


import static java.lang.Math.*;
class A
{
public static void main(String args[])
{
double num=pow(10,3);
double value=sqrt(25);

System.out.println("num="+num);
System.out.println("Square root of 25 is "+value);
}
}

21
Output:

num=1000.0

Square root of 25 is 5.0

What is the difference between import and static import?


The import allows the java programmer to access classes of a package without
package qualification whereas the static import feature allows to access the static
members of a class without the class qualification.
The import provides accessibility to classes and interface whereas static import
provides accessibility to static members of the class.

21

You might also like