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

Fepj - 1

Uploaded by

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

Fepj - 1

Uploaded by

Ankush Thakur
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 54

Reference Document

Front End Development & Programming using


Java
OOP Concepts

Object Oriented Programming is a paradigm that provides many concepts such as


Inheritance, data binding, polymorphism etc. Simula is considered as the first object-
oriented programming language. The programming paradigm where everything is
represented as an object is known as truly object-oriented programming language.
Smalltalk is considered as the first truly object-oriented programming language.

OOPs (Object Oriented Programming System)


Object means a real word entity such as pen, chair, table etc. Object-Oriented
Programming is a methodology or paradigm to design a program using classes and objects. It
simplifies the software development and maintenance by providing some concepts:

 Object

 Class

 Inheritance

 Polymorphism

 Abstraction

 Encapsulation

Object

Any entity that has state and behavior is known as an object. For example: chair, pen, table,
keyboard, bike etc. It can be physical and logical.

JAVA PROGRAMMING Page 1


Class
Collection of objects is called class. It is a logical entity.

Inheritance
When one object acquires all the properties and behaviors of parent object i.e. known
as inheritance. It provides code reusability. It is used to achieve runtime polymorphism.

Polymorphism
When one task is performed by different ways i.e. known as polymorphism. For
example: to convince the customer differently, to draw something e.g. shape or rectangle
etc. In java, we use method overloading and method overriding to achieve polymorphism. Another
example can be to speak something e.g. cat speaks meaw, dog barks woof etc.
Abstraction
Hiding internal details and showing functionality is known as abstraction. For example:
phone call, we don't know the internal processing. In java, we use abstract class and interface to
achieve abstraction.
Encapsulation
Binding (or wrapping) code and data together into a single unit is known as
encapsulation. For example: 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.

Benefits of Inheritance
One of the key benefits of inheritance is to minimize the amount of duplicate code in an
application by sharing common code amongst several subclasses. Where equivalent code
exists in two related classes, the hierarchy can usually be refactored to move the common
code up to a mutual superclass. This also tends to result in a better organization of code and
smaller, simpler compilation units. Inheritance can also make application code more
flexible to change because classes that inherit from a common superclass can be used
interchangeably. If the return type of a method is superclass
Reusability - facility to use public methods of base class without rewriting the same.

Extensibility - extending the base class logic as per business logic of the derived class.
Data hiding - base class can decide to keep some data private so that it cannot be altered by
the derived class.

JAVA PROGRAMMING Page 2


PROCEDURAL AND OBJECT ORIENTED PROGRAMMING
PARADIGMS

JAVA PROGRAMMING Page 3


Java Programming- History of Java
The history of java starts from Green Team. Java team members (also
known as Green Team), initiated a revolutionary task to develop a language for digital
devices such as set-top boxes, televisions etc. For the green team members, it was an
advance concept at that time. But, it was suited for internet programming. Later, Java
technology as incorporated by Netscape.
Currently, Java is used in internet programming, mobile devices, games, e-
business solutions etc. There are given the major points that describes the history of java.
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.

Java Version History


There are many java versions that has been released. Current stable release of Javais Java SE 8.

1. JDK Alpha and Beta (1995)


2. JDK 1.0 (23rd Jan, 1996)
3. JDK 1.1 (19th Feb, 1997)
4. J2SE 1.2 (8th Dec, 1998)
5. J2SE 1.3 (8th May, 2000)
6. J2SE 1.4 (6th Feb, 2002)
7. J2SE 5.0 (30th Sep, 2004)
8. Java SE 6 (11th Dec, 2006)
9. Java SE 7 (28th July, 2011)
10. Java SE 8 (18th March, 2014)
11. Java SE 9 (21st Sep 2017)
12. Java SE 10 (20th Mar 2018)
13. Java SE 11 (September 2018)
14. Java SE 12 (March 2019)
15. Java SE 13 (September 2019)
16. Java SE 14 (Mar 2020)
17. Java SE 15 (September 2020)
18. Java SE 16 (Mar 2021)
19. Java SE 17 (September 2021)
JAVA PROGRAMMING Page 4
20. Java SE 18 (March 2022)
21. Java SE 19 (September 2022)

Features of Java
There is given many features of java. They are also known as java buzzwords. The Java
Featuresgiven 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

Java Comments
The java comments are statements that are not executed by the compiler and interpreter.
The comments can be used to provide information or explanation about the variable,
method, class or any statement. It can also be used to hide program code for

specific time.

Types of Java Comments

There are 3 types of comments in java.

