Java Unit 1
Java Unit 1
History of Java
The history of Java is very interesting.
Java was originally designed for interactive television, but it was too
advanced technology for the digital cable television industry at the time.
The history of Java starts with the Green Team.
Java team members (also known as Green Team), initiated this project to
develop a language for digital devices such as set-top boxes, televisions,
etc.
It was best suited for internet programming.
Later, Java technology was incorporated by Netscape.
The principles for creating Java programming were "Simple, Robust,
Portable, Platform-independent, Secured, High Performance,
Multithreaded, Architecture Neutral, Object-Oriented, Interpreted, and
Dynamic".
Java was developed by James Gosling, who is known as the father of
Java, in 1995.
James Gosling and his team members started the project in the early '90s.
1) James Gosling, Mike Sheridan, and Patrick Naughton initiated the Java
language project in June 1991. The small team of sun engineers called Green
Team.
PREPARED BY: PATEL MANESH - M.Sc(CA & IT) Contact: 90165 17796 1
PATEL MANESH
3) Firstly, it was called "Greentalk" (language)by James Gosling, and the file
extension was .gt.
4) After that, it was called Oak (Language) and was developed as a part of the
Green project.
Why Java was named as "Oak"?
5) Why Oak? Oak is a symbol of strength and chosen as a national tree of many
countries like the U.S.A., France, Germany, Romania, etc.
The team gathered to choose a new name. The suggested words were
"dynamic", "revolutionary", "Silk", "jolt", "DNA", etc.
They wanted something that reflected the essence of the technology:
revolutionary, dynamic, lively, cool, unique, and easy to spell, and fun to
say.
According to James Gosling, "Java was one of the top choices along
with Silk". Since Java was so unique, most of the team members preferred
Java than other names.
s
PREPARED BY: PATEL MANESH - M.Sc(CA & IT), B.ED Contact: 90165 17796 2
PATEL MANESH
8) Java is an island in Indonesia where the first coffee was produced (called Java
coffee). Java name was chosen by James Gosling while having a cup of coffee
nearby his office.
Where it is used?
There are many devices where Java is currently used.
Some of them are as follows:
4. Mobile Application
5. Embedded System
6. Smart Card
7. Robotics
8. Games etc.
4) JavaFx
s
PREPARED BY: PATEL MANESH - M.Sc(CA & IT), B.ED Contact: 90165 17796 5
PATEL MANESH
To create a simple java program, you need to create a class that contains
main method.
Let's understand the requirement first.
s
PREPARED BY: PATEL MANESH - M.Sc(CA & IT), B.ED Contact: 90165 17796 6
PATEL MANESH
o Object
o Class
o Inheritance
o Polymorphism
o Abstraction
o Encapsulation
Apart from these concepts, there are some other terms which are used in Object-
Oriented design:
o Coupling
o Cohesion
o Association
o Aggregation
o Composition
s
PREPARED BY: PATEL MANESH - M.Sc(CA & IT), B.ED Contact: 90165 17796 7
PATEL MANESH
Object
Object-oriented programming revolves around data.
The main programming unit of OOP is the object.
An object is a representation of a real-time entity and consists of data and
methods or functions that operate on data.
This way, data, and functions are closely bound and data security is ensured.
In OOP, everything is represented as an object and when programs are
executed, the objects interact with each other by passing messages.
An object need not know the implementation details of another object for
communicating.
Any entity that has state and behavior is known as an object. For example, a
chair, pen, table, keyboard, bike, etc. It can be physical or logical.
An Object can be defined as an instance of a class.
An object contains an address and takes up some space in memory.
Objects can communicate.
The only necessary thing is the type of message accepted and the type of
response returned by the objects.
Example: A dog is an object because it has states like color, name, breed, etc.
as well as behaviors like wagging the tail, barking, eating, etc.
Class
Collection of objects is called class. It is a logical entity.
Class is a combination of data member and member function.
A class can also be defined as a blueprint from which you can create an
individual object.
Class doesn't consume any space.
A class is a blueprint of the object.
An object can be defined as an instance of a class.
A class contains a skeleton of the object and does not take any space in the
memory.
s
PREPARED BY: PATEL MANESH - M.Sc(CA & IT), B.ED Contact: 90165 17796 8
PATEL MANESH
Encapsulation
Binding (or wrapping) code and data together into a single unit are known as
encapsulation.
For example, a capsule, it is wrapped with different medicines.
Java class is the example of encapsulation.
Class is a combination of data member and member function into a single
unit.
It provides security from unauthorised object.
Abstraction
Abstraction is the process of hiding irrelevant information from the user.
Hiding internal details and showing functionality is known as abstraction.
For example phone call, we don't know the internal processing.
Using abstraction in programming, we can hide unnecessary details from the
user.
By using abstraction in our application, the end user is not affected even if we
change the internal implementation.
Inheritance
We can create a new class from the old class and access all the functionalities
from the parent class to child class, that knowns as inheritance.
Using inheritance, object of one class can inherit the properties of the object
of another class.
Inheritance provides reusability of code.
As such we can design a new class by inherit the properties and functionality
of another class and in this process, we need not modify the functionality of
the parent class.
We only add new functionality to the class.
Inheritance is a mechanism of driving a new class from an existing class.
The existing (old) class is known as base class or super class or parent class.
The new class is known as a derived class or sub class or child class.
It allows us to use the properties and behavior of one class (parent) in another
class (child).
s
PREPARED BY: PATEL MANESH - M.Sc(CA & IT), B.ED Contact: 90165 17796 9
PATEL MANESH
Types of Inheritance
Java supports four types of inheritance:
1. Single inheritance
2. Hierarchical inheritance
3. Multilevel inheritance
4. Hybrid inheritance
Coupling
Coupling refers to the knowledge or information or dependency of another
class.
It arises when classes are aware of each other.
If a class has the details information of another class, there is strong
coupling.
In Java, we use private, protected, and public modifiers to display the
visibility level of a class, method, and field.
s
PREPARED BY: PATEL MANESH - M.Sc(CA & IT), B.ED Contact: 90165 17796 10
PATEL MANESH
Association
Association represents the relationship between the objects.
Here, one object can be associated with one object or many objects.
There can be four types of association between the objects:
1. One to One
2. One to Many
3. Many to One, and
4. Many to Many
Aggregation
Aggregation is a way to achieve Association.
Aggregation represents the relationship where one object contains other
objects as a part of its state.
It represents the weak relationship between objects.
It is also termed as a has-a relationship in Java.
Like, inheritance represents the is-a relationship.
It is another way to reuse objects.
Composition
The composition is also a way to achieve Association.
The composition represents the relationship where one object contains
other objects as a part of its state.
There is a strong relationship between the containing object and the
dependent object.
It is the state where containing objects do not have an independent
existence.
If you delete the parent object, all the child objects will be deleted
automatically.
s
PREPARED BY: PATEL MANESH - M.Sc(CA & IT), B.ED Contact: 90165 17796 11
PATEL MANESH
Features of Java
There is given many features of java.
They are also known as java buzzwords.
The Java Features given below are simple and easy to understand.
1. Simple
2. Object-Oriented
3. Portable
4. Platform independent
5. Secured
6. Robust
7. Architecture neutral
8. Dynamic
9. Interpreted
10. High Performance
11. Multithreaded
12. Distributed
s
PREPARED BY: PATEL MANESH - M.Sc(CA & IT), B.ED Contact: 90165 17796 12
PATEL MANESH
Simple
According to Sun, Java language is simple because:
syntax is based on C++ (so easier for programmers to learn it after C++).
removed many confusing and/or rarely-used features e.g., explicit pointers,
operator overloading etc.
No need to remove unreferenced objects because there is Automatic
Garbage Collection in java.
Object-oriented
Object-oriented means we organize our software as a combination of
different types of objects that incorporates both data and behaviour.
Object-oriented programming(OOPs) is a methodology that simplify
software development and maintenance by providing some rules.
Platform Independent
A platform is the hardware or software environment in which a program
runs.
There are two types of platforms software-based and hardware-based. Java
provides software-based platform.
The Java platform differs from most other platforms in the sense that it is a
software-based platform that runs on the top of other hardware-based
platforms. It has two components:
1. Runtime Environment
2. API(Application Programming Interface)
s
PREPARED BY: PATEL MANESH - M.Sc(CA & IT), B.ED Contact: 90165 17796 13
PATEL MANESH
Java code can be run on multiple platforms e.g. Windows, Linux, Sun
Solaris, Mac/OS etc.
Java code is compiled by the compiler and converted into bytecode.
This bytecode is a platform-independent code because it can be run on multiple
platforms i.e. Write Once and Run Anywhere (WORA).
Secured
Java is secured because:
No explicit pointer
Java Programs run inside virtual machine sandbox
Classloader: adds security by separating the package for the classes of the
local file system from those that are imported from network sources.
Bytecode Verifier: checks the code fragments for illegal code that can
violate access right to objects.
Security Manager: determines what resources a class can access such as
reading and writing to the local disk.
Robust
Robust simply means strong.
Java uses strong memory management.
There are lack of pointers that avoids security problem.
There is automatic garbage collection in java.
There is exception handling and type checking mechanism in java.
All these points makes java robust.
s
PREPARED BY: PATEL MANESH - M.Sc(CA & IT), B.ED Contact: 90165 17796 14
PATEL MANESH
Architecture-neutral
There is no implementation dependent features e.g. size of primitive types
is fixed.
In C programming, int data type occupies 2 bytes of memory for 32-bit
architecture and 4 bytes of memory for 64-bit architecture.
But in java, it occupies 4 bytes of memory for both 32 and 64 bit
architectures.
Portable
We may carry the java bytecode to any platform.
High-performance
Java is faster than traditional interpretation since byte code is "close" to
native code still somewhat slower than a compiled language (e.g., C++)
Distributed
We can create distributed applications in java.
RMI and EJB are used for creating distributed applications.
We may access files by calling the methods from any machine on the
internet.
Multi-threaded
A thread is like a separate program, executing concurrently.
We can write Java programs that deal with many tasks at once by defining
multiple threads.
The main advantage of multi-threading is that it doesn't occupy memory for
each thread.
It shares a common memory area.
Threads are important for multi-media, Web applications etc.
s
PREPARED BY: PATEL MANESH - M.Sc(CA & IT), B.ED Contact: 90165 17796 15
PATEL MANESH
s
PREPARED BY: PATEL MANESH - M.Sc(CA & IT), B.ED Contact: 90165 17796 16
PATEL MANESH
Compiler and C++ uses compiler only. Java uses both compiler and
Interpreter C++ is compiled and run interpreter.
using the compiler which Java source code is
converts source code into converted into bytecode at
machine code. compilation time. The
interpreter executes this
bytecode at runtime and
produces output.
Call by Value C++ supports both call by Java supports call by value
and Call by value and call by only. There is no call by
reference reference. reference in java.
Structure and C++ supports structures Java doesn't support
Union and unions. structures and unions.
Thread Support C++ doesn't have built-in Java has built-
support for threads. in thread support.
s
PREPARED BY: PATEL MANESH - M.Sc(CA & IT), B.ED Contact: 90165 17796 18
PATEL MANESH
import java.io.*;
import java.lang.*;
s
PREPARED BY: PATEL MANESH - M.Sc(CA & IT), B.ED Contact: 90165 17796 19
PATEL MANESH
s
PREPARED BY: PATEL MANESH - M.Sc(CA & IT), B.ED Contact: 90165 17796 20
PATEL MANESH
s
PREPARED BY: PATEL MANESH - M.Sc(CA & IT), B.ED Contact: 90165 17796 21
PATEL MANESH
In this example, we are receiving only one argument and printing it.
To run this java program, you must pass at least one argument from the
command prompt.
class CmdExa
{
public static void main(String args[])
{
System.out.println("Your first argument is: "+args[0]);
}
}
Output:
s
PREPARED BY: PATEL MANESH - M.Sc(CA & IT), B.ED Contact: 90165 17796 22
PATEL MANESH
import java.io.*;
class CmdExa
{
public static void main(String args[])
{
}
}
Output:
Manesh
25
5000
s
PREPARED BY: PATEL MANESH - M.Sc(CA & IT), B.ED Contact: 90165 17796 23
PATEL MANESH
Java Comments
The Java comments are the statements in a program that are not executed
by the compiler and interpreter.
s
PREPARED BY: PATEL MANESH - M.Sc(CA & IT), B.ED Contact: 90165 17796 24
PATEL MANESH
Syntax:
/*
This
is
multi line
comment
*/
Syntax:
/**
*
*We can use various tags to depict the parameter
*or heading or author name
*We can also use HTML tags
*
*/
s
PREPARED BY: PATEL MANESH - M.Sc(CA & IT), B.ED Contact: 90165 17796 25
PATEL MANESH
Java Improvements
s
PREPARED BY: PATEL MANESH - M.Sc(CA & IT), B.ED Contact: 90165 17796 26
PATEL MANESH
s
PREPARED BY: PATEL MANESH - M.Sc(CA & IT), B.ED Contact: 90165 17796 27
PATEL MANESH
s
PREPARED BY: PATEL MANESH - M.Sc(CA & IT), B.ED Contact: 90165 17796 28
PATEL MANESH
Constants
Constant means fix value that cannot be changed once assigned.
In Java, the constant values are defined by using the final keyword and
static keyword.
The final keyword represents that the value of the variable cannot be
changed.
Note that the identifier name must be in capital letters.
We can also define constants as static because without object we can
access easily.
Literals
In Java, literals are the constant values that appear directly in the program.
It can be assigned directly to a variable.
Java has various types of literals.
The following figure represents a literal.
1. Integer Literal
2. Character Literal
3. Boolean Literal
4. String Literal
s
PREPARED BY: PATEL MANESH - M.Sc(CA & IT), B.ED Contact: 90165 17796 29
PATEL MANESH
1. Integer Literals
Integer literals are sequences of digits.
There are three types of integer literals:
o Decimal Integer: These are the set of numbers that consist of digits from 0
to 9. It may have a positive (+) or negative (-) Note that between numbers
commas and non-digit characters are not permitted.
o For example, 5678, +657, -89, etc.
o Binary Integer: Base 2, whose digits consists of the numbers 0 and 1 (you
can create binary literals in Java SE 7 and later).
o Prefix 0b represents the Binary system.
o For example, 0b11010.
Backslash Literals
Java supports some special backslash character literals known as backslash
literals.
They are used in formatted output.
For example:
Character Literals
A character literal is expressed as a character or an escape sequence,
enclosed in a single quote ('') mark.
It is always a type of char.
For example, 'a', '%', '\u000d', etc.
String Literals
String literal is a sequence of characters that is enclosed
between double quotes ("") marks.
It may be alphabet, numbers, special characters, blank space, etc.
For example, "Jack", "12345", "\n", etc.
o Floating-point literals for float type end with F or f. For example, 6f,
8.354F, etc. It is a 32-bit float literal.
o Floating-point literals for double type end with D or d. It is optional to
write D or d. For example, 6d, 8.354D, etc. It is a 64-bit double literal.
o It can also be represented in the form of the exponent.
s
PREPARED BY: PATEL MANESH - M.Sc(CA & IT), B.ED Contact: 90165 17796 31
PATEL MANESH
Boolean Literals
Boolean literals are the value that is either true or false.
It may also have values 0 and 1.
For example, true, 0, etc.
System.out.println(no);
System.out.println(per);
System.out.println(cost);
System.out.println(binary);
System.out.println(c);
System.out.println(str);
}
}
s
PREPARED BY: PATEL MANESH - M.Sc(CA & IT), B.ED Contact: 90165 17796 32
PATEL MANESH
Data Types
Variables are nothing but reserved memory locations to store values.
This means that when you create a variable you reserve some space in the
memory.
Based on the data type of a variable, the operating system allocates memory
and decides what can be stored in the reserved memory.
By assigning different data types to variables, you can store integers,
decimals, or characters in these variables.
1. byte
2. short
s
PREPARED BY: PATEL MANESH - M.Sc(CA & IT), B.ED Contact: 90165 17796 33
PATEL MANESH
3. int
4. long
5. float
6. double
7. boolean
s
PREPARED BY: PATEL MANESH - M.Sc(CA & IT), B.ED Contact: 90165 17796 34
PATEL MANESH
8. char
Java Variables
A variable is a container which holds the value.
Def. Variable is a data name that is used to store data value.
A variable is assigned with a data type.
Variable is a name of memory location.
There are three types of variables in java: local, instance and static.
There are two types of data types in Java: primitive and non-primitive.
s
PREPARED BY: PATEL MANESH - M.Sc(CA & IT), B.ED Contact: 90165 17796 35
PATEL MANESH
Types of Variables
There are three types of variables in Java:
1. local variable
2. instance variable
3. 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.
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.
3) Static variable
s
PREPARED BY: PATEL MANESH - M.Sc(CA & IT), B.ED Contact: 90165 17796 36
PATEL MANESH
import java.io.*;
void show()
1. {
2. int n=90; //local variable
3. }
Final Variables
If you don't want to overwrite existing values, you have to use
the final keyword.
Example:
final int no = 9;
no = 10; // will generate an error: cannot assign a value to a final
variable
s
PREPARED BY: PATEL MANESH - M.Sc(CA & IT), B.ED Contact: 90165 17796 37
PATEL MANESH
So, we have Static variables that are globally declared and are accessible by
all method, subclass of a program.
Java Keywords
Java keywords are also known as reserved words.
Keywords are particular words that act as a key to a code.
These are predefined words by Java so they cannot be used as a variable or
object name or class name.
s
PREPARED BY: PATEL MANESH - M.Sc(CA & IT), B.ED Contact: 90165 17796 38
PATEL MANESH
s
PREPARED BY: PATEL MANESH - M.Sc(CA & IT), B.ED Contact: 90165 17796 39
PATEL MANESH
Converting a lower data type into a higher one is called widening type
casting.
It is also known as implicit conversion or casting down.
It is done automatically.
It is safe because there is no chance to lose data.
int x = 10;
long y = x; // Automatic Conversion
Note:
The conversion between numeric data type to char or Boolean is not done
automatically.
Also, the char and Boolean data types are not compatible with each other.
class Demo
{
public static void main(String M[])
{
int x = 10;
} Output:
}
Before conversion, the value is: 10
After conversion, the long value is: 10
After conversion, the float value is: 10.0
s
PREPARED BY: PATEL MANESH - M.Sc(CA & IT), B.ED Contact: 90165 17796 40
PATEL MANESH
Converting a higher data type into a lower one is called narrowing type
casting.
It is also known as explicit conversion or casting up.
It is done manually by the programmer.
If we do not perform casting then the compiler reports a compile-time error.
double -> float -> long -> int -> char -> short -> byte
import java.io.*;
}
}
s
PREPARED BY: PATEL MANESH - M.Sc(CA & IT), B.ED Contact: 90165 17796 41
PATEL MANESH
Output:
Before conversion: 50.75
After conversion into long type: 50
After conversion into int type: 50
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:
s
PREPARED BY: PATEL MANESH - M.Sc(CA & IT), B.ED Contact: 90165 17796 42
PATEL MANESH
class incre
{
public static void main(String args[])
{
int a=10;
int b=10;
System.out.println(a++ + ++a);
//10+12=22
System.out.println(b++ + b++);
//10+11=21
}
}
Output:
22
21
class Arith
{
public static void main(String args[])
{
int a=10;
int b=5;
System.out.println(a+b); //15
System.out.println(a-b); //5
Output:
System.out.println(a*b); //50 15
System.out.println(a/b); //2 5
System.out.println(a%b); //0 50
} 2
0
}
s
PREPARED BY: PATEL MANESH - M.Sc(CA & IT), B.ED Contact: 90165 17796 44
PATEL MANESH
class OpExa
{
public static void main(String args[])
{
System.out.println(10*10/5+3-1*4/2);
}
}
Output: 21
s
PREPARED BY: PATEL MANESH - M.Sc(CA & IT), B.ED Contact: 90165 17796 45
PATEL MANESH
Output:
2
5
2
class LogicalExa
{
public static void main(String args[])
{
int a=10;
int b=5;
int c=20;
System.out.println(a<b && a<c); //false && true = false
System.out.println(a<b & a<c); //false & true = false
}
}
Output:
false
false
s
PREPARED BY: PATEL MANESH - M.Sc(CA & IT), B.ED Contact: 90165 17796 46
PATEL MANESH
s
PREPARED BY: PATEL MANESH - M.Sc(CA & IT), B.ED Contact: 90165 17796 47
PATEL MANESH
a += 2; //a=a+4 (a=10+4)
b -= 2; //b=b-4 (b=20-4)
System.out.println(a);
Output:
System.out.println(b); 12
} 18
}
s
PREPARED BY: PATEL MANESH - M.Sc(CA & IT), B.ED Contact: 90165 17796 48
PATEL MANESH
s
PREPARED BY: PATEL MANESH - M.Sc(CA & IT), B.ED Contact: 90165 17796 49
PATEL MANESH
Decision-Making statements:
1) If Statement:
1. Simple if statement
2. if-else statement
3. if-else-if ladder
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.
1. class Student
{
2. public static void main(String[] args)
3. {
4. int x = 10;
5. int y = 12;
6. if(x+y > 20)
7. {
8. System.out.println("x + y is greater than 20");
}
}
2) if-else statement
s
PREPARED BY: PATEL MANESH - M.Sc(CA & IT), B.ED Contact: 90165 17796 50
PATEL MANESH
class Student
{
public static void main(String[] ashvin)
{
int x = 10;
int y = 12;
else
{
System.out.println("x + y is greater than 20");
}
}
}
3) if-else-if ladder:
The if-else-if statement contains the if-statement followed by multiple else-if
statements.
In other words, we can say that it is the chain of if-else statements that create a
decision tree where the program may enter in the block of code where the condition
is true.
We can also define an else statement at the end of the chain.
s
PREPARED BY: PATEL MANESH - M.Sc(CA & IT), B.ED Contact: 90165 17796 51
PATEL MANESH
class Grade
{
public static void main(String Manish[])
{
int score; // To hold a test score
char grade; // To hold a letter grade
s
PREPARED BY: PATEL MANESH - M.Sc(CA & IT), B.ED Contact: 90165 17796 52
PATEL MANESH
Switch Statement:
o The case variables can be int, short, byte, char, or enumeration. String type is also
supported since version 7 of Java
o Cases cannot be duplicate
o Default statement is executed when any of the case doesn't match the value of
expression. It is optional.
o Break statement terminates the switch block when the condition is satisfied.
It is optional, if not used, next case is executed.
switch (expression)
{
case value1:
statement1;
break;
.
.
.
case valueN:
statementN;
break;
default:
default statement;
}
s
PREPARED BY: PATEL MANESH - M.Sc(CA & IT), B.ED Contact: 90165 17796 53
PATEL MANESH
import java.util.*;
class Week
{
public static void main(String[] ashvin)
{
int no;
switch(no)
{
case 1:
System.out.println (“sunday”);
break;
case 2:
System.out.println ("Monday");
break;
case 3:
System.out.println ("Tuesday");
break;
case 4:
System.out.println ("Wednesday");
break;
default:
System.out.println (“Sorry!!!...Plz…enter number between
1 and 7”);
break;
}
}
}
You can use Numaric, Character and String using switch case.
s
PREPARED BY: PATEL MANESH - M.Sc(CA & IT), B.ED Contact: 90165 17796 54
PATEL MANESH
Loop Statements
In programming, sometimes we need to execute the block of code
repeatedly while some condition evaluates to true.
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.
1. for loop
2. while loop
3. do-while loop
s
PREPARED BY: PATEL MANESH - M.Sc(CA & IT), B.ED Contact: 90165 17796 55
PATEL MANESH
Import java.io.*;
class Sum
{
public static void main(String[] manu)
{
int sum = 0;
}
}
The while loop is also used to iterate over the number of statements
multiple times.
However, if we don't know the number of iterations in advance, it is
recommended to use a while loop.
Unlike for loop, the initialization and increment/decrement doesn't take
place inside the loop statement in while loop.
It is also known as the entry-controlled loop since the condition is checked
at the start of the loop.
If the condition is true, then the loop body will be executed; otherwise, the
statements after the loop will be executed.
while (condition)
{
//looping statements
}
s
PREPARED BY: PATEL MANESH - M.Sc(CA & IT), B.ED Contact: 90165 17796 56
PATEL MANESH
import java.io.*;
class Even
{
public static void main(String[] args)
{
int i = 0;
while (i<=10)
{
System.out.println (i);
i = i + 2;
}
}
}
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.
s
PREPARED BY: PATEL MANESH - M.Sc(CA & IT), B.ED Contact: 90165 17796 57
PATEL MANESH
do
{
//statements
} while (condition);
do {
System.out.println(i);
i = i + 2;
}while(i<=10);
}
}
s
PREPARED BY: PATEL MANESH - M.Sc(CA & IT), B.ED Contact: 90165 17796 58
PATEL MANESH
Nested Loop
Nested for loop in Java means a for loop inside another for loop is called
nested for loops.
A nested for loops consists of an outer for loop and one or more inner for
loops.
Each time the outer for loop repeats, the inner for loop re-enters and starts a
new execution.
s
PREPARED BY: PATEL MANESH - M.Sc(CA & IT), B.ED Contact: 90165 17796 59
PATEL MANESH
Java Method
A method is a way to perform some task.
The method in Java is a collection of instructions that performs a specific task.
It provides the reusability of code.
We can also easily modify code using methods.
It is used to achieve the reusability of code.
We write a method once and use it many times.
We do not require to write code again and again.
It also provides the easy modification and readability of code, just by adding or
removing a chunk of code.
The method is executed only when we call or invoke it.
The most important method in Java is the main() method.
Method Declaration
s
PREPARED BY: PATEL MANESH - M.Sc(CA & IT), B.ED Contact: 90165 17796 60
PATEL MANESH
Naming a Method
Single-word method name: sum(), area()
Multi-word method name: areaOfCircle(), stringComparision()
It is also possible that a method has the same name as another method name
in the same class, it is known as method overloading.
Types of Method
There are two types of methods in Java:
1. Predefined Method
2. User-defined Method
1. 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(), print(), println(), Max(), Min() etc.
User-defined Method
s
PREPARED BY: PATEL MANESH - M.Sc(CA & IT), B.ED Contact: 90165 17796 61
PATEL MANESH
class Display
{
public static void main(String[] args)
{
show();
}
s
PREPARED BY: PATEL MANESH - M.Sc(CA & IT), B.ED Contact: 90165 17796 62
PATEL MANESH
Abstract Method
The method that does not has method body is known as abstract method.
In other words, without an implementation is known as abstract method.
It always declares in the abstract class.
It means the class itself must be abstract if it has abstract method.
To create an abstract method, we use the keyword abstract.
Syntax
s
PREPARED BY: PATEL MANESH - M.Sc(CA & IT), B.ED Contact: 90165 17796 63
PATEL MANESH
class Demo
{
int a,b; //class or instance variable
s
PREPARED BY: PATEL MANESH - M.Sc(CA & IT), B.ED Contact: 90165 17796 64
PATEL MANESH
class Demo1
{
public static void main(String M[])
{
Demo D1=new Demo(); Output:
Instance Methods are the group of codes that performs a particular task.
Sometimes the program grows in size, and we want to separate the logic of
the main method from other methods.
A method is a function written inside the class.
Java is an object-oriented programming language, we need to write a
method inside some classes.
s
PREPARED BY: PATEL MANESH - M.Sc(CA & IT), B.ED Contact: 90165 17796 65
PATEL MANESH
class Demo
{
int a,b; //class or instance variable
s
PREPARED BY: PATEL MANESH - M.Sc(CA & IT), B.ED Contact: 90165 17796 66
PATEL MANESH
class Demo1
{
public static void main(String M[])
{
Demo D1=new Demo(); //Object Output:
s
PREPARED BY: PATEL MANESH - M.Sc(CA & IT), B.ED Contact: 90165 17796 67
PATEL MANESH
Static method
static keyword in java is used a lot in java programming.
Java static keyword is used to create a Class level variable in java.
static variables and methods are part of the class, not the instances of the
class.
The static keyword in java is used for memory management mainly.
We can apply java static keyword with variables, methods, blocks and
nested class.
s
PREPARED BY: PATEL MANESH - M.Sc(CA & IT), B.ED Contact: 90165 17796 68
PATEL MANESH
class Student
{
int rollno;
String name;
String college="BCA";
}
Suppose there are 500 students in my college, now all instance data
members will get memory each time when object is created.
All students have its unique rollno and name so instance data member is
good.
Here, college refers to the common property of all objects.If we make it
static,this field will get memory only once.
Java static property is shared to all objects.
Example
class Student
{
int rollno;
String name;
static String college ="BCA";
Student8(int r,String n)
{
rollno = r;
name = n;
}
void display ()
{
System.out.println(rollno+" "+name+" "+college);
}
s
PREPARED BY: PATEL MANESH - M.Sc(CA & IT), B.ED Contact: 90165 17796 69
PATEL MANESH
s1.display();
s2.display();
}
Output:
111 MANESH BCA
222 BINA BCA
If you apply static keyword with any method, it is known as static method.
A static method belongs to the class.
static method can access static data member and can change the value
of it.
class Student
{
int rollno;
String name;
static String college = "B.com";
void display ()
{
System.out.println (rollno+" "+name+" "+college);
}
s1.display ();
111 Ashvin BCA
s2.display ();
}} 222 Nivanshi BCA
class Demo
{
static
{
System.out.println ("static block is invoked"); Output:
}
static block is invoked
public static void main(String M[])
{ Hello main
System.out.println ("Hello main");
}
}
s
PREPARED BY: PATEL MANESH - M.Sc(CA & IT), B.ED Contact: 90165 17796 71
PATEL MANESH
Yes, one of the way is static block but in previous version of JDK not in JDK
1.7 and later.
class XYZ{
static
{
System.out.println ("static block is invoked");
System.exit (0);
} }
Method overloading
If a class has multiple methods having same name but different in
parameters, it is known as Method Overloading.
If we have to perform only one operation, having same name of the
methods increases the readability of the program.
Suppose you have to perform addition of the given numbers but there can
be any number of arguments,
if you write the method such as a(int,int) for two parameters, and
b(int,int,int) for three parameters then it may be difficult for you as well as
other programmers to understand the behavior of the method because its
name differs.
class Demo
{
int a=10,b=20;
void add()
{
System.out.println (a+b);
}
a = no1;
int r = a + b;
return (r); class Manish
} {
public static void main (String M[])
void add (int no1, int no2) {
{ Demo d=new Demo ();
a=no1;
b=no2; d.add ();
System.out.println (a + b);
int z = d.add (100);
}
System.out.println (z);
}
d.add (500,600);
}
}
Public
s
PREPARED BY: PATEL MANESH - M.Sc(CA & IT), B.ED Contact: 90165 17796 73
PATEL MANESH
Constructors in Java
In Java, a constructor is a block of codes similar to the method.
It is called when an object of the class is created.
At the time of calling constructor, memory for the object is allocated in the
memory.
It is a special type of method which is used to initialize the object.
Every time an object is created using the new() keyword, at least one
constructor is called.
It calls a default constructor if there is no constructor available in the class.
In such case, Java compiler provides a default constructor by default.
1. Default constructor
2. Parameterized constructor.
<class_name> () {}
Example Demo() {}
s
PREPARED BY: PATEL MANESH - M.Sc(CA & IT), B.ED Contact: 90165 17796 74
PATEL MANESH
import java.io.*;
class Demo
{
}
}
The default constructor is used to provide the default values to the object like
0, null, etc., depending on the type.
s
PREPARED BY: PATEL MANESH - M.Sc(CA & IT), B.ED Contact: 90165 17796 75
PATEL MANESH
class Student
{
int id;
String name;
s
PREPARED BY: PATEL MANESH - M.Sc(CA & IT), B.ED Contact: 90165 17796 76
PATEL MANESH
class Student
{
int id, age;
String name;
void display()
{
System.out.println (id+" "+name+" "+age);
}
s1.display ();
s2.display ();
}
}
s
PREPARED BY: PATEL MANESH - M.Sc(CA & IT), B.ED Contact: 90165 17796 77
PATEL MANESH
s
PREPARED BY: PATEL MANESH - M.Sc(CA & IT), B.ED Contact: 90165 17796 78
PATEL MANESH
Suggestion: If you are beginner to java, lookup only three usage of this keyword.
void display ()
{
System.out.println (rollno+" "+name+" "+fee);
}
}
class Demo
{
public static void main (String M[])
{
Student s1=new Student (111, "Bina", 5000f);
Student s2=new Student (112, "Nivanshi", 6000f);
s1.display ();
s2.display (); OUTPUT
}
0 null 0.0
}
0 null 0.0
s
PREPARED BY: PATEL MANESH - M.Sc(CA & IT), B.ED Contact: 90165 17796 79
PATEL MANESH
In the above example, parameters (formal arguments) and instance variables are
same. So, we are using this keyword to distinguish local variable and instance
variable.
void display ()
{
System.out.println (rollno+" "+name+" "+fee);
}
}
class Demo
{
public static void main (String M[])
{
Student s1=new Student (111, "Bina", 5000f);
Student s2=new Student (112, "Nivanshi", 6000f);
s1.display ();
s2.display ();
} OUTPUT
} 111 Bina 5000
112 Nivanshi 6000
s
PREPARED BY: PATEL MANESH - M.Sc(CA & IT), B.ED Contact: 90165 17796 80
PATEL MANESH
You may invoke the method of the current class by using this keyword.
If you don't use this keyword, compiler automatically adds this keyword
while invoking the method.
Let's see the example
class A
{
void m()
{
System.out.println ("hello m");
}
void show()
{
System.out.println ("hello n");
//m(); //same as this.m()
this.m ();
}
}
class Demo
{
public static void main (String M[])
{
A obj=new A();
obj.show();
}
}
Output:
hello n
hello m
s
PREPARED BY: PATEL MANESH - M.Sc(CA & IT), B.ED Contact: 90165 17796 81
PATEL MANESH
class A
{
A()
{
this(5); // Parameterized Constructor calling
System.out.println ("Hello");
}
class Test
{
public static void main (String args[])
{
A a=new A(); // Default Constructor calling
}
}
Output:
5
Hello
4) this: to pass as an argument in the method
class S2
{
void m (S2 obj)
{
System.out.println ("method is invoked");
}
s
PREPARED BY: PATEL MANESH - M.Sc(CA & IT), B.ED Contact: 90165 17796 82
PATEL MANESH
void p()
{
m(this);
}
Java Array
Normally, array is a collection of similar type of elements that have
contiguous memory location.
Java array is an object contains elements of similar data type.
It is a data structure where we store similar elements.
We can store only fixed set of elements in a java array.
Array in java is index based, first element of the array is stored at 0 index.
Size Limit: We can store only fixed size of elements in the array.
It doesn't grow its size at runtime.
To solve this problem, collection framework is used in java.
s
PREPARED BY: PATEL MANESH - M.Sc(CA & IT), B.ED Contact: 90165 17796 83
PATEL MANESH
class arr
{
public static void main(String manish[]){
s
PREPARED BY: PATEL MANESH - M.Sc(CA & IT), B.ED Contact: 90165 17796 84
PATEL MANESH
class arr
{
public static void main(String args[])
{
int a[]={33,3,4,5}; //declaration, instantiation and initialization
//printing array
}}
s
PREPARED BY: PATEL MANESH - M.Sc(CA & IT), B.ED Contact: 90165 17796 85
PATEL MANESH
For example,
arr[0][0]=1;
arr[0][1]=2;
arr[0][2]=3;
arr[1][0]=4;
arr[1][1]=5;
arr[1][2]=6;
arr[2][0]=7;
arr[2][1]=8;
arr[2][2]=9;
s
PREPARED BY: PATEL MANESH - M.Sc(CA & IT), B.ED Contact: 90165 17796 86
PATEL MANESH
class Demo
{
public static void main(String args[])
{
//declaring and initializing 2D array
int arr[][]={{1,2,3},{2,4,5},{4,4,5}};
//printing 2D array
Syntax:
import java.io.*;
class Demo
{
public static void main(String M[])
{
int arr[] = { 10, 50, 60, 80, 90 }; // array declaration
10 50 60 80 90
s
PREPARED BY: PATEL MANESH - M.Sc(CA & IT), B.ED Contact: 90165 17796 88
PATEL MANESH
Another Example
class Demo1
{
public static void main(String M[])
{
int arr[]={10,20,30,40};
int total=0;
} Total: 100
System.out.println ("Total: "+total);
}
}
s
PREPARED BY: PATEL MANESH - M.Sc(CA & IT), B.ED Contact: 90165 17796 89
PATEL MANESH
import java.util.*;
for (int i = 0; i < a.length; i++) //for loop to print the array
{
System.out.print (a[i] + " ");
}
}
s
PREPARED BY: PATEL MANESH - M.Sc(CA & IT), B.ED Contact: 90165 17796 90