Unit1-BCA IADC
Unit1-BCA IADC
Faculty of BCA
Application
According to Sun, 3 billion devices run Java. There are many devices where Java is currently
used. Some of them are as follows:
1. Desktop Applications such as acrobat reader, media player, antivirus, etc.
2. Web Applications such as irctc.co.in, javatpoint.com, etc.
3. Enterprise Applications such as banking applications.
4. Mobile
5. Embedded System
6. Smart Card
7. Robotics
8. Games, etc.
2) Web Application
● An application that runs on the server side and creates a dynamic page is called a
web application. Currently, Servlet, JSP, Struts, Spring, Hibernate, JSF, etc.
technologies are used for creating web applications in Java.
3) Enterprise Application
● An application that is distributed in nature, such as banking applications, etc. is
called enterprise application. It has advantages of the high-level security, load
balancing, and clustering. In Java, EJB is used for creating enterprise applications.
4) Mobile Application
● An application which is created for mobile devices is called a mobile application.
Currently, Android and Java ME are used for creating mobile applications.
OOP Concepts
(Class, Object, Encapsulation, Inheritance, Polymorphism)
● Object means a real-world entity such as a pen, chair, table, computer, watch,
etc. Object-Oriented Programming is a methodology or paradigm to design a
program using classes and objects.
1. Object
● 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.
Prepared By:Prof.Shweta Joshi Page 2
Indian Academy Degree College
Faculty of BCA
2. Class
● Collection of objects is called class. It is a logical entity.
● A class can also be defined as a blueprint from which you can create an individual
object. Class doesn't consume any space.
3. Inheritance
● When one object acquires all the properties and behaviors of a parent object, it is
known as inheritance. It provides code reusability. It is used to achieve runtime
polymorphism.
4. Polymorphism
● If one task is performed in different ways, it is known as polymorphism. For
example: to convince the customer differently, to draw something, for example,
shape, triangle, rectangle,circle etc.
● Polymorphism means that a call to a member function will cause a different function
to be executed depending on the type of object that invokes the function.
● There are two types of polymorphism compile time and run time polymorphism
● In Java, we use method overloading(compile time) and method overriding(runtime)
to achieve polymorphism.
● Method overloading means having multiple methods with same name but with
different signatures(number,type and order of parameters) in same class.
● When a subclass contains a method with the same name and signature as in the
super class then it is called as method overriding.
5. Abstraction
● Hiding internal details and showing functionality is known as abstraction. For
example we know how to drive car i.e clutch, break,..(interface of car),…etc we also
know what happens when we press the break but we don’t know how it
happened(internal mechanism called implementation)?It is abstracted from the
driver. This is called abstraction.
● Abstraction separates specification(or interface) from implementation of class.
● In Java, we use abstract class and interface to achieve abstraction.
6. 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.
● A java class is the example of encapsulation. Java bean is the fully encapsulated class
because all the data members are private here.
Features of Java
A list of most important features of Java language is given below.
1. Simple
2. Object-Oriented
3. Portable
4. Platform independent
5. Secured
6. Robust
7. Architecture neutral
8. Interpreted
9. High Performance
10. Multithreaded
11. Distributed
12. Dynamic
Simple
● Java is very easy to learn, and its syntax is simple, clean and easy to understand.
According to Sun, Java language is a simple programming language because Java
syntax is based on C++ (so easier for programmers to learn it after C++).
● Java has removed many complicated and rarely-used features, for example, explicit
pointers, operator overloading, etc.
● There is no need to remove unreferenced objects because there is an Automatic
Garbage Collection in Java.
Object-oriented
● Java is an object-oriented programming language. Everything in Java is an object.
Object-oriented means we organize our software as a combination of different types
of objects that incorporates both data and behavior.
● Object-oriented programming (OOPs) is a methodology that simplifies software
development and maintenance by providing some rules.
6. Polymorphism:
● The process of ability to take more than one form is known as polymorphism.There
are two types of polymorphism:Compile time(Method overloading) and run
time(Method overriding,Virtual class).
Method overloading:
● Method name is same and no of arguments and types are different in same class.
Method overriding:
● Method name is same and no of arguments and types are same in different class.
7. Platform Independent
● Java is platform independent because it is different from other languages like C, C++,
etc. which are compiled into platform specific machines while Java is a write once,
run anywhere language. 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
a software-based platform.
● The Java platform differs from most other platforms in the sense that it is a
software-based platform that runs on the top of other hardware-based platforms. It
has two components:
1. Runtime Environment
2. API(Application Programming Interface)
● Java code can be run 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).
8. Secured
● Java is best known for its security. With Java, we can develop virus-free systems. Java
is secured because:
o No explicit pointer
o Java Programs run inside a virtual machine sandbox
o classloader: Classloader in Java is a part of the Java Runtime Environment(JRE)
which is used to load Java classes into the Java Virtual Machine dynamically. It
adds security by separating the package for the classes of the local file system
from those that are imported from network sources.
o Bytecode Verifier: It checks the code fragments for illegal code that can violate
access right to objects.
o Security Manager: It determines what resources a class can access such as reading
and writing to the local disk.
o Java language provides these securities by default. Some security can also be
provided by an application developer explicitly through SSL, JAAS, Cryptography, etc.
9. Robust
● Robust simply means strong. Java is robust because:
o It uses strong memory management.
o There is a lack of pointers that avoids security problems.
o There is automatic garbage collection in java which runs on the Java Virtual
Machine to get rid of objects which are not being used by a Java application
anymore.
o There are exception handling and the type checking mechanism in Java. All these
points make Java robust.
10.Architecture-neutral
● Java is architecture neutral because there are no implementation dependent
features, for example, the size of primitive types is fixed.
● In C programming, int data type occupies 2 bytes of memory for 32-bit architecture
and 4 bytes of memory for 64-bit architecture. However, it occupies 4 bytes of
memory for both 32 and 64-bit architectures in Java.
11.Portable
● Java is portable because it facilitates you to carry the Java bytecode to any platform.
It doesn't require any implementation.
12.High-performance
● Java is faster than other traditional interpreted programming languages because
Java bytecode is "close" to native code. It is still a little bit slower than a compiled
language (e.g., C++). Java is an interpreted language that is why it is slower than
compiled languages, e.g., C, C++, etc.
13.Distributed
● Java is distributed because it facilitates users to create distributed applications in
Java. RMI and EJB are used for creating distributed applications. This feature of Java
makes us able to access files by calling the methods from any machine on the
internet.
14.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.
15.Dynamic
● Java is a dynamic language. It supports dynamic loading of classes. It means classes
are loaded on demand. It also supports functions from its native languages, i.e., C
and C++.
● Java supports dynamic compilation and automatic memory management (garbage
collection).
C++ vs Java
● There are many differences and similarities between the C++ programming language
and Java. A list of top differences between C++ and Java are given below:
Mainly used for C++ is mainly used for system Java is mainly used for application
programming. programming. It is widely used in
window, web-based, enterprise and
mobile applications.
Design Goal C++ was designed for systems Java was designed and created as an
and applications interpreter for printing systems but
programming. It was an later extended as a support network
extension of C programming computing. It was designed with a
language. goal of being easy to use and
accessible to a broader audience.
Compiler and C++ uses compiler only. C++ Java uses compiler and interpreter
Interpreter is compiled and run using the both. Java source code is converted
compiler which converts into bytecode at compilation time.
source code into machine The interpreter executes this
code so, C++ is platform bytecode at runtime and produces
dependent. output. Java is interpreted that is
why it is platform independent.
Call by Value C++ supports both call by Java supports call by value only.
and Call by value and call by reference. There is no call by reference in java.
reference
Structure and C++ supports structures and Java doesn't support structures and
Union unions. unions.
Thread Support C++ doesn't have built-in Java has built-in thread support.
support for threads. It relies
on third-party libraries for
thread support.
Virtual Keyword C++ supports virtual keyword Java has no virtual keyword. We can
so that we can decide override all non-static methods by
whether or not override a default. In other words, non-static
function. methods are virtual by default.
unsigned right C++ doesn't support >>> Java supports unsigned right shift
shift >>> operator. >>> operator that fills zero at the top
Inheritance Tree C++ creates a new Java uses a single inheritance tree
inheritance tree always. always because all classes are the
child of Object class in java. The
object class is the root of
the inheritance tree in java.
C++ Example
#include <iostream>
int main() {
cout << "Hello C++ Programming";
return 0;
}
Java Example
File: Simple.java
class Simple{
public static void main(String args[]){
System.out.println("Hello Java");
}
}
To Compile:javac Simple.java
TO run:java Simple
Compilation Flow:
When we compile Java program using javac tool, java compiler converts the source code
into byte code.
etc.
● James Gosling, Mike Sheridan, and Patrick Naughton initiated the Java language
project in June 1991. The small team of sun engineers called Green Team.
● Originally designed for small, embedded systems in electronic appliances like
set-top boxes.
● Firstly, it was called "Greentalk" by James Gosling, and file extension was .gt.
● After that, it was called Oak and was developed as a part of the Green project.
1. Documentation Section
It includes basic information about a Java program. The information includes the author's
name, date of creation, version, program name, company name, and description of the
program. Using comments we can write in the documentation section. The comments
may be single-line, multi-line, and documentation comments.
Example:
Single line comment: //
Multi-line Comment:/* …..*/
Documentation Comment: /** …….*/
2. Package Declaration
The package declaration is optional. It is placed just after the documentation section. In
this section, we declare the package name in which the class is placed. There can be only
one package statement in a Java program. It must be defined before any class and
interface declaration.We use the keyword package to declare the package name.
Ex.package packagename;
1. Import Statements
If we want to use any class of a particular package, we need to import that class. The
import statement represents the class stored in the other package. We use the import
keyword to import the class. It is written before the class declaration and after the
package statement.
Ex. import java.util.*;
Import java.util.scanner;
4. Interface Section
It is an optional section. We can create an interface in this section if required. We use the
interface keyword to create an interface. An interface is a slightly different from the class.
It contains only constants and method declarations.
Ex.
interface runnable{
final static int a=10;
void run();
void show();
}
5. Class Definition
In this section, we define the class.Without the class, we cannot create any Java program.
We use the class keyword to define the class. It contains information about user-defined
methods, variables, and constants. Every Java program has at least one class that contains
the main() method.
Methods
In this section, we define the functionality of the program by using the methods. The
methods are the set of instructions that we want to perform. These instructions execute at
runtime and perform the specified task.
Ex.
public static void main(String args[])
{
int a=10;
void show(){
System.out.println(“value of a is:”+a);
}
}
2. Identifiers: Identifiers are used as naming of variables, functions and arrays. You
cannot use keywords as identifiers; they are reserved for special use
Prepared By:Prof.Shweta Joshi Page 18
Indian Academy Degree College
Faculty of BCA
3. Constants/Literals: Constants are also like normal variables. But, the only difference
is, their values can not be modified by the program once they are defined. Constants
refer to fixed values. They are also called as literals.Constants may belong to any of the
datatype.
Syntax:
final data_type variable_name;
● For example, the number 100 is a literal. Literals are also commonly called
constants.
● Java literals can be of any of the primitive data types.
● By default, integer literals are of type int. If you want to specify a long literal, append
an l or an L.For example, 12 is an int, but 12L is a long.
● By default, floating point literals are of type double. To specify a float literal, append
an F or f to the constant. For example, 10.19F is of type float.
● Hexadecimal, Octal, and Binary Literals: In programming it is sometimes easier to
use a number system based on 8 or 16 instead of 10.The number system based on 8
is called octal, and it uses the digits 0 through 7. In octal the number 10 is the same
as 8 in decimal. The base 16 number system is called hexadecimal and uses the
digits 0 through 9 plus the letters A through F, which stand for 10, 11, 12, 13, 14, and
15.
● For A hexadecimal literal must begin with 0x or 0X (a zero followed by an x or X). An
octal literal begins with a zero.
● Here are some examples:
hex=0XFF; //255 in decimal
oct=011; //9 in decimal
● It is possible to specify an integer literal by use of binary. To do so, precede the
binary number with a 0b or 0B. For example, this specifies the value 12 in binary:
0b1100.
● String Literals:
● Java supports one other type of literal: the string. A string is a set of characters
enclosed by double quotes. For example,”this is a String.”
● Special Symbols: The following special symbols are used in Java having some
special meaning and thus, cannot be used for some other purpose.
[] () {}, ; * =
● Brackets[]: Opening and closing brackets are used as array element reference.
These indicate single and multidimensional subscripts.
● Parentheses(): These special symbols are used to indicate function calls and
function parameters.
● Braces{}: These opening and ending curly braces marks the start and end of a
block of code containing more than one executable statement.
● comma (, ): It is used to separate more than one statements like for separating
parameters in function calls.
● semicolon : It is an operator that essentially invokes something called an
initialization list.
● asterick (*): It is used to create pointer variable.
● assignment operator: It is used to assign values.
4. Separators:
● The most commonly used separator in Java is the semicolon (;). As you have
seen, it is used to terminate the statements.
● The separators are listed in the following table :
● Symbol ● Name ● Description
Comments in Java
In Java there are three types of comments:
1. Single – line comments.
Syntax:
//Comments here( Text in this line only is considered as comment )
3. Documentation comments.
Syntax:
/**Comment start
*
*tags are used in order to specify a parameter
*or method or heading
*HTML tags can also be used
*such as <h1>
*
*comment ends*/
Prepared By:Prof.Shweta Joshi Page 21
Indian Academy Degree College
Faculty of BCA
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
o Special Operator-instanceOf and dot(.) operator
1.Arithmetic operators:
Java defines the following arithmetic operators:
3.Relational Operators:
4.Logical operators:
Example:
boolean p=true,q=false,r;
int a=24,b=12,c=2;
q= !p;
System.out.println("Logical unary NOT ~ Operator "+q);
r=p^q;
System.out.println("Logical XOR ^ Operator "+r);
boolean s=(p&!q)&&(r&p);
System.out.println("Logical AND && Operator "+s);
s=(a<b)||(a<c);
System.out.println("Logical OR || Operator "+s);
Output:
Logical unary NOT ~ Operator false
Logical XOR ^ Operator true
Logical AND && Operator true
6.Assignment Operator:
7.Bitwise Operator:
Example:
int i=5;
i&k =0
i|k=7
i==k;=>false
i<<3;=>40.
8.Special Operators:
Additive +-
Equality == !=
bitwise exclusive OR ^
bitwise inclusive OR |
logical OR ||
Ternary Ternary ?:
byte 0 1 byte
short 0 2 byte
int 0 4 byte
long 0L 8 byte
Type casting:
Type casting is when you assign a value of one primitive data type to another type.
In Java, there are two types of casting:
● Widening Casting (automatically) - converting a smaller type to a larger type size
byte -> short -> char -> int -> long -> float -> double
Widening Casting
● Widening casting is done automatically when passing a smaller size type to a larger
Prepared By:Prof.Shweta Joshi Page 32
Indian Academy Degree College
Faculty of BCA
size type:
public class MyClass {
public static void main(String[] args) {
int myInt = 9;
double myDouble = myInt; // Automatic casting: int to double
System.out.println(myInt); // Outputs 9
System.out.println(myDouble); // Outputs 9.0
}}
Narrowing Casting
● Narrowing casting must be done manually by placing the type in parentheses in
front of the value:
public class MyClass {
public static void main(String[] args) {
double myDouble = 9.78;
int myInt = (int) myDouble; // Manual casting: double to int
V. Variables in JAVA:
● variables are declared using this form of statement,
Syntax: datatype varname;
Example: int a;
● where type is the data type of the variable, and varname is its name
Initializing a Variable:
● One way to give a variable a value is through an assignment statement, Another way is
by giving it an initial value when it is declared. The general form of initialization is
shown here:
Syntax: datatype var = value;
● Here, value is the value that is given to var when var is created.
Example: int a=10;
● When declaring two or more variables of the same type using a comma separated list,you
can give one or more of those variables an initial value.
Example: int a,b=8,c=10,d;
Dynamic Initialization:
Java allows variables to be initialized dynamically, using any expression valid at the time the
variable is declared.
● Two of the most common scopes in Java are those defined by a class and those defined
by a method. variables declared inside a scope are not visible (that is, accessible) to code
that is defined outside that scope. Thus, when you declare a variable within a scope, you
are localizing that variable and protecting it from unauthorized access and/or
modification.
● A variable declared within a block is called a local variable. variables are created when
their scope is entered, and destroyed when their scope is left. This means that a variable
will not hold its value once it has gone out of scope.
Methods:
Type Method Description
Example:
import java.util.*;
public class ScannerDemo {
public static void main(String args[]){
Scanner in = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = in.nextLine();
System.out.println("Name is: " + name);
String s = "Hello, Java.";
//Create scanner Object and pass string in it
Scanner scan = new Scanner(s); //Check if the scanner has a token
System.out.println("Boolean Result: " + scan.hasNext()); //Print the string
System.out.println("String: " +scan.nextLine());
System.out.print("Enter your age: ");
int i = in.nextInt();
System.out.println("Age: " + i);
System.out.print("Enter your salary: ");
double d = in.nextDouble();
System.out.println("Salary: " + d);
String st = "Hello/This is Java/we use scanner class.";
Scanner sc = new Scanner(st);
sc.useDelimiter("/");
//Printing the tokenized Strings
System.out.println("---Tokenizes String---");
while(sc.hasNext()){
System.out.println(sc.next());
}
//Display the new delimiter
System.out.println("Delimiter used: " +sc.delimiter());
}
}
We use the object of BufferedReader class to take inputs from the keyboard.
Reading Characters
● read() method is used with BufferedReader object to read characters. As this
function returns integer type value has we need to use typecasting to convert it into
char type.
Example:
class StreamDemo
{
public static void main(String[] args)
{
try
{
File fl = new File("d:/sbj/bca/java prog/myfile.txt");
BufferedReader br = new BufferedReader(new FileReader(fl)) ;
String str;
while ((str=br.readLine())!=null)
{
System.out.println(str);
}
}
catch(IOException e) {
e.printStackTrace();
}
}
}
These statements allow you to control the flow of your program’s execution based upon
conditions known only during run time.
● if: if statement is the most simple decision making statement. It is used to decide
whether a certain statement or block of statements will be executed or not i.e if a
certain condition is true then a block of statement is executed otherwise not.
Syntax:
if(condition)
{
// Statements to execute if
// condition is true
}
Example:
class IfDemo
{
public static void main(String args[])
{
int i = 10;
if (i > 15)
System.out.println("10 is less than 15");
System.out.println("I am Not in if");
}
}
if-else: The if statement alone tells us that if a condition is true it will execute a block of
statements and if the condition is false it won’t. But what if we want to do something else if
the condition is false. Here comes the else statement. We can use the else statement with if
statement to execute a block of code when the condition is false.
Syntax:
if (condition)
Prepared By:Prof.Shweta Joshi Page 39
Indian Academy Degree College
Faculty of BCA
{
// Executes this block if
// condition is true
}
else
{
// Executes this block if
// condition is false
}
Example:
class IfElseDemo
{
public static void main(String args[])
{
int i = 10;
if (i < 15)
System.out.println("i is smaller than 15");
else
System.out.println("i is greater than 15");
}
}
Example:
class NestedIfDemo
{
Prepared By:Prof.Shweta Joshi Page 40
Indian Academy Degree College
Faculty of BCA
if (i == 10)
{
if (i < 15)
System.out.println("i is smaller than 15");
if (i < 12)
System.out.println("i is smaller than 12 too");
else
System.out.println("i is greater than 15");
}
}
}
if-else-if ladder: Here, a user can decide among multiple options. The if statements are
executed from the top down. As soon as one of the conditions controlling the if is true, the
statement associated with that if is executed, and the rest of the ladder is bypassed. If none
of the conditions is true, then the final else statement will be executed.
Syntax:
if (condition)
statement;
else if (condition)
statement;
.
.
else
statement;
Example:
class ifelseifDemo
{
public static void main(String args[])
{
int i = 20;
if (i == 10)
System.out.println("i is 10");
else if (i == 15)
System.out.println("i is 15");
Prepared By:Prof.Shweta Joshi Page 41
Indian Academy Degree College
Faculty of BCA
else if (i == 20)
System.out.println("i is 20");
else
System.out.println("i is not present");
}
}
switch-case The switch statement is a multiway branch statement. It provides an easy way
to dispatch execution to different parts of code based on the value of the expression.
Syntax:
switch (expression)
{
case value1:
statement1;
break;
case value2:
statement2;
break;
.
.
case valueN:
statementN;
break;
default:
statementDefault;
}
Example:
class SwitchCaseDemo
{
public static void main(String args[])
{
int i = 9;
switch (i)
{
case 0:
System.out.println("i is zero.");
break;
case 1:
System.out.println("i is one.");
break;
Prepared By:Prof.Shweta Joshi Page 42
Indian Academy Degree College
Faculty of BCA
case 2:
System.out.println("i is two.");
break;
default:
System.out.println("i is greater than 2.");
}
}
}
jump: Java supports three jump statement: break, continue and return. These three
statements transfer control to other part of the program.
1. Break: In Java, break is majorly used for:
● Terminate a sequence in a switch statement (discussed above).
● To exit a loop.
● Used as a “civilized” form of goto.
Using break to exit a Loop
Using break, we can force immediate termination of a loop, bypassing the conditional
expression and any remaining code in the body of the loop.
Example:
class BreakLoopDemo
{
public static void main(String args[])
{
// Initially loop is set to run from 0-9
for (int i = 0; i < 10; i++)
{
// terminate loop when i is 5.
if (i == 5)
break;
System.out.println("i: " + i);
}
System.out.println("Loop complete.");
}
}
● Syntax:
label:
{
statement1;
statement2;
statement3;
.
.
}
● break statement can be use to jump out of target block.
You cannot break to any label which is not defined for an enclosing block.
Syntax:
break label;
Example:
class BreakLabelDemo
{
public static void main(String args[])
{
boolean t = true;
first:
{
// Illegal statement here as label second is not
// introduced yet break second;
second:
{
third:
{
// Before break
System.out.println("Before the break statement");
}}
2. Continue:
● Sometimes it is useful to force an early iteration of a loop. That is, you might want to
continue running the loop but stop processing the remainder of the code in its body
for this particular iteration.
● This is, in effect, a goto just past the body of the loop, to the loop’s end. The continue
statement performs such an action.
Example:
class ContinueDemo
{
public static void main(String args[])
{
for (int i = 0; i < 10; i++)
{
// If the number is even
// skip and continue
if (i%2 == 0)
continue;
if (t)
return;
// after return
System.out.println("This won't execute.");
}
}
1. While loop:
● while loop is the most basic loop in Java. It has one control condition and executes as
long the condition is true.
● The condition of the loop is tested before the body of the loop is executed; hence it is
called an entry-controlled loop.
Syntax:
while (condition)
{
statement(s);
Incrementation;
}
Example:
public class Sample {
public static void main(String args[]) {
int n = 1, times = 5;
while (n <= times) {
System.out.println("Java while loops:" + n);
n++;
}
}
}
2. do-while loop:
● Java do-while loops are very similar to the while loops, but it always executes the
code block at least once and furthermore as long as the condition remains true.
This loop is an exit-controlled loop.
Syntax:
do
{
statement(s);
}while( condition );
Example:
public class Sample {
public static void main(String args[]) {
int n = 1, times = 0;
do {
System.out.println("Java do while loops:" + n);
n++;
} while (n <= times);
}
}
3. for loop:
● Java for loops is very similar to Java while loops in that it continues to process a
block of code until a statement becomes false, and everything is defined in a single
line.
Syntax:
for ( init; condition; increment )
{
statement(s);
}
Example:
public class Sample {
public static void main(String args[]) {
int n = 1, times = 5;
for (n = 1; n <= times; n = n + 1) {
System.out.println("Java for loops:" + n);
}
}
}
Syntax:
for(declaration : expression) {
// Statements
}
● Declaration − The newly declared block variable, is of a type compatible with the
elements of the array you are accessing. The variable will be available within the for
block and its value would be the same as the current array element.
● Expression − This evaluates to the array you need to loop through. The expression
can be an array variable or method call that returns an array.
Example:
public class Test {
public static void main(String args[]) {
int [] numbers = {10, 20, 30, 40, 50};
for(int x : numbers ) {
System.out.print( x );
System.out.print(",");
}
System.out.print("\n");
String [] names = {"James", "Larry", "Tom", "Lacy"};
for( String name : names ) {
System.out.print( name );
System.out.print(",");
}
}
}
}
is equivalent to:
for (int i=0; i<arr.length; i++)
{
type var = arr[i];
statements using var;
}
Example:
class Testarray1{
public static void main(String args[]){
int arr[]={33,3,4,5};
for(int i:arr)
System.out.println(i);
}}
Object creation:
● An Object contains properties and performs actions. Properties are represented by
variables and actions are performed by function which known as method.
● Objects are created and destroyed as the program runs and there can be many
objects in the same class.
● In java creating an object of a class is a two step process:
● At first we need to declare a variable of the class type. This variable does not define
an object.
● Second we must acquire an actual physical copy of object and assign it to that
variable.We can do this using new operator.
Syntax:
classname objectname;
objectname=new classname();
or
classname objectname=new classname();
New operator:
● It creates single instance of a class and returns a reference to that object.
● This reference is the address in memory of the object allocated by new operator.
Example:
Employee e=new Employee ();
● Here e is a reference to an instance of object. The reference is then stored in t he
variable. The variable e is a reference to the object. It does not actually contain it.
Dot operator:
● It is used to obtain the value of the instance variable.
Syntax:
Objectreference.variablename;
Example:
e.name;
Instance Variable:
● An instance variable is a variable whose separate copy is available to each object.
● A variable which is created inside the class but outside the method is known as an
instance variable. Instance variable doesn't get memory at compile time.
● It gets memory at runtime when an object or instance is created. That is why it is
known as an instance variable.
Method in Java:
In Java, a method is like a function which is used to expose the behavior of an object.
Syntax:
Returntype functionname
{
//line1…
}
Advantage of Method
o Code Reusability
o Code Optimization
How to access a method in Java:
we have to use object name and dot(.) operator to access a method in java.
Syntax: objectname.methodname();
Example: d.show();
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.
● When we call a method in an object java matches up the method name first and then
the number and type of parameters to decide which one of definitions to execute.
This process is known as polymorphism.
● There are two ways to overload the method in java
1. By changing number of arguments
2. By changing the data type
Example:
class M{
void disp(){
System.out.println("Hello");
}
void disp(int x){
System.out.println(x);
}
void disp(String s){
System.out.println(s);
}
}
class Methodoverload{
public static void main(String args[])
{
M m=new M();
m.disp();
m.disp("JAVA");
m.disp(8);
}
}
● As you can see in the above figure, object gets the memory in heap memory area.
The reference variable refers to the object allocated in the heap memory area. Here,
s1 and s2 both are reference variables that refer to the objects allocated in memory.
7) There are many ways to create There is only one way to define class in
object in java such as new keyword, java using class keyword.
newInstance() method, clone()
method, factory method and
deserialization.
Protected:
● This access specifier gives more security and you can access data members of one
class in other subclasses.
Private:
● Most restrictive access modifier
● Private data members may not be accessed by any other classes.
● An object’s primary job is to encapsulate its data and limit manipulation. This is
achieved by declaring data as private.
Default Constructor
● A constructor is called "Default Constructor" when it doesn't have any parameter.
Syntax:
<class_name>(){}
Parameterized Constructor
● A constructor which has a specific number of parameters is called a parameterized
constructor.
Why use the parameterized constructor?
● The parameterized constructor is used to provide different values to distinct objects.
However, you can provide the same values also.
Example:
class Student4{
int id;
String name;
Student4(int i,String n){
id = i;
name = n;
}
void display()
{
System.out.println(id+" "+name);
}
public static void main(String args[]){
Student4 s1 = new Student4(111,"Karan");
Student4 s2 = new Student4(222,"Aryan");
s1.display();
s2.display();
}
}
int id;
String name;
int age;
Student5(int i,String n){
id = i;
name = n;
}
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();
}
}
dataType arr[];
Example:
class Testarray{
public static void main(String args[]){
int a[]=new int[5];
a[0]=10;
a[1]=20;
a[2]=70;
a[3]=40;
a[4]=50;
for(int i=0;i<a.length;i++)
System.out.println(a[i]);
}}
}}
Example:
class Testarray3{
public static void main(String args[]){
int arr[][]={{1,2,3},{2,4,5},{4,4,5}};
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
System.out.print(arr[i][j]+" ");
}
System.out.println();
}
}}
Example:
class TestJaggedArray{
public static void main(String[] args){
int arr[][] = new int[3][];
arr[0] = new int[3];
arr[1] = new int[4];
arr[2] = new int[2];
int count = 0;
for (int i=0; i<arr.length; i++)
for(int j=0; j<arr[i].length; j++)
arr[i][j] = count++;
for (int i=0; i<arr.length; i++){
for (int j=0; j<arr[i].length; j++){
System.out.print(arr[i][j]+" ");
}
System.out.println();//new line
}
}
}
Command Line Argument Array
● The java command-line argument is an argument i.e. passed at the time of running
the java program.
● The arguments passed from the console can be received in the java program and it
can be used as an input.
● So, it provides a convenient way to check the behavior of the program for the
different values. To access the command-line argument inside a java program is
quite easy, they are stored as string in String array passed to the args parameter
of main() method. You can pass n numbers of arguments from the command prompt.
Example:
class CommandLineExample{
public static void main(String args[]){
System.out.println("Your first argument is: "+args[0]);
}
}
compile by > javac CommandLineExample.java
Example:
class A{
public static void main(String args[]){
for(int i=0;i<args.length;i++)
System.out.println(args[i]);
}
}
compile by > javac A.java
run by > java A 1 3 abc
Example:
class cmd
{
public static void main(String[] args)
{
for(int i=0;i< args.length;i++)
{
System.out.println(args[i]);
}
}
}
X. Finalizer/Garbage Collection:
● Since objects are dynamically allocated by using the new operator, objects are
destroyed and their memory released for later reallocation.
● In some languages, such as C++,dynamically allocated objects must be manually
released by use of a delete operator.
● Java takes a different approach; it handles deallocation for you automatically. The
technique that accomplishes this is called garbage collection.
● when no references to an object exist, that object is assumed to be no longer needed,
and the memory occupied by the object can be reclaimed. There is no explicit need
to destroy objects as in C++.
finalize( ) Method:
● Sometimes an object will need to perform some action when it is destroyed.
● For example,if an object is holding some non-Java resource such as a file handle or
window character font, then you might want to make sure these resources are freed
before an object is destroyed. To handle such situations, Java provides a mechanism
called finalization.
● By using finalization, you can define specific actions that will occur when an object is
just about to be reclaimed by the garbage collector.
● finalize( ) method you will specify those actions that must be performed before an
object is destroyed.
● The garbage collector runs periodically, checking for objects that are no longer
referenced by any running state or indirectly through other referenced objects.
● Right before an asset is freed, the Java run time calls the finalize( ) method on the
object.
● Syntax:
protected void finalize( )
{
// finalization code here
}
Example:
public class JavafinalizeExample1 {
public static void main(String[] args)
{
JavafinalizeExample1 obj = new JavafinalizeExample1();
System.out.println(obj.hashCode());
obj = null;
// calling garbage collector
System.gc();
System.out.println("end of garbage collection");
}
protected void finalize()
{
System.out.println("finalize method called");
}
}
Field:
Following are the fields for java.lang.Math class −
● static double E − This is the double value that is closer than any other to e, the
base of the natural logarithms.
● static double PI − This is the double value that is closer than any other to pi, the
ratio of the circumference of a circle to its diameter.
⮚ Math.floor()
● The Math.floor() function rounds a floating point value down to the nearest integer
value.
● The rounded value is returned as a double.
● Example:
double floor = Math.floor(7.343); // floor = 7.0
⮚ Math.min()
● The Math.min() method returns the smallest of two values passed to it as parameter
● Example:
int min = Math.min(10, 20);
⮚ Math.max()
● The Math.max() method returns the largest of two values passed to it as parameter.
● Example:
int max = Math.max(10, 20);
⮚ Math.round()
● The Math.round() method rounds a float or double to the nearest integer using
normal math round rules (either up or down).
● Example:
double roundedDown = Math.round(23.445);
double roundedUp = Math.round(23.545);
● After executing these two Java statements the roundedDown variable will contain
the value 23.0 , and the roundedUp variable will contain the value 24.0.
⮚ Math.random()
● The Math.random() method returns a random floating point number between 0 and
1. Of course the number is not fully random, but the result of some calculation which
is supposed to make it as unpredictable as possible.
● Example:
double random = Math.random();
● Example:
double exp1 = Math.exp(1);
System.out.println("exp1 = " + exp1);
double exp2 = Math.exp(2);
System.out.println("exp2 = " + exp2);
Output:
exp1 = 2.718281828459045
exp2 = 7.38905609893065
⮚ Math.log()
● The Math.log() method provides the logarithm of the given parameter. The base for
the logarithm is i (Euler's number). Thus, Math.log() provides the reverse function
of Math.exp().
● Example:
double log1 = Math.log(1);
System.out.println("log1 = " + log1);
double log10 = Math.log(10);
System.out.println("log10 = " + log10);
output:
log1 = 0.0
log10 = 2.302585092994046
⮚ Math.log10()
● The Math.log10 method works like the Math.log() method except is uses 10 as is
base for calculating the logarithm instead of e (Euler's Number).
● Example:
double log10_1 = Math.log10(1);
System.out.println("log10_1 = " + log10_1);
double log10_100 = Math.log10(100);
System.out.println("log10_100 = " + log10_100);
Output:
log10_1 = 0.0
log10_100 = 2.0
⮚ Math.pow()
● The Math.pow() function takes two parameters. The method returns the value of the
first parameter raised to the power of the second parameter.
● Example:
double pow2 = Math.pow(2,2);
⮚ Math.tan()
● The Math.tan() method calculates the tangens value of some angle value in radians.
● Example:
double tan = Math.tan(Math.PI);
System.out.println("tan = " + tan);
Output:
tan=-1.224646…..
⮚ Math.asin()
● The Math.asin() method calculates the arc sine value of a value between 1 and 1.
● Example:
double asin = Math.asin(1.0);
System.out.println("asin = " + asin);
Output:
asin=1.570796…..
⮚ Math.acos()
● The Math.acos() method calculates the arc cosine value of a value between 1 and -1.
● Example:
double acos = Math.acos(1.0);
System.out.println("acos = " + acos);
Output:
acos=0.0
⮚ Math.atan()
● The Math.atan() method calculates the arc tangens value of a value between 1 and
-1.
● Example:
double atan = Math.atan(1.0);
System.out.println("atan = " + atan);
Output:
atan=0.78539816….
⮚ Math.toRadians()
● The Math.toRadians() method converts an angle in degrees to radians.
● Example:
double radians = Math.toRadians(180);
System.out.println("radians = " + radians);
Output:
radians=3.141….
⮚ Math.toDegrees()
● The Math.toDegrees() method converts an angle in radians to degrees.
● Example:
double degrees = Math.toDegrees(Math.PI);
System.out.println("degrees = " + degrees);
Output:
degrees=180
2. Java.lang.String Class
● The java.lang.String class represents character strings. All string literals in Java
programs, such as "abc", are implemented as instances of this class.
● Strings are constant, their values cannot be changed after they are created. That is
called immutable.
Class Declaration
Syntax:
public final class String extends Object implements Serializable, Comparable<String>,
CharSequence
1. String Literal
● Java String literal is created by using double quotes.
● Example:
String s="welcome";
● Each time you create a string literal, the JVM checks the "string constant pool" first.
Prepared By:Prof.Shweta Joshi Page 72
Indian Academy Degree College
Faculty of BCA
If the string already exists in the pool, a reference to the pooled instance is returned.
If the string doesn't exist in the pool, a new string instance is created and placed in
the pool.
● Example:
String s1="Welcome";
String s2="Welcome";//It doesn't create a new instance
● String objects are stored in a special memory area known as the "string constant
pool"
Why Java uses the concept of String literal?
● To make Java more memory efficient (because no new objects are created if it exists
already in the string constant pool).
2. By new keyword
● Example:
String s=new String("Welcome");//creates two objects and one reference variable
● In such case, JVM will create a new string object in normal (non-pool) heap memory,
and the literal "Welcome" will be placed in the string constant pool. The variable s
will refer to the object in a heap (non-pool).
Example:
public class StringMethodsDemo {
public static void main(String[] args) {
String targetString = "Java is fun to learn";
String s1= "JAVA";
String s2= "Java";
String s3 = " Hello Java ";
System.out.println("Char at index 2(third position): " +
targetString.charAt(2));
3. Java.lang.StringBuffer class
● Java StringBuffer class is used to create mutable (modifiable) string. The
StringBuffer class in java is same as String class except it is mutable i.e. it can
be changed.
● Java StringBuffer class is thread-safe i.e. multiple threads cannot access it
simultaneously. So it is safe and will result in an order.
Constructors:
Constructor Description
StringBuffer() creates an empty string buffer with the initial capacity of 16.
Methods:
public insert(int offset, is used to insert the specified string with this string
synchronized String s) at the specified position. The insert() method is
StringBuffer overloaded like insert(int, char), insert(int,
boolean), insert(int, int), insert(int, float),
insert(int, double) etc.
public int length() is used to return the length of the string i.e. total
number of characters.
public String substring(int is used to return the substring from the specified
beginIndex, int beginIndex. and endIndex.
endIndex)
Example:
public class StringBufferExample {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer("Hello");
int sbLength = sb.length();
int sbCapacity = sb.capacity();
System.out.println("String Length of " + sb + " is " + sbLength);
System.out.println("Capacity of " + sb + " is " + sbCapacity);
sb.append("World ");
System.out.println(sb);
sb.insert(5, " ");
sb.insert(sb.length(), 2017);
System.out.println(sb);
System.out.println(sb.reverse());
System.out.println(sb.delete(5,11));
StringBuffer sb2 = new StringBuffer("Hello World!");
System.out.println(sb2.deleteCharAt(11));
System.out.println(sb.replace(6,11,"Earth"));
}
}
4. Java.lang.StringBuilder Class:
● Java StringBuilder class is used to create mutable (modifiable) string.
● The Java StringBuilder class is same as StringBuffer class except that it is non
synchronized. which means it is not thread safe. Its because StringBuilder methods
are not synchronised.
2) String is slow and consumes more memory StringBuffer is fast and consumes
when you concat too many strings because less memory when you concat
every time it creates new instance. strings.
3) String class overrides the equals() method StringBuffer class doesn't override
of Object class. So you can compare the the equals() method of Object
contents of two strings by equals() method. class.
StringBuilder classes are mutable. There are many differences between StringBuffer and
StringBuilder.
2. boolean isDigit(char ch): This method is used to determine whether the specified char
value(ch) is a digit or not. Here also we can pass ASCII value as an argument.
It returns true if ch is a digit, otherwise, return false.
3.toString(char ch): It returns a String class object representing the specified character
value(ch) i.e a one-character string. Here we cannot pass ASCII value.
Syntax:
String toString(char ch)
Parameters:
ch – a primitive character
Returns: It returns a String object.
5. compareTo():
The compareTo(character another character) method of character class is used to compare two
objects numerically.
Syntax:
public int compareTo(CharcteranotherCharcter )
Parameter:
The above method requires only one parameter:
The character that need to be compared.
The value 0 if the given Character is equal to the argument Character.
A value less than 0 if the given Character is numerically less than the Character argument
A value greater than the given Character is numerically greater than the Character argument.
Example:
Character firstVal = new Character('g');
Constructors
Constructor Description
File(File parent, String It creates a new File instance from a parent abstract pathname and
child) a child pathname string.
File(String pathname) It creates a new File instance by converting the given pathname
string into an abstract pathname.
File(String parent, String It creates a new File instance from a parent pathname string and a
child) child pathname string.
File(URI uri) It creates a new File instance by converting the given file: URI into
an abstract pathname.
Methods
boolean canWrite() It tests whether the application can modify the file
denoted by this abstract pathname.String[]
boolean canExecute() It tests whether the application can execute the file
denoted by this abstract pathname.
boolean canRead() It tests whether the application can read the file denoted
by this abstract pathname.
Example 1
import java.io.*;
Prepared By:Prof.Shweta Joshi Page 82
Indian Academy Degree College
Faculty of BCA
String name;
student(int rollno,String name,int marks)
{
this.rollno=rollno;
this.name=name;
this.marks=marks;
}
void show()
{
System.out.println("Rollno:"+rollno+"\nName:"+name+"\nMarks:"+marks);
}
}
class Thisdemo2
{
public static void main(String args[])
{
student s=new student(1,"Aarshvi",50);
s.show();
}
}
2. this can be used to invoke current class method (implicitly)
● You may invoke the method of the current class by using the this keyword. If you
don't use the this keyword, compiler automatically adds this keyword while
invoking the method.
Example:
class A{
void m()
{
System.out.println("hello m");
}
void n()
{
System.out.println("hello n");
//m();//same as this.m()
Prepared By:Prof.Shweta Joshi Page 84
Indian Academy Degree College
Faculty of BCA
this.m();
}
}
class TestThis4{
public static void main(String args[]){
A a=new A();
a.n();
}
}
3. this() can be used to invoke current class constructor.
● The this() constructor call can be used to invoke the current class constructor. It is
used to reuse the constructor. In other words, it is used for constructor chaining.
● Call to this() must be the first statement in constructor.
Example1:
Calling default constructor from parameterized constructor:
class A{
A()
{
System.out.println("hello a");
}
A(int x)
{
this();
System.out.println(x);
}
}
class TestThis5{
public static void main(String args[]){
A a=new A(10);
}
}
Example2:
Calling parameterized constructor from default constructor:
Prepared By:Prof.Shweta Joshi Page 85
Indian Academy Degree College
Faculty of BCA
class A{
A()
{
this(5);
System.out.println("hello a");
}
A(int x)
{
System.out.println(x);
}
}
class TestThis6{
public static void main(String args[])
{
A a=new A();
}
}
4.this can be passed as an argument in the method call.
● The this keyword can also be passed as an argument in the method. It is mainly used
in the event handling.
Example:
class S2{
void m(S2 obj)
{
System.out.println("method is invoked");
}
void p()
{
m(this);
}
public static void main(String args[]){
S2 s1 = new S2();
s1.p();
}
Prepared By:Prof.Shweta Joshi Page 86
Indian Academy Degree College
Faculty of BCA
}
5.this can be passed as argument in the constructor call.
● We can pass the this keyword in the constructor also. It is useful if we have to use
one object in multiple classes.
Example:
class B{
A4 obj;
B(A4 obj)
{
this.obj=obj;
}
void display(){
System.out.println(obj.data);//using data member of A4 class
}
}
class A4{
int data=10;
A4(){
B b=new B(this);
b.display();
}
public static void main(String args[]){
A4 a=new A4();
}
}
6.this can be used to return the current class instance from the method.
● We can return this keyword as an statement from the method. In such case, return
type of the method must be the class type (non-primitive).
Syntax:
return_type method_name(){
return this;
}
Example:
Prepared By:Prof.Shweta Joshi Page 87
Indian Academy Degree College
Faculty of BCA
class A{
A getA()
{
return this;
}
void msg()
{
System.out.println("Hello java");
}
}
class Test1{
public static void main(String args[]){
new A().getA().msg();
}
}
Notes:
static variable
o If you declare any variable as static, it is known as a static variable. The static
variable can be used to refer to the common property of all objects (which is not
unique for each object), for example, the company name of employees, college name
of students, etc.
o The static variable gets memory only once in the class area at the time of class
loading.
Advantages of static variable
● It makes your program memory efficient (i.e., it saves memory).
Example:
class Student{
int rollno;//instance variable
String name;
static String college ="DSTC";//static variable
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(1,"Kia");
Student s2 = new Student(2,"ria");
s1.display();
s2.display();
}
}
static method
● If you apply static keyword with any method, it is known as static method.
o A static method belongs to the class rather than the object of a class.
o A static method can be invoked without the need for creating an instance of a
class.
o A static method can access static data member and can change the value of it.
Syntax:
static returntype functionname{
Prepared By:Prof.Shweta Joshi Page 89
Indian Academy Degree College
Faculty of BCA
///……..
}
Example:
class static1
{
int st=30;
static void show()
{
System.out.println("Hello static keyword is used");
System.out.println("st="+st);
}
}
class Staticdemo
{
public static void main(String args[])
{
int a=10;
int b=20;
int c=2;
System.out.println("a="+a+"\nb="+b+"\nc="+c);
static1.show();
st=b+c;
System.out.println("The value of st is:"+st);
}
}
● There are two main restrictions for the static method. They are:
1. The static method can not use non static data member or call non-static method
directly.
2. this and super cannot be used in static context.
Example:
class A{
int a=40;
public static void main(String args[]){
System.out.println(a); //gives an error
Prepared By:Prof.Shweta Joshi Page 90
Indian Academy Degree College
Faculty of BCA
}
}
static block
● Is used to initialize the static data member.
● It is executed before the main method at the time of classloading
Example:
class A2{
static{
System.out.println("static block is invoked");
}
public static void main(String args[]){
System.out.println("Hello main");
}
}
Difference table:
Topic static Non static
JVM
● JVM (Java Virtual Machine) is an abstract machine. It is called a virtual machine
because it doesn't physically exist.
● It is a specification that provides a runtime environment in which Java byte code can
be executed. It can also run those programs which are written in other languages
and compiled to Java byte code.
● JVMs are available for many hardware and software platforms. JVM, JRE, and JDK are
platform dependent because the configuration of each OS is different from each
other. However, Java is platform independent.
● There are three notions of the JVM:
specification, implementation, and instance.
1. A specification: where working of Java Virtual Machine is specified. But
implementation provider is independent to choose the algorithm. Its
implementation has been provided by Oracle and other companies.
2.An implementation: Its implementation is known as JRE (Java Runtime
Environment).
3. Runtime Instance: Whenever you write java command on the command prompt
to run the java class, an instance of JVM is created.
● The JVM performs the following main tasks:
o Loads code
o Verifies code
o Executes code
o Provides runtime environment
JVM Architecture
● It contains class loader, memory area, execution engine etc.
JRE:
● JRE is an acronym for Java Runtime Environment. It is also written as Java RTE.
● The Java Runtime Environment is a set of software tools which are used for
developing Java applications. It is used to provide the runtime environment.
● It is the implementation of JVM. It physically exists.
● It contains a set of libraries + other files that JVM uses at runtime. The
implementation of JVM is also actively released by other companies besides Sun
Micro Systems.
JDK :
● JDK is an acronym for Java Development Kit.
● The Java Development Kit (JDK) is a software development environment which is
used to develop Java applications and applets. It contains JRE + development tools.
● JDK is an implementation of any one of the below given Java Platforms released by
Oracle Corporation:
o Standard Edition Java Platform
o Enterprise Edition Java Platform
o Micro Edition Java Platform
● The JDK contains a private Java Virtual Machine (JVM) and a few other resources
such as an interpreter/loader (java), a compiler (javac), an archiver (jar), a
documentation generator (Javadoc), etc. to complete the development of a Java
Application.
Java has a feature that Write Once and Run anywhere explain.
● One of the initial "killer feature" of Java was supposed to be the write once, run
anywhere nature of it.