JAVA PROGRAMMING Page 5


1. Single Line Comment
2. Multi Line Comment
3. Documentation Comment

Java Single Line Comment


The single line comment is used to comment only one line.
Syntax:
1. //This is single line comment

Example:
public class CommentExample1 {

public static void main(String[] args) {int i=10;//Here, i is a variable


System.out.println(i);
}

}
Output: 10

Java Multi Line Comment


The multi line comment is used to comment multiple lines of code.
Syntax:
/* Thisis
multi linecomment
*/
Example:
public class CommentExample2 {

public static void main(String[] args) {

/* Let's declare and print variable in java. */


int i=10; System.out.println(i);
}}

Output: 10

JAVA PROGRAMMING Page 6


Java Documentation Comment
The documentation comment is used to create documentation API. To create documentation API,
you needto use javadoc tool.
Syntax:
/** Thisis
documentationcomment
*/
Example:
/** The Calculator class provides methods to get addition and subtraction of given 2 numbers.*/

public class Calculator {

/** The add() method returns addition of given numbers.*/

public static int add(int a, int b){return a+b;}

/** The sub() method returns subtraction of given numbers.*/

public static int sub(int a, int b){return a-b;} }

Compile it by javac tool: javac Calculator.java


Execute it by using : java Calculator

Now, there will be HTML files created for your Calculator class in the current directory.
Open the HTMLfiles and see the explanation of Calculator class provided through documentation
comment.

Data Types
Data types represent the different values to be stored in the variable. In java, there are two types of data types:
1) Primitive data types 2) Non-primitive data types
Data Type Default Value Default size

boolean false 1 bit

char '\u0000' 2 byte

byte 0 1 byte

short 0 2 byte

int 0 4 byte

long 0L 8 byte

float 0.0f 4 byte

double 0.0d 8 byte

JAVA PROGRAMMING Page 7


Java Variable Example: Add Two Numbers
class Simple{
public static void main(String[] args){
int a=10; int b=10;int c=a+b;
System.out.println(c);
}}
Output:20

Variables and Data Types in Java


Variable is a name of memory location. There are three types of variables in java: local,
instanceand static. There are two types of data types in java: primitive and non-primitive.
Types of Variable

There are three types of variables in java:

 local variable
 instance variable
 static variable

JAVA PROGRAMMING Page 8


1) Local Variable

A variable which is declared inside the method is called local variable.

2) Instance Variable

A variable which is declared inside the class but outside the method, is called instance
variable . Itis
not declared as static.

3) Static variable

A variable that is declared as static is called static variable. It cannot be local.We will have
detailed
learning of these variables in next chapters.
Example to understand the types of variables in java

class A{
int data=50;//instance variable static int m=100;//static variablevoid method(){
int n=90;//local variable
}
}//end of class

Constants in Java

A constant is a variable which cannot have its value changed after declaration. It uses the 'final'
keyword.

Syntax
modifier final dataType variableName = value; //global constant

modifier static final dataType variableName = value; //constant within a c

JAVA PROGRAMMING Page 9


Scope and Life Time of Variables
The scope of a variable defines the section of the code in which the variable is visible.
As a general rule, variables that are defined within a block are not accessible outside
that block. The lifetime of a variable refers to how long the variable exists before it is
destroyed. Destroying variables refers to deallocating the memory that was allotted to
the variables when declaring it. We have written a few classes till now. You might have
observed that not all variables are the same. The ones declared in the body of a method
were different from those that were declared in the class itself. There are three types of
variables: instance variables, formal parameters or local variables and local variables.

Instance variables
Instance variables are those that are defined within a class itself and not in any method
or constructor of the class. They are known as instance variables because every instance
of the class (object) contains a copy of these variables. The scope of instance variables
is determined by the access specifier that is applied to these variables. We have already
seen about it earlier. The lifetime of these variables is the same as the lifetime of the
object to which it belongs. Object once created do not exist for ever. They are
destroyed by the garbage collector of Java when there are no more reference to that
object. We shall see about Java's automatic garbage collector later on.

Argument variables
These are the variables that are defined in the header oaf constructor or a method. The
scope of these variables is the method or constructor in which they are defined. The
lifetime is limited to the time for which the method keeps executing. Once the method
finishes execution, these variables are destroyed.

Local variables
A local variable is the one that is declared within a method or a constructor (not in the
header). The scope and lifetime are limited to the method itself. One important
distinction between these three types of variables is that access specifiers can be
applied to instance variables only and not to argument or local variables. In addition to
the local variables defined in a method, we also have variables that are defined in bocks
life an if block and an else block. The scope and is the same as that of the blockitself.

JAVA PROGRAMMING Page 10


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

 Arithmetic Operator,

 shift Operator,

 Relational Operator,

 Bitwise Operator,

 Logical Operator,

 Ternary Operator and

 Assignment Operator.

Operators Hierarchy

JAVA PROGRAMMING Page 11


Expressions
Expressions are essential building blocks of any Java program, usually created to produce a
new value, although sometimes an expression simply assigns a value to a variable.
Expressions are built using values, variables, operators and method calls.

Types of Expressions
While an expression frequently produces a result, it doesn't always. There are three
types ofexpressions in Java:
 Those that produce a value, i.e. the result of (1 + 1)

 Those that assign a variable, for example (v = 10)

 Those that have no result but might have a "side effect" because an expression can
include a wide range of elements such as method invocations or increment operators
that modify the state (i.e. memory) of a program.

Java Type casting and Type conversion


Widening or Automatic Type Conversion
Widening conversion takes place when two data types are automatically converted. This
happenswhen:

 The two data types are compatible.


 When we assign value of a smaller data type to a bigger data type.

For Example, in java the numeric data types are compatible with each other but no
automatic conversion is supported from numeric type to char or boolean. Also, char and
boolean are not compatible with each other.

Narrowing or Explicit Conversion


If we want to assign a value of larger data type to a smaller data type we perform
explicit typecasting or narrowing.

 This is useful for incompatible data types where automatic conversion cannot be done.

JAVA PROGRAMMING Page 12


 Here, target-type specifies the desired type to convert the specified value to.

Java Enum
Enum in java is a data type that contains fixed set of constants.
It can be used for days of the week (SUNDAY, MONDAY, TUESDAY, WEDNESDAY,
THURSDAY, FRIDAY and SATURDAY) , directions (NORTH, SOUTH, EAST and
WEST) etc. The java enum constants are static and final implicitly. It is available from
JDK 1.5.Java Enums can be thought of as classes that have fixed set of constants.

Simple example of java enum

class EnumExample1{

public enum Season { WINTER, SPRING, SUMMER, FALL }


public static void main(String[] args) {for (Season s : Season.values()) System.out.println(s); }}

Output:
WINTER
SPRING
SUMMER
FALL

Control Flow Statements


The control flow statements in Java allow you to run or skip blocks of code when special
conditions are met.

The “if” Statement

The “if” statement in Java works exactly like in most programming languages. With the
help of “if” you can choose to execute a specific block of code when a predefined condition
is met. Thestructure of the “if” statement in Java looks like this:

if (condition) {
// execute this code
}
JAVA PROGRAMMING Page 13
The condition is Boolean. Boolean means it may be true or false. For example you may put
amathematical equation as condition. Look at this full example:

Creating a Stand-Alone Java Application

Write a main method that runs your program. You can write this method anywhere. In this
example, I'll write my main method in a class called Main that has no other methods. For
example:
public class Main3.
{
public static void main(String[] args)
{
Game.play();
}
}
Make sure your code is compiled, and that you have tested it thoroughly. if you're using
Windows, you will need to set your path to include Java, if you haven't done so already.
This is a delicate operation. Open Explorer, and look inside C:\ProgramFiles\Java, and you
should see some version of the JDK. Open this folder, and then open the bin folder. Select
the complete path from the top of the Explorer window, andpress Ctrl-C to copy it.

JAVA PROGRAMMING Page 14


Next, find the "My Computer" icon (on your Start menu or desktop), right-click it, and
select properties. Click on the Advanced tab, and then click on the Environment variables
button. Look at the variables listed for all users, and click on the Path variable. Do not
delete the contents of this variable! Instead, edit the contents by moving the cursor to the
right end, entering a semicolon (;), and pressing Ctrl-V to paste the path you copied earlier.
Then go ahead and save your changes. (If you have any Cmd windows open, you will need
to closethem.)
If you're using Windows, go to the Start menu and type "cmd" to run a program that brings
up a command prompt window. If you're using a Mac or Linux machine, run the Terminal
program to bring up a command prompt. In Windows, type dir at the command prompt to
list the contents of the current directory. On a Mac or Linux machine, type ls to do this.
Now we want to change to the directory/folder that contains your compiled code. Look at
the listing of sub-directories within this directory, and identify which one contains your
code. Type cd followed by the name of that directory, to change to that directory. For
example, to change to a directory called Desktop, you would type:

cd Desktop
To change to the parent directory, type:
cd ..
Every time you change to a new directory, list the contents of that directory to see where to
gonext. Continue listing and changing directories until you reach the directory that contains
your .class files. If you compiled your program using Java 1.6, but plan to run it on a Mac,
you'll need torecompile your code from the command line, by typing:

javac -target 1.5 *.java

Now we'll create a single JAR file containing all of the files needed to run your program.

Arrays

Java provides a data structure, the array, which stores a fixed-size sequential collection of
elements of the same type. An array is used to store a collection of data, but it is often more
useful to think of an array as a collection of variables of the same type. Instead of declaring
individual variables, such as number0, number1, ..., and number99, you declare one array
variable such as numbers and use numbers[0], numbers[1], and ..., numbers[99] to

JAVA PROGRAMMING Page 15


represent individual variables. This tutorial introduces how to declare array variables,
create arrays, and process arrays using indexed variables.

Declaring Array Variables:


To use an array in a program, you must declare a variable to reference the array, and you
must specify the type of array the variable can reference. Here is the syntax for declaring
an array variable:

dataType[] arrayRefVar; // preferred way.


or
dataType arrayRefVar[]; // works but not preferred way.

Note: The style dataType[] arrayRefVar is preferred. The style dataType


arrayRefVar[] comes from the C/C++ language and was adopted in Java to accommodate
C/C++ programmers.

Example:
The following code snippets are examples of this syntax:

double[] myList;or // preferred way.


double myList[];

Creating Arrays: // works but not preferred way.

JAVA PROGRAMMING Page 16


You can create an array by using the new operator with the following syntax:

arrayRefVar = new dataType[arraySize];

The above statement does two things:


 It creates an array using new dataType[arraySize];
 It assigns the reference of the newly created array to the variable arrayRefVar.

Declaring an array variable, creating an array, and assigning the reference of the array
to thevariable can be combined in one statement, as shown below:

dataType[] arrayRefVar = new dataType[arraySize];

Alternatively you can create arrays as follows:

dataType[] arrayRefVar = {value0, value1, ..., valuek};

The array elements are accessed through the index. Array indices are 0-based; that is,
they startfrom 0 to arrayRefVar.length-1.
Example:
Following statement declares an array variable, myList, creates an array of 10
elements ofdouble type and assigns its reference to myList:

double[] myList = new double[10];

Following picture represents array myList. Here, myList holds ten double values and the
indicesare from 0 to 9.

JAVA PROGRAMMING Page 17


Processing Arrays:
When processing array elements, we often use either for loop or for each loop because all
of theelements in an array are of the same type and the size of the array is known.

Example:
Here is a complete example of showing how to create, initialize and process arrays:

public class TestArray


{
public static void main(String[] args) {
double[] myList = {1.9, 2.9, 3.4, 3.5};
// Print all the array elements
for (int i = 0; i < myList.length; i++) {
System.out.println(myList[i] + " ");
}
// Summing all elements
double total = 0;
for (int i = 0; i < myList.length; i++) {
total += myList[i];
}
System.out.println("Total is " + total);
// Finding the largest element
double max = myList[0];
for (int i = 1; i < myList.length; i++) {
if (myList[i] > max) max = myList[i];
}
System.out.println("Max is " + max);
}
}

JAVA PROGRAMMING Page 18


This would produce the following result:

1.9
2.9
3.4
3.5
Total is 11.7
Max is 3.5
public class TestArray {
public static void main(String[] args) {
double[] myList = {1.9, 2.9, 3.4, 3.5};
// Print all the array elements
for (double element: myList) {
System.out.println(element);
}}}

Java Console Class


The Java Console class is be used to get input from console. It provides methods to read
texts and passwords. If you read password using Console class, it will not be displayed to
the user. The java.io.Console class is attached with system console internally. The Console
class isintroduced since 1.5.
Let's see a simple example to read text from console.
 String text=System.console().readLine();
 System.out.println("Text is: "+text);

Java Console Example


import java.io.Console;
class ReadStringTest
{
public static void main(String args[])
{
Console c=System.console(); System.out.println("Enter your name: ");
String n=c.readLine(); System.out.println("Welcome "+n); }
}

JAVA PROGRAMMING Page 19


Output

Enter your name: Nakul Jain


Welcome Nakul Jain

Constructors
Constructor in java is a special type of method that is used to initialize the object.
Java constructor is invoked at the time of object creation. It constructs the values i.e.
provides datafor the object that is why it is known as constructor.
There are basically two rules defined for the constructor.
 Constructor name must be same as its class name

 Constructor must have no explicit return type

Types of java constructors


There are two types of constructors:
 Default constructor (no-arg constructor)

 Parameterized constructor

Java Default Constructor


A constructor that have no parameter is known as default constructor.
Syntax of default constructor:
<class_name>
(){}
Example of default constructor

In this example, we are creating the no-arg constructor in the Bike class. It will be invoked
atthe time of object creation.
class Bike1{
Bike1(){System.out.println("Bike is created");}
public static void main(String args[]){Bike1 b=new Bike1();

Output: Bike is created

}}
JAVA PROGRAMMING Page 20
Example of parameterized constructor
In this example, we have created the constructor of Student class that have two parameters.
Wecan have any number of parameters in the constructor.
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();
}}

Output:

111 Karan
222 Aryan

Constructor Overloading in Java

Constructor overloading is a technique in Java in which a class can have any number of
constructors that differ in parameter lists.The compiler differentiates these constructors by
taking into account the number of parameters in the list and their type.

Example of Constructor Overloading


class Student5{
int id; String name;int age;
Student5(int i,String n){id = i;
name = n;
}
JAVA PROGRAMMING Page 21
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();

JAVA PROGRAMMING Page 22


s2.display();
}}

Output:

111 Karan 0
222 Aryan 25

Java Copy Constructor

There is no copy constructor in java. But, we can copy the values of one object to another
likecopy constructor in C++.

There are many ways to copy the values of one object into another in java. They are:

oBy constructor

oBy assigning the values of one object into another


oBy clone() method of Object class

In this example, we are going to copy the values of one object into another using java
constructor.
class Student6{
int id;
String name;
Student6(int i,String n){id = i;
name = n;
}

Student6(Student6 s){id = s.id;


name =s.name;
}
void display(){System.out.println(id+" "+name);}

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


Student6 s2 = new Student6(s1); s1.display();

JAVA PROGRAMMING Page 23


s2.display();
}}

Output:

111 Karan
111 Karan

JAVA PROGRAMMING Page 24


Java-Methods

A Java method is a collection of statements that are grouped together to perform an


operation. When you call the System.out.println() method, for example, the system
actually executes several statements in order to display a message on the console.

Now you will learn how to create your own methods with or without return values, invoke
a method with or without parameters, and apply method abstraction in the program design.

CreatingMethod

Considering the following example to explain the syntax of a method −

Syntax

public static int methodName(int a, int b) {


// body
}

Here,

 public static − modifier

 int − return type

 methodName − name of the method

 a, b − formal parameters

 int a, int b − list of parameters

Method definition consists of a method header and a method body. The same is shown
in thefollowing syntax −

Syntax

JAVA PROGRAMMING Page 25


modifier returnType nameOfMethod (Parameter List) {
// method body
}

The syntax shown above includes −

 modifier − It defines the access type of the method and it is optional to


use.

 returnType − Method may return a value.

 nameOfMethod − This is the method name. The method signature


consists of the methodname and the parameter list.

JAVA PROGRAMMING Page 26


 Parameter List − The list of parameters, it is the type, order, and
number of parameters of a method. These are optional, method may contain zero
parameters.

 method body − The method body defines what the method does with
the statements.

Call by Value and Call by Reference in Java

There is only call by value in java, not call by reference. If we call a method passing a
value, it is known as call by value. The changes being done in the called method, is not
affected in the calling method.

Example of call by value in java

In case of call by value original value is not changed. Let's take a simple example:

class Operation{

int data=50;

void change(int data){

data=data+100;//changes will be in the local variable only

public static void main(String args[]){ Operation op=new Operation();


System.out.println("before change "+op.data);op.change(500);
System.out.println("after change "+op.data);

Output:before change 50
after change 50
}

In Java, parameters are always passed by value. For example, following program prints i =
10, j = 20.
// Test.javaclass Test {
// swap() doesn't swap i and j
public static void swap(Integer i, Integer j) {Integer temp = new Integer(i);
JAVA PROGRAMMING Page 27
i = j;
j = temp;
}
public static void main(String[] args) { Integer i = new Integer(10);
Integer j = new Integer(20);swap(i, j);

System.out.println("i = " + i + ", j = " + j);

JAVA PROGRAMMING Page 28


}
}

Static Fields and Methods

The static keyword in java is used for memory management mainly. We can apply java
static keyword with variables, methods, blocks and nested class. The static keyword
belongs to the classthan instance of the class.

The static can be:

1. variable (also known as class variable)

2. method (also known as class method)

3. block

4. nested class

Java static variable

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

o The static variable can be used to refer the common property of all objects
(that is not unique foreach object) e.g. company name of employees,college name of students etc.

o The static variable gets memory only once in class area at the time of class
loading.

Advantage of static variable

It makes your program memory efficient (i.e it saves memory).

JAVA PROGRAMMING Page 29


Understanding problem without static variable

1. class Student{

2. int rollno;

3. String name;

4. String college="ITS";5. }

Example of static variable

//Program of static variable

class Student8{

int rollno;

JAVA PROGRAMMING Page 30


String name;

static String college ="ITS";Student8(int r,String n){ rollno = r;


name = n;

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

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


new Student8(222,"Aryan");

s1.display();

s2.display();

}}

Output:111 Karan ITS

222 Aryan ITS

Java 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 object of a class.

o A static method can be invoked without the need for creating an


instance of a class.

o static method can access static data member and can change the value
of it.

Example of static method

//Program of changing the common property of all objects(static field).

class Student9{int rollno; String name;


static String college = "ITS";

static void change(){college = "BBDIT";


JAVA PROGRAMMING Page 31
}

Student9(int r, String n){rollno = r;

name = n;

JAVA PROGRAMMING Page 32


}

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

public static void main(String args[]){Student9.change();


Student9 s1 = new Student9 (111,"Karan"); Student9 s2 = new Student9 (222,"Aryan");
Student9 s3 = new Student9 (333,"Sonoo");s1.display();
s2.display();

s3.display();

Output:111 Karan BBDIT


222 Aryan BBDIT
333 Sonoo BBDIT
}}

Java static block

o Is used to initialize the static data member.

o It is executed before main method at the time of class loading.

Example of static blockclass A2{


static{System.out.println("static block is invoked");} public static void main(String
args[]){ System.out.println("Hello main");

Output: static block is invoked


Hello main
}}

Access Control

Access Modifiers in java

There are two types of modifiers in java: access modifiers and non-access modifiers.

JAVA PROGRAMMING Page 33


The access modifiers in java specifies accessibility (scope) of a data member, method,
constructoror class.

There are 4 types of java access modifiers:

JAVA PROGRAMMING Page 34


1. private

2. default

3. protected

4. public

private access modifier

The private access modifier is accessible only within class.

Simple example of private access modifier

In this example, we have created two classes A and Simple. A class contains private data
member and private method. We are accessing these private members from outside the
class, so there is compile time error.
class A{

private int data=40;

private void msg(){System.out.println("Hello java");} }

public class Simple{

public static void main(String args[]){A obj=new A();


System.out.println(obj.data);//Compile Time Errorobj.msg();//Compile Time Error
}}

2) default access modifier

If you don't use any modifier, it is treated as default bydefault. The default modifier is
accessible only within package.

Example of default access modifier

In this example, we have created two packages pack and mypack. We are accessing the A
class from outside its package, since A class is not public, so it cannot be accessed from
outside the package.
//save by A.javapackage pack; class A{
void msg(){System.out.println("Hello");}

JAVA PROGRAMMING Page 35


//save by B.java package mypack;import pack.*;

JAVA PROGRAMMING Page 36


class B{

public static void main(String args[]){ A obj = new A();//Compile Time Error
obj.msg();//Compile Time Error } }

In the above example, the scope of class A and its method msg() is default so it cannot be
accessed from outside the package.

3) protected access modifier

The protected access modifier is accessible within package and outside the package but
through inheritance only.

The protected access modifier can be applied on the data member, method and constructor.
It can'tbe applied on the class.

Example of protected access modifier

In this example, we have created the two packages pack and mypack. The A class of pack
package is public, so can be accessed from outside the package. But msg method of this
package is declared as protected, so it can be accessed from outside the class only through
inheritance.

//save by A.javapackage pack; public class A{


protected void msg(){System.out.println("Hello");} }

//save by B.javapackage mypack; import pack.*; class B extends A{


public static void main(String args[]){B obj = new B();
obj.msg();

}}

Output:Hello

4) public access modifier

The public access modifier is accessible everywhere. It has the widest scope among all
othermodifiers.
JAVA PROGRAMMING Page 37
JAVA PROGRAMMING Page 38
Example of public access modifier

//save by A.javapackage pack; public class A{


public void msg(){System.out.println("Hello");} }

//save by B.java package mypack;import pack.*; class B{


public static void main(String args[]){A obj = new A();
obj.msg();

}}

Output:Hello

Understanding all java access modifiers

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

Access within within outside package by outside


Modifier class package subclass only package

Private Y N N N

Y Y N N
Default

Y Y Y N
Protected

Y Y Y Y
Public

this keyword in java

Usage of java this keyword

Here is given the 6 usage of java this keyword.

1. this can be used to refer current class instance variable.


JAVA PROGRAMMING Page 39
2. this can be used to invoke current class method (implicitly)

3. this() can be used to invoke current class constructor.

JAVA PROGRAMMING Page 40


4. this can be passed as an argument in the method call.
5. this can be passed as argument in the constructor call.
6. this can be used to return the current class instance from the method.

class Student{
int rollno;
String name;
float fee;
Student(int rollno,String name,float fee){
this.rollno=rollno;
this.name=name;
this.fee=fee;
}
void display(){System.out.println(rollno+" "+name+" "+fee);}
}
class TestThis2{
public static void main(String args[]){
Student s1=new Student(111,"ankit",5000f);
Student s2=new Student(112,"sumit",6000f);
s1.display();
s2.display();
}}

Output:
111 ankit 5000
112 sumit 6000

Difference between constructor and method in java

Java Constructor Java Method

Constructor is used to initialize the state of an object. Method is used to expose behaviour
an object.

Constructor must not have return type. Method must have return type.
Constructor is invoked implicitly. Method is invoked explicitly.

The java compiler provides a default constructor if you Method is not provided by compiler
don't have any constructor. any case.

Constructor name must be same as the class name. Method name may or may
be

JAVA PROGRAMMING Page 31


same as class name. There are many differences between constructors and methods. They
are given belo

Constructor Overloading in Java

Constructor overloading is a technique in Java in which a class can have any number of
constructors that differ in parameter lists.The compiler differentiates these constructors by
taking into account the number of parameters in the list and their type.

Example of Constructor Overloading


class Student5{

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();

Output:

JAVA PROGRAMMING Page 32


111 Karan 0
222 Aryan 25

Method Overloading in java

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

If we have to perform only one operation, having same name of the methods
increases thereadability of the program.

Method Overloading: changing no. of arguments

In this example, we have created two methods, first add() method performs addition
of twonumbers and second add method performs addition of three numbers.

In this example, we are creating static methods so that we don't need to create instance for
callingmethods.

class Adder{

static int add(int a,int b){return a+b;}

static int add(int a,int b,int c){return a+b+c;}

class TestOverloading1{

public static void main(String[] args){ System.out.println(Adder.add(11,11));


System.out.println(Adder.add(11,11,11));
}}

Output:

JAVA PROGRAMMING Page 33


22
33

Method Overloading: changing data type of arguments

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

JAVA PROGRAMMING Page 34


Recursion in Java
Recursion in java is a process in which a method calls itself continuously. A method in java
thatcalls itself is called recursive method.

Java Recursion Example 1: Factorial Number

public class RecursionExample3 {

static int factorial(int n){

if (n == 1)return 1;else
return(n * factorial(n-1));

}}

public static void main(String[] args) { System.out.println("Factorial of 5 is:


"+factorial(5));
}}

Output:

Factorial of 5 is: 120

Java Garbage Collection

In java, garbage means unreferenced objects.

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


In otherwords, it is a way to destroy the unused objects.

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

JAVA PROGRAMMING Page 35


Advantage of Garbage Collection

o It makes java memory efficient because garbage collector removes


the unreferencedobjects from heap memory.

o It is automatically done by the garbage collector(a part of JVM) so we


don't need to makeextra efforts.

gc() method

JAVA PROGRAMMING Page 36


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

public static void gc(){}

Simple Example of garbage collection in javapublic class TestGarbage1{


public void finalize(){System.out.println("object is garbage collected");}

public static void main(String args[]){ TestGarbage1 s1=new TestGarbage1();


TestGarbage1 s2=new TestGarbage1();s1=null;
s2=null; System.gc();

object is garbage collected


object is garbage collected
}}

Java String

string is basically an object that represents sequence of char values. An array of characters
workssame as java string. For example:

1. char[] ch={'j','a','v','a','t','p','o','i','n','t'};
2. String s=new String(ch);ssame as:
1. String s="javatpoint";

2. Java String class provides a lot of methods to perform operations on


string such as compare(), concat(), equals(), split(), length(), replace(), compareTo(),
intern(), substring()etc.
3. The java.lang.String cl

CharSequence Interface
JAVA PROGRAMMING Page 37
JAVA PROGRAMMING Page 38
The CharSequence interface is used to represent sequence of characters. It is implemented by
String, StringBuffer and StringBuilder classes. It means, we can create string in java by using
these 3 classes.

The java String is immutable i.e. it cannot be changed. Whenever we change any string, a new
instance is created. For mutable string, you can use StringBuffer and StringBuilderclasses.
There are two ways to create String object:
1. By string literal
2. By new keyword

String Literal

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

1. String s="welcome";

Each time you create a string literal, the JVM checks the string constant pool first. If the string
already exists in the pool, a reference to the pooled instance is returned. If string doesn't exist
in the pool, a new string instance is created and placed in the pool. For example:

1. String s1="Welcome";
2. String s2="Welcome";//will not create new instance

By new keyword
1. 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 heap (non pool).

Java String Example


public class StringExample{
public static void main(String args[]){
String s1="java";//creating string by java string literal
char ch[]={'s','t','r','i','n','g','s'};
String s2=new String(ch);//converting char array to string
String s3=new String("example");//creating java string by new keyword
System.out.println(s1);
System.out.println(s2);System.out.println(s3);
}}

Java
strings
example

Immutable String in Java


In java, string objects are immutable. Immutable simply means unmodifiable or
unchangeable.Once string object is created its data or state can't be changed but a new string
object is created. Let's try to understand the immutability concept by the example given below:
class Testimmutablestring{public static void main(String args[]){ String s="Sachin";
s.concat(" Tendulkar");//concat() method appends the string at the end
System.out.println(s);//will print Sachin because stringsare immutable objects
}}
Output:Sachin
class Testimmutablestring1{public static void main(String args[]){
String s="Sachin";s=s.concat(
"
Tendulkar"
);
System.out.println(s);
} } Output:Sachin Tendulkar
Final Keyword in Java

The final keyword in java is used to restrict the user. The java final keyword can be used in many
context. Final can be:

1. variable
2. method
3. class

The final keyword can be applied with the variables, a final variable that have no value it is called
blank final variable or uninitialized final variable. It can be initialized in the constructor only. The
blank final variable can be static also which will be initialized in the static block only. We will
have detailed learning of these. Let's first learn the basics of final keyword.

1) Java final variable

If you make any variable as final, you cannot change the value of final variable(It will be
constant).

Example of final variable

There is a final variable speedlimit, we are going to change the value of this variable, but It can't
be changed because final variable once assigned a value can never be changed.

 If you want to prevent the members of superclass from being overridden in the subclasses
then declare them as final using the keyword final as a modifier.
 Variable of a class can be declared as final indicating that the value of that particular
variable cannot be changed.
 Ex: final int a =10;
 Local variable cannot be declared as final variable.

2) Java final method

Methods can be declared final indicating that they can be overridden in subclasses. It ensures
that the functionality defined in this method will never be altered in anyway.
Ex: final void display ()
{
Body of the display method
}

Garbage collection
Garbage collection in Java is the process by which Java programs perform automatic
memory management. Java programs compile to bytecode that can be run on a Java Virtual
Machine, or JVM for short. When Java programs run on the JVM, objects are created on the
heap, which is a portion of memory dedicated to the program. Eventually, some objects will no
longer be needed. The garbage collector finds these unused objects and deletes them to free up
memory.
In C/C++, a programmer is responsible for both the creation and destruction of objects.
Usually, programmer neglects the destruction of useless objects. Due to this negligence, at a
certain point, sufficient memory may not be available to create new objects, and the entire
program will terminate abnormally, causing OutOfMemoryErrors.
But in Java, the programmer need not care for all those objects which are no longer in use.
Garbage collector destroys these objects. The main objective of Garbage Collector is to free
heap memory by destroying unreachable objects. The garbage collector is the best example of
the Daemon thread as it is always running in the background.

Working of Garbage collection

Java garbage collection is an automatic process. Automatic garbage collection is the


process of looking at heap memory, identifying which objects are in use and which are not,
and deleting the unused objects. An in-use object, or a referenced object, means that some part
of your program still maintains a pointer to that object. An unused or unreferenced object is no
longer referenced by any part of your program. So the memory used by an unreferenced object
can be reclaimed. The programmer does not need to mark objects to be deleted explicitly. The
garbage collection implementation lives in the JVM.
Garbage collection (GC) is a memory recovery feature built into programming languages
such as C# and Java. A GC-enabled programming language includes one or more garbage
collectors (GC engines) that automatically free up memory space that has been allocated to
objects no longer needed by the program.

Advantages of Garbage Collection in Java


 It makes java memory-efficient because the garbage collector removes the
unreferenced objects from heap memory.
 It is automatically done by the garbage collector(a part of JVM), so we don’t need
extra effort.

You might also like