Unit 1 Notes
Unit 1 Notes
Java Basics:-
1. Introduction
2. History of Java
3. Java buzzwords
4. Data types
5. Variables
6. Scope and Life time of variables
7. Arrays
8. Operators
9. Expressions
10. Control statements
11. Type conversion and casting
12. Simple Java programs
13. Concepts of classes
14. Objects
15. Constructors
16. Methods
17. Access control
18. This keyword
19. Garbage collection
20. Overloading methods
21. Parameter passing
22. Recursion
23. Exploring String Class
1.Introduction:-
1. What is Java?
2. Application
3. Java Platforms / Editions
4. The requirement for Java Hello World Example
5. Creating Hello World Example
6. Parameters used in First Java Program
7. how many ways we can write a Java program?
8. How to set path in Java?
9. OOPS concepts?
10. Memory Allocation?
1.What is Java?
Java is a programming language and a platform. Java is a high level, robust, object-oriented and secure
programming language.
Java was developed by Sun Microsystems (which is now the subsidiary of Oracle) in the year 1995. James
Gosling is known as the father of Java. Before Java, its name was Oak. Since Oak was already a registered
company, so James Gosling and his team changed the name from Oak to Java.
Platform: Any hardware or software environment in which a program runs, is known as a platform. Since Java
has a runtime environment (JRE) and API, it is called a platform.
2.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) Standalone Application
Standalone applications are also known as desktop applications or window-based applications. These are
traditional software that we need to install on every machine. Examples of standalone application are Media
player, antivirus, etc. AWT and Swing are used in Java for creating standalone applications.
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 an enterprise application.
It has advantages like 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.
It is a Java programming platform. It includes Java programming APIs such as java.lang, java.io, java.net,
java.util, java.sql, java.math etc. It includes core topics like OOPs, String, Regex, Exception, Inner classes,
Multithreading, I/O Stream, Networking, AWT, Swing, Reflection, Collection, etc.
It is an enterprise platform that is mainly used to develop web and enterprise applications. It is built on top of the
Java SE platform. It includes topics like Servlet, JSP, Web Services, EJB(Enterprise Java Bean), JPA(Java
Persistence API (Application Programming Interface)), etc.
3) Java ME (Java Micro Edition)
4) JavaFX
It is used to develop rich internet applications. It uses a lightweight user interface API.
4.The requirement for Java Hello World Example
For executing any Java program, the following software or application must be properly installed.
o Install the JDK if you don't have installed it, download the JDK and install it.
o Set path of the jdk/bin directory. http://www.javatpoint.com/how-to-set-path-in-java
o Create the Java program
o Compile and run the Java program
1. class Simple{
2. public static void main(String args[]){
3. System.out.println("Hello Java");
4. }
5. }
Output:
Hello Java
Can you save a Java source file by another name than the class name?
Yes, if the class is not public. It is explained in the figure given below:
Compile time:
Javac Hard.java
Runtime:
Java FirstProgram
What happens at runtime?
At runtime, the following steps are performed:
To write the simple program, you need to open notepad by start menu -> All Programs -> Accessories
-> Notepad and write a simple program as we have shownbelow:
As displayed in the above diagram, write the simple program of Java in notepad and saved it as
Simple.java. In order to compile and run the above program, you need to open the command prompt
by start menu -> All Programs -> Accessories -> command prompt. When we have done with all the
steps properly, it shows the following output:
If you are saving the Java source file inside the JDK/bin directory, the path is not required to be set because all
the tools will be available in the current directory.
However, if you have your Java file outside the JDK/bin folder, it is necessary to set the path of JDK.
1. Temporary
2. Permanent
For Example:
set path=C:\Program Files\Java\jdk1.6.0_23\bin
o Go to MyComputer properties -> advanced tab -> environment variables -> new tab of user variable -> write path
in variable name -> write path of bin folder in variable value -> ok -> ok -> ok
For Example:
1) Go to MyComputer properties
2) Click on the advanced tab
3) Click on environment variables
8) Click on ok button
9) Click on ok button
Now your permanent path is set. You can now execute any program of java from any drive.
Difference between Pop(Procedure Oriented Programming)
and OOP(Object Oriented Programming)
Java definition: - Java is also an object-oriented, class-based, static, strong, robust, safe,
and high-level programming language. It was developed by James Gosling in 1995.
3 Approach It uses the top- It uses the It also uses the bottom-up approach.
down approach. bottom-up
approach.
5 Code The code is The code is The code is executed by the JVM.
Execution executed executed
directly. directly.
10 Source File The source file The source file The source file has a .java extension.
Extension has a .c has a .cpp
extension. extension.
11 Pointer It supports It also supports Java does not support the pointer
Concept pointer. pointer. concept because of security.
12 Union and It supports It also supports It does not support union and
Structure union and union and structure data types.
Datatype structure data structure data
types. types.
13 Pre-processor It uses pre- It uses pre- It does not use directives but uses
Directives processor processor packages.
directives such directives such
as #include, as #include,
#define, etc. #define,
#header, etc.
16 Memory It uses the It uses new and It uses a garbage collector to manage
Management calloc(), delete operator the memory.
malloc(), free(), to manage the
and realloc() memory.
methods to
manage the
memory.
20 Array Size An array should An array should An array can be declared without
be declared with be declared with declaring the size. For example, int num[].
size. For size.
example, int
num[10].
8. OOPS Concepts?
OOPS concepts are as follows:
1. Class
2. Object
3. Method and method passing
4. Pillars of OOPs
Abstraction
Encapsulation
Inheritance
Polymorphism
Compile-time polymorphism
Runtime polymorphism
A class is a user-defined blueprint or prototype from which objects are created. It represents the set of properties or methods that
are common to all objects of one type. Using classes, you can create multiple objects with the same behavior instead of writing their
code multiple times. This includes classes for objects occurring more than once in your code. In general, class declarations can
include these components in order:
1. Modifiers: A class can be public or have default access (Refer to this for details).
2. Class name: The class name should begin with the initial letter capitalized by convention.
3. Superclass (if any): The name of the class’s parent (superclass), if any, preceded by the keyword extends. A class can only
extend (subclass) one parent.
4. Interfaces (if any): A comma-separated list of interfaces implemented by the class, if any, preceded by the keyword
implements. A class can implement more than one interface.
5. Body: The class body is surrounded by braces, { }.
An object is a basic unit of Object-Oriented Programming that represents real-life entities. A typical Java program creates many
objects, which as you know, interact by invoking methods. The objects are what perform your code, they are the part of your c ode
visible to the viewer/user. An object mainly consists of:
1. State: It is represented by the attributes of an object. It also reflects the properties of an object.
2. Behavior: It is represented by the methods of an object. It also reflects the response of an object to other objects.
3. Identity: It is a unique name given to an object that enables it to interact with other objects.
4. Method: A method is a collection of statements that perform some specific task and return the result to the caller. A method
can perform some specific task without returning anything. Methods allow us to reuse the code without retyping it, which is
why they are considered time savers. In Java, every method must be part of some class, which is different from languages like
C, C++, and Python.
Java
public class GFG {
Pillar 1: Abstraction
Data Abstraction is the property by virtue of which only the essential details are displayed to the user. The trivial or non -essential
units are not displayed to the user. Ex: A car is viewed as a car rather than its individual components.
Data Abstraction may also be defined as the process of identifying only the required characteristics of an object, ignoring the
irrelevant details. The properties and behaviors of an object differentiate it from other objects of similar type and also he lp in
classifying/grouping the object.
Consider a real-life example of a man driving a car. The man only knows that pressing the accelerators will increase the car speed
or applying brakes will stop the car, but he does not know how on pressing the accelerator, the speed is actually increasing. He does
not know about the inner mechanism of the car or the implementation of the accelerators, brakes etc. in the car. This is what
abstraction is.
In Java, abstraction is achieved by interfaces and abstract classes. We can achieve 100% abstraction using interfaces.
The abstract method contains only method declaration but not implementation.
Demonstration of Abstract class
Java
//abstract class
abstract class GFG{
//abstract methods declaration
abstract void add();
abstract void mul();
abstract void div();
}
Pillar 2: Encapsulation
It is defined as the wrapping up of data under a single unit. It is the mechanism that binds together the code and the data it manipulates.
Another way to think about encapsulation is that it is a protective shield that prevents the data from being accessed b y the code
outside this shield.
Technically, in encapsulation, the variables or the data in a class is hidden from any other class and can be accessed only
through any member function of the class in which they are declared.
In encapsulation, the data in a class is hidden from other classes, which is similar to what data-hiding does. So, the terms
“encapsulation” and “data-hiding” are used interchangeably.
Encapsulation can be achieved by declaring all the variables in a class as private and writing public methods in the class to set
and get the values of the variables.
Demonstration of Encapsulation:
Java
//Employee class contains private data called employee id and employee name
class Employee {
private int empid;
private String ename;
}
Pillar 3: Inheritance
Inheritance is an important pillar of OOP (Object Oriented Programming). It is the mechanism in Java by which one class is allowed
to inherit the features (fields and methods) of another class. We are achieving inheritance by using extends keyword. Inheritance is
also known as “is-a” relationship.
Let us discuss some frequently used important terminologies:
Superclass: The class whose features are inherited is known as superclass (also known as base or parent class).
Subclass: The class that inherits the other class is known as subclass (also known as derived or extended or child class). The
subclass can add its own fields and methods in addition to the superclass fields and methods.
Reusability: Inheritance supports the concept of “reusability”, i.e. when we want to create a new class and there is already a
class that includes some of the code that we want, we can derive our new class from the existing class. By doing this, we are
reusing the fields and methods of the existing class.
Demonstration of Inheritance :
Java
Pillar 4: Polymorphism
It refers to the ability of object-oriented programming languages to differentiate between entities with the same name efficiently.
This is done by Java with the help of the signature and declaration of these entities. The ability to appear in many forms is
called polymorphism.
E.g.
Java
sleep(1000) //millis
sleep(1000,2000) //millis,nanos
Polymorphism in java can be classified into two types:
Java
// Overloaded sum().
// This sum takes two int parameters
public int sum(int x, int y)
{
return (x + y);
}
// Overloaded sum().
// This sum takes three int parameters
public int sum(int x, int y, int z)
{
return (x + y + z);
}
// Overloaded sum().
// This sum takes two double parameters
public double sum(double x, double y)
{
return (x + y);
}
// Driver code
public static void main(String args[])
{
Sum s = new Sum();
System.out.println(s.sum(10, 20));
System.out.println(s.sum(10, 20, 30));
System.out.println(s.sum(10.5, 20.5));
}
}
Output
30
60
31.0
10.Java Memory Allocation
What is Stack Memory?
Stack in java is a section of memory which contains methods, local variables, and
reference variables. Stack memory is always referenced in Last-In-First-Out order. Local
variables are created in the stack.
1. Heap
2. Stack
3. Code
4. Static
int x = int a + 3;
The variable X in m1 will also be created in the frame for m1 in the stack. (See image
below).
Method m1 is calling method m2. In the stack java, a new frame is created for m2 on top
of the frame m1.
Variable b and c will also be created in a frame m2 in a stack.
public void m2(int b){
boolean c;
}
Same method m2 is calling method m3. Again a frame m3 is created on the top of the
stack (see image below).
Now let say our method m3 is creating an object for class “Account,” which has
two instances variable int p and int q.
Account {
Int p;
Int q;
}
Here is the code for method m3
public void m3(){
Account ref = new Account();
// more code
}
The statement new Account() will create an object of account in heap.
The reference variable “ref” will be created in a stack java.
The assignment “=” operator will make a reference variable to point to the object in the
Heap.
Once the method has completed its execution. The flow of control will go back to the
calling method. Which in this case is method m2.
Once method m2 has completed its execution. It will be popped out of the stack, and all
its variable will be flushed and no longer be available for use.
Eventually, the flow of control will return to the start point of the program. Which
usually, is the “main” method.
1) James Gosling, Mike Sheridan, and Patrick Naughton initiated the Java language project in June 1991. The
small team of sun engineers called Green Team.
2) 2) Initially it was designed for small, embedded systems in electronic appliances like set-top boxes.
3) 3) Firstly, it was called "Greentalk" by James Gosling, and the file extension was .gt.
4) 4) After that, it was called Oak and was developed as a part of the Green project.
According to James Gosling, "Java was one of the top choices along with Silk". Since Java was so unique, most
of the team members preferred Java than other names.
8) Java is an island in Indonesia where the first coffee was produced (called Javacoffee). It is a kind of espresso
bean. Java name was chosen by James Gosling while having a cup of coffee nearby his office.
10) Initially developed by James Gosling at Sun Microsystems (which is now a subsidiary of Oracle Corporation)
and released in 1995.
11) In 1995, Time magazine called Java one of the Ten Best Products of 1995.
12) JDK 1.0 was released on January 23, 1996. After the first release of Java, there have been many additional
features added to the language. Now Java is being used in Windows applications, Web applications, enterprise
applications, mobile applications, cards, etc. Each new version adds new features in Java.
Since Java SE 8 release, the Oracle corporation follows a pattern in which every even version is release in March
month and an odd version released in September month.
3. Java buzzwords
A list of the most important features of the Java language is given below.
1. Simple
2. Object-Oriented
3. Platform independent
4. Secured
5. Robust
6. Architecture neutral
7. Portable
8. High Performance
9. Distributed
10. Multithreaded
11. Dynamic
12. Interpreted
1)Simple
Java is very easy to learn, and its syntax is simple, clean and easy to understand. According to Sun Microsystem,
Java language is a simple programming language because:
o Java syntax is based on C and C++ (so easier for programmers to learn it after C++).
o Java has removed many complicated and rarely-used features, for example, explicit pointers, operator
overloading, etc.
o There is no need to remove unreferenced objects because there is an Automatic Garbage Collection in
Java.
2)Object-oriented
OOP stands for Object-Oriented Programming. OOP is a programming paradigm in which every program is
follows the concept of object. In other words, OOP is a way of writing programs based on the object concept.
1. Object
2. Class
3. Inheritance
4. Polymorphism
5. Abstraction
6. Encapsulation
3)Platform Independent
Any hardware or software environment in which a program runs, is known as a platform. Since Java has a runtime
environment (JRE) and API, it is called a platform.
Java code can be executed on multiple platforms, for example, Windows, Linux, Sun Solaris, Mac/OS, etc. Java code is
compiled by the compiler and converted into byte code. This byte code is a platform-independent code because it can be
run on multiple platforms, i.e., Write Once and Run Anywhere (WORA).
4)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 rights to objects.
o Security Manager: It determines what resources a class can access such as reading and writing to the local disk.
Java language provides these securities by default. Some security can also be provided by an application
developer explicitly through SSL(Secure socket layer), JAAS(java Authentication and authorization service),
Cryptography, etc.
5)Robust
The English mining of Robust is strong. Java is robust because:
6)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. Java occupies 4 bytes of memory for both 32 and 64-bit architectures in Java.
7)Portable
Java is portable because it facilitates you to carry the Java byte code to any platform. It doesn't require any
implementation.
8)High-performance
Java is faster than other traditional interpreted programming languages because Java byte code 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.
9)Distributed
Java is distributed because it facilitates users to create distributed applications in Java. RMI(remote method
invocation) and EJB(Enterprise java bean) 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.
10)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.
11)Dynamic
Java is a dynamic language. It supports the 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).
12)Interpreted:-
Java is a interpreter language. It is convert byte code to executable code in jvm. It is design to
read the input source code and then translate the executable code instruction by instruction.
3.Data types
Data types specify the different sizes and values that can be stored in the variable.In java, data types are classified
into two types and they are as follows.
The following table provides more description of each primitive data type.
Let's look at the following example java program to illustrate primitive data types in java and their default values.
Example
public class PrimitiveDataTypes {
bytei;
shor j;
in k;
lon l;
float m;
double n;
charch;
boolean p;
System.out.println("i = " + obj.i + ", j = " + obj.j + ", k = " + obj.k + ", l = " + obj.l);
}
}
When we run the above example code, it produces the following output.
Example
public class NonPrimitiveDataTypes {
String str;
When we run the above example code, it produces the following output.
Primitive Vs Non-primitive Data Types
Primitive Data Type Non-primitive Data Type
These are built-in data types These are created by the users
5.Variables
Defination:-A variable is a named memory location used to store a data value. A
variable can be defined as a container that holds a data value.A variable is assigned
with a data type.
In java, we use the following syntax to create variables.
Syntax
data_type variable_name;
(or)
data_type variable_name_1, variable_name_2,...;
(or)
data_type variable_name = value;
(or)
data_type variable_name_1 = value, variable_name_2 = value,...;
Scope of a Variable
A variable can be declared and defined inside a class, method, or block. It defines the
scope of the variable where a variable is available to use. i.e. the visibility or
accessibility of a variable. Variable declared inside a block or method are not visible to
outside. If we try to do so, we will get a compilation error.
Example:-
class DemoScope
{ //class scope
public static void main(String args[])
{ //main method scope
int x;
x=10;
if(x==10)
{ //condition scope
int y=20;
System.out.println("X and Y:"+x+" "+y);
x=y*2;
}
//y=100;//get compilation error
System.out.println("X is:"+x);}
}
Life Time of a Variable:
The lifetime of a variable is the time during which the variable stays in memory
and is therefore accessible during program execution. The variables that are
local to a method are created the moment the method is activated and are
destroyed when the activation of the method terminates.
Ex:-
class DemoLifeTime
{
public static void main(String args[])
{
int x;
for(x=0;x<3;x++)
{
int y=-1;
System.out.println("Y is"+y);
y=20;
System.out.println("Y is "+y);
}// After loop completion y is destroyed no longer can use
}
}
7.Arrays
Java Arrays
Defination:-array is a collection of similar type of elements which has contiguous
memory location.
An array is a collection of similar data values with a single name. An array can also be defined
as, a special type of variable that holds multiple values of the same data type at a time.
In java, arrays are objects and they are created dynamically using new operator. Every array in
java is organized using index values. The index value of an array starts with '0' and ends with
'size-1'. We use the index value to access individual elements of an array.
In java, there are two types of arrays and they are as follows.
One Dimensional Array or Single Dimensional Array
Creating an array
Syntax
data_type array_name[ ] = new data_type[size];(or)
data_type[ ] array_name = new data_type[size];
Let's look at the following example program.
Example
public class ArrayExample {
public static void main(String[] args) {
int list[] = new int[5];
list[0] = 10;
System.out.println("Value at index 0 - " + list[0]);
System.out.println("Length of the array - " + list.length);
}
}
When we run the above example code, it produces the following output.In java, an array can also be initialized at the time
of its declaration. When an array is initialized
at the time of its declaration, it need not specify the size of the array and use of the new operator.
Here, the size is automatically decided based on the number of values that are initialized.
Example
int list[ ] = {10, 20, 30, 40, 50};
Example
public class ArrayExample {
public static void main(String[] args) {
short list[] = null;list[0] = 10;
System.out.println("Value at index 0 - " + list[0]);
}
}
When we run the above example code, it produces the following output.
Example
public class ArrayExample {public static void main(String[] args) {
short list[] = {10, 20, 30};
list[4] = 10;
System.out.println("Value at index 0 - " + list[0]);
}
}
When we run the above example code, it produces the following output.
the following example program to display sum of all the lements in a list. Example
import java.util.Scanner;
public class ArrayExample {
public static void main(String[] args) {
Scanner read = new Scanner(System.in);
int size, sum = 0;
System.out.print("Enter the size of the list: ");
size = read.nextInt();
short list[] = new short[size];
System.out.println("Enter any " + size + " numbers: ");
for(int i = 0; i < size; i++) // Simple for statement
list[i] = read.nextShort();
for(int i : list) // for-each statement
sum = sum + i;
System.out.println("Sum of all elements: " + sum);
}
}
When we run the above example code, it produces the following output.
Multidimensional Array
Two Dimensional Array:-
In java, we can create an array with multiple dimensions. We can create 2-dimensional, 3-
dimensional, or any dimensional array.
In Java, multidimensional arrays are arrays of arrays. To create a multidimensional array
variable, specify each additional index using another set of square brackets. We use the
following syntax to create two-dimensional array.
Syntax to Declare Multidimensional Array in Java
1. dataType[][] arrayRefVar; (or)
2. dataType [][]arrayRefVar; (or)
3. dataType arrayRefVar[][]; (or)
4. dataType []arrayRefVar[]; Example to instantiate Multidimensional Array in Java
Syntax
data_type array_name[ ][ ] = new data_type[rows][columns];
(or)
data_type[ ][ ] array_name = new data_type[rows][columns];
When we create a two-dimensional array, it created with a separate index for rows and columns.
The individual element is accessed using the respective row index followed by the column
index. A multidimensional array can be initialized while it has created using the following
syntax.
Syntax
data_type array_name[ ][ ] = {{value1, value2}, {value3, value4}, {value5, value6},...};
When an array is initialized at the time of declaration, it need not specify the size of the array
and use of the new operator. Here, the size is automatically decided based on the number of
values that are initialized.
Example Program:-
public class Multidimensional {
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();
}
}
}Out Put:-
123
245
445
Syntax:-
Data_type array_name[][]=new data_type[n][];\\ n means number
of rows
array_name[]=new datatype[n1];\\n1 means number of columns
(or)
Int arr_name[][]={{value1,value2},{value1,value2,value3}};Ex:-
int arr[][] = new int[3][];
arr[0] = new int[3];
arr[1] = new int[4];
arr[2] = new int[2];
Example Program:-
class TestJaggedArray{
public static void main(String[] args){
//declaring a 2D array with odd columns
int arr[][] = new int[3][];
arr[0] = new int[3];
arr[1] = new int[4];
arr[2] = new int[2];
//initializing a jagged array
int count = 0;
for (int i=0; i<arr.length; i++)
for(int j=0; j<arr[i].length; j++)
arr[i][j] = count++;
//printing the data of a jagged array
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
}
}
}
Out Put:-
012
3456
78
}} Output:
268
6 8 10
Output:
666
12 12 12
18 18 18
Example:-
int[ ][ ][ ] x = new int[2][3][4];
For example:
x[0][0][0] refers to the data in the first table, first row, and first column.
x[1][0][0] refers to the data in the second table, first row, and first column.
x[1][2][3] refers to the data in the second table, thrid row, and fourth
column.Example program:-
package arraysProgram;
public class ThreeDArray {
public static void main(String[] args)
{
int[ ][ ][ ] x;
x = new int[3][3][3];
for(int i = 0; i < 3; i++)
{
for(int j = 0; j < 3; j++)
for(int k = 0; k < 3; k++)
x[i][j][k] = i + 1;
}
for(int i = 0; i < 3; i++)
{
System.out.println("Table-" +(i + 1));
for(int j = 0; j < 3; j++)
{
for(int k = 0; k < 3; k++)
System.out.print(x[i][j][k] +" ");System.out.println();
}
System.out.println();
}
}
}
Out Put:-
Table-1
111
111
111
Table-2
222
222
222
Table-3
333
333
333
8.Operators
An Operator is a symbol that performs an operation. An operator acts on some variables, called operands to get the
desired result, For example: +, -, *, / etc.
There are many types of operators in Java which are given below:
o Unary Operator,
o Arithmetic Operator,
o Bitwise Operator,
o Assignment Operator,
o Relational Operator,
o Logical Operator,
o Ternary Operator and
o Special Operator.
1.Unary Operator: -
The Java unary operators require only one operand. Unary operators are used to perform various operations.
Negating an expression ~
Bitwise Not complement
Logical or boolean !
Example:-
class UnaryOperator
{
public static void main(String args[])
{
int a=10,b=-5,d=10;
boolean c=true;
System.out.println(a);//10
System.out.println(a++);//10(11)
System.out.println(++a);//12
System.out.println(a--);//12(11)
System.out.println(--a);//10
System.out.println(~d);//-11
System.out.println(~b);//4
System.out.println(!c);//false
System.out.println(!c);//false
}
}
2.Arithmetic Operators:
In java, arithmetic operators are used to performing basic mathematical operations like addition, subtraction,
multiplication, division, modulus, increment, decrement, etc.,
+ Addition 10 + 5 = 15
- Subtraction 10 - 5 = 5
* Multiplication 10 * 5 = 50
/ Division 10 / 5 = 2
Example:-
Ex:-
public class UnaryOperator{
public static void main(String args[]){
int a=5;
int b=6;
int c=2;
int d=-2;
System.out.println(a&b);//4
System.out.println(a|b);//7
System.out.println(a^b);//3
System.out.println(a<<c);//20 5*2^2=5*4=20
System.out.println(a>>c);//1 5/2^2=5/4=1
System.out.println(d>>c);-1
System.out.println(a>>>c);//1
System.out.println(d>>>c);//1073741823
}
}
Assignment Operator:-
The operator is used to store some value into a variable .
The assignment operators are used to assign right-hand side value (Rvalue) to the left-hand side variable (Lvalue).
The assignment operator is used in different variants along with arithmetic operators. The following table
describes all the assignment operators in the java programming language.
Assignment operator
+= Add both left and right-hand side values and store the result into left-hand side variable A += 10
-= Subtract right-hand side value from left-hand side variable value and store the result into left- A -= B
hand side variable
*= Multiply right-hand side value with left-hand side variable value and store the result into left- A *= B
hand side variable
/= Divide left-hand side variable value with right-hand side variable value and store the result A /= B
into the left-hand side variable
division
%= Divide left-hand side variable value with right-hand side variable value and store the A %= B
remainder into the left-hand side variable
modulus
|= Logical OR assignment -
Ex:-
public class UnaryOperator{
public static void main(String args[]){
int a=10,b=10;
System.out.println(a+=b);//20
System.out.println(a-=b);//10
System.out.println(a*=b);//100
System.out.println(a/=b);//10
System.out.println(a%=b);//0
System.out.println(a&=b);//0
System.out.println(a|=b);10
System.out.println(a^=b);0
}
}
< Returns TRUE if the first value is smaller than second value otherwise returns FALSE 10 < 5 is FALSE
> Returns TRUE if the first value is larger than second value otherwise returns FALSE 10 > 5 is TRUE
Less than operator
<= Returns TRUE if the first value is smaller than or equal to second value otherwise 10 <= 5 is
returns FALSE FALSE
>= Returns TRUE if the first value is larger than or equal to second value otherwise 10 >= 5 is TRUE
returns FALSE
!= Returns TRUE if both values are not equal otherwise returns FALSE 10 != 5 is TRUE
}
}
Logical Operators
The logical operators are the symbols that are used to combine multiple conditions into one condition. The
following table provides information about logical operators.
| Logical OR - Returns FALSE if all conditions are FALSE otherwise returns TRUE false | true =>
true
^ Logical XOR - Returns FALSE if all conditions are same otherwise returns TRUE true ^ true =>
false
! Logical NOT - Returns TRUE if condition is FLASE and returns FALSE if it is !false => true
TRUE
&& short-circuit AND - Similar to Logical AND (&), but once a decision is finalized it false & true =>
does not evaluate remianing. false
|| short-circuit OR - Similar to Logical OR (|), but once a decision is finalized it does not false | true =>
evaluate remianing. true
��� The operators &, |, and ^ can be used with both boolean and integer data type values. When they are used
with integers, performs bitwise operations and with boolean, performs logical operations.
��� Logical operators and Short-circuit operators both are similar, but in case of short-circuit operators once
the decision is finalized it does not evaluate remaining expressions.
Ex:-
class Test4
{
public static void main(String args[])
{
int a=10,b=20;
System.out.println(a>b & a<b);//false
System.out.println(a>b && a<b);//false
System.out.println(a>b | a<b);//true
System.out.println(a>b || a<b);//true
System.out.println(a>b ^ a<b);//true
System.out.println(!(a>b));//true
}
}
Conditional or Ternary Operator:-
The Ternary operator is a conditional operator that decreases the length of code while performing comparisons and
conditionals. This method is an alternative for using if-else and nested if-else statements. The order of execution for this
operator is from left to right.
Ex:-
class Test4
{
public static void main(String args[])
{
int a=10,b=20;
int max=a>b?a:b;
System.out.println(max);
}
}
Special Operators:-
1.instanceof operator
2.Member or Dot Operator
3.Cast Operator
1.Instanceof: This operator allows us to determine that the object belongs to a particular class or
not.Ex: Person instanceof Student (Object instanceof Class)2. . (Dot) Operator: This operator
is used to access the instance variables and the methods of class objectsEx: Person.age;
Person.getdata();
3.Cast Operator:- Cast operator is used to convert one data type to other.
class Test4
{
double b=20;
int a=(int)b;
public static void main(String args[])
{
Test4 t=new Test4();
System.out.println(t instanceof Test4);
System.out.println(t.b);
System.out.println(t.a);
}
}
9. Expressions
In any programming language, if we want to perform any calculation or to frame any condition etc., we use a set
of symbols to perform the task. These set of symbols makes an expression.In the java programming language, an
expression is defined as follows.
An expression is a collection of operators and operands that represents a specific value.
In the above definition, an operator is a symbol that performs tasks like arithmetic operations, logical operations,
and conditional operations, etc.
Operands are the values on which the operators perform the task. Here operand can be a direct value or variable
or address of memory location.
Expression Types
In the java programming language, expressions are divided into THREE types. They are as follows.
Infix Expression
Postfix Expression
Prefix Expression
Infix Expression
The expression in which the operator is used between operands is called infix expression.
The infix expression has the following general structure.
Example
Postfix Expression
The expression in which the operator is used after operands is called postfix expression.
The postfix expression has the following general structure.
Example
Prefix Expression
The expression in which the operator is used before operands is called a prefix expression.
The prefix expression has the following general structure.
Example
10.Control statements
Java Control Statements
In java, the default execution flow of a program is a sequential order. But the sequential order of execution flow
may not be suitable for all situations. Sometimes, we may want to jump from line to another line, we may want
to skip a part of the program, or sometimes we may want to execute a part of the program again and again. To
solve this problem, java provides control statements.
In java, the control statements are the statements which will tell us that in which order the instructions are getting
executed. The control statements are used to control the order of execution according to our requirements. Java
provides several control statements, and they are classified as follows.
if statement
if-else statement
if-else-if statement
nested if statement
switch statement
if statement in java
In java, we use the if statement to test a condition and decide the execution of a block of statements based on that
condition result. The if statement checks, the given condition then decides the execution of a block of statements.
If the condition is True, then the block of statements is executed and if it is False, then the block of statements is
ignored. The syntax and execution flow of if the statement is as follows.
Java Program
import java.util.Scanner;
if((num % 5) == 0) {
System.out.println("We are inside the if-block!");
System.out.println("Given number is divisible by 5!!");
}
In the above execution, the number 12 is not divisible by 5. So, the condition becomes False and the condition
is evaluated to False. Then the if statement ignores the execution of its block of statements.
When we enter a number which is divisible by 5, then it produces the output as follows.
Java Program
import java.util.Scanner;
if((num % 2) == 0) {
System.out.println("We are inside the true-block!");
System.out.println("Given number is EVEN number!!");
}
else {
System.out.println("We are inside the false-block!");
System.out.println("Given number is ODD number!!");
}
Syntax
if(condition_1){
if(condition_2){
inner if-block of statements;
...
}
...
}
Java Program
import java.util.Scanner;
public class NestedIfStatementTest {
Syntax
if(condition_1){
condition_1 true-block;
...
}
else if(condition_2){
condition_2 true-block;
condition_1 false-block too;
...
}
Java Program
import java.util.Scanner;
else
System.out.println("\nThe largest number is " + num3) ;
The switch statement contains multiple blocks of code called cases and a single case is executed based on the variable
which is being switched.
switch( value )
{
case 0: System.out.println("ZERO") ; break ;
case 1: System.out.println("ONE") ; break ;
case 2: System.out.println("TWO") ; break ;
case 3: System.out.println("THREE") ; break ;
case 4: System.out.println("FOUR") ; break ;
case 5: System.out.println("FIVE") ; break ;
case 6: System.out.println("SIX") ; break ;
case 7: System.out.println("SEVEN") ; break ;
case 8: System.out.println("EIGHT") ; break ;
case 9: System.out.println("NINE") ; break ;
default: System.out.println("Not a Digit") ;
}
while statement
do-while statement
for statement
for-each statement
Java Program
ipublic class WhileTest {
int num = 1;
Java Program
public class DoWhileTest {
do {
System.out.println(num);
num++;
}while(num <= 10);
Java Program
public class ForTest {
The for-each statement has the following syntax and execution flow diagram.
Let's look at the following example java code.
Java Program
public class ForEachTest {
for(int i : arrayList) {
System.out.println("i = " + i);
}
break
continue
return
The floowing picture depictes the execution flow of the break statement.
Let's look at the following example java code.
Java Program
public class JavaBreakStatement {
for(int i : list) {
if(i == 30)
break;
System.out.println(i);
}
Java Program
public class JavaContinueStatement {
for(int i : list) {
if(i == 30)
continue;
System.out.println(i);
}
Java Program
import java.util.Scanner;
verify: if (value % 2 == 0) {
System.out.println("\nYou won!!!");
System.out.println("Your score is " + i*10 + " out of 30.");
break reading;
} else {
System.out.println("\nSorry try again!!!");
System.out.println("You let with " + (3-i) + " more options...");
continue reading;
}
}
}
}
In java, the return statement used with both methods with and without return type. In the case of a method with
the return type, the return statement is mandatory, and it is optional for a method without return type.
When a return statement used with a return type, it carries a value of return type. But, when it is used without a
return type, it does not carry any value. Instead, simply transfers the execution control.
Let's look at the following example java code.
Java Program
import java.util.Scanner;
public class JavaReturnStatementExample {
int value;
int readValue() {
Scanner read = new Scanner(System.in);
System.out.print("Enter any number: ");
return this.value=read.nextInt();
}
obj.showValue(obj.readValue());
}
}
Double->float->long->int->char->short->byte
Syntax:
Target_datatype: It is the data type in which we want to convert the destination data type. The variable defines
a value that is to be converted in the target_data type. Let's understand the concept of type casting with an
example.
Suppose, we want to convert the float data type into int data type. Here, the target data type is smaller than the
source data because the size of int is 4 bytes, and the size of the float data type is 8 bytes. And when we change
it, the value of the float variable is truncated and convert into an integer variable. Casting can be done with a
compatible and non-compatible data type.
1. float b = 3.0;
2. int a = (int) b; // converting a float value into integer
AreaOfRectangle.java
() is Cast operator
Datatype variable=(target-type)variable;
Java Variable example:Narrowing (typecasting)
Class Simple
{
Public static void main(String args[])
{
float f=10.5f;
Int a=(int)f;
System.out.println(a);
System.out.println(f);
}
}
o/p:-
10.5
10
Byte->short->char->int->long->float->double
Suppose, we have an int data type and want to convert it into a float data type. These are data types compatible
with each other because their types are numeric, and the size of int is 4 bytes which is smaller than float data
type. Hence, the compiler automatically converts the data types without losing or truncating the values.
1. int a = 20;
2. Float b;
3. b = a; // Now the value of variable b is 20.000 /* It defines the conversion of int data type to float data type without losin
g the information. */
In the above example, the int data type is converted into the float, which has a larger size than int, and hence it
widens the source data type.
Class Simple
{
Public static void main(String args[])
{
Int a=10;
float f=a;
System.out.println(a);
System.out.println(f);
}
}
o/p:
10
10.0
Note:
1.For widening conversions,the numeric types,including integer and floating-point types are compatible with each other.
2.No automatic conversions from the numeric types to char or Boolean. also, char and Boolean are not compatible with
each other.
1 Type casting is a mechanism in which one data Type conversion allows a compiler to convert one data type
type is converted to another data type using a to another data type at the compile time of a program or code.
casting () operator by a programmer.
2 It can be used both compatible data type and Type conversion is only used with compatible data types, and
incompatible data type. hence it does not require any casting operator.
3 It requires a programmer to manually casting one It does not require any programmer intervention to convert
data into another type. one data type to another because the compiler automatically
compiles it at the run time of a program.
4 It is used while designing a program by the It is used or take place at the compile time of a program.
programmer.
5 When casting one data type to another, the When converting one data type to another, the destination
destination data type must be smaller than the type should be greater than the source data type.
source data.
6 It is also known as narrowing conversion because It is also known as widening conversion because one smaller
one larger data type converts to a smaller data data type converts to a larger data type.
type.
8 There is a possibility of data or information being In type conversion, data is unlikely to be lost when
lost in type casting. converting from a small to a large data type.
Example:-
1. class FibonacciExample1{
2. public static void main(String args[])
3. {
4. int n1=0,n2=1,n3,i,count=10;
5. System.out.print(n1+" "+n2);//printing 0 and 1
6.
7. for(i=2;i<count;++i)//loop starts from 2 because 0 and 1 are already printed
8. {
9. n3=n1+n2;
10. System.out.print(" "+n3);
11. n1=n2;
12. n2=n3;
13. }
14.
15. }}
Output:-
0 1 1 2 3 5 8 13 21 34
In the above array, the first duplicate will be found at the index 4 which is the duplicate of the element (2) present
at index 1. So, duplicate elements in the above array are 2, 3 and 8.
Output:-
Output:-
Duplicate elements in given array:
2
3
8
4.Java Program to count the total number of vowels and consonants in
a string
In this program, our task is to count the total number of vowels and consonants present in the given string.
As we know that, the characters a, e, i, o, u are known as vowels in the English alphabet. Any character other
than that is known as the consonant.
To solve this problem, First of all, we need to convert every upper-case character in the string to lower-case so
that the comparisons can be done with the lower-case vowels only not upper-case vowels, i.e.(A, E, I, O, U).
Then, we have to traverse the string using a for or while loop and match each character with all the vowels, i.e.,
a, e, i, o, u. If the match is found, increase the value of count by 1 otherwise continue with the normal flow of the
program.
Example:-
1. public class CountVowelConsonant {
2. public static void main(String[] args) {
3.
4. //Counter variable to store the count of vowels and consonant
5. int vCount = 0, cCount = 0;
6.
7. //Declare a string
8. String str = "This is a really simple sentence";
9.
10. //Converting entire string to lower case to reduce the comparisons
11. str = str.toLowerCase();
12.
13. for(int i = 0; i < str.length(); i++) {
14. //Checks whether a character is a vowel
15. if(str.charAt(i) == 'a' || str.charAt(i) == 'e' || str.charAt(i) == 'i' || str.charAt(i) == 'o' || str.charAt(i) == 'u')
{
16. //Increments the vowel counter
17. vCount++;
18. }
19. //Checks whether a character is a consonant
20. else if(str.charAt(i) >= 'a' && str.charAt(i)<='z') {
21. //Increments the consonant counter
22. cCount++;
23. }
24. }
25. System.out.println("Number of vowels: " + vCount);
26. System.out.println("Number of consonants: " + cCount);
27. }
28. }
Output:-
Number of vowels: 10
Number of consonants: 17
13.Concepts of Classes:-
Definition: - A class is a template or blueprint from which you can create an individual
object. Class doesn’t consume any space. It is logical entity.
Ex:-Car
Example Program:-
New:-
The new keyword is used to allocate memory at runtime. All objects get memory in heap memory area.
Syntax:-
<class_name> <object_name>=new <class_name>();
(Or)
<class_name> <object_name>;
<object_name>=new <class_name>();
class Car
{
String color="red";
int weight=50;
int speed=100;
String model="1";
void startCar()
{
System.out.println("car Started");
}
void changeGear()
{
System.out.println("Gear Changed");
}
void slowDown()
{
System.out.println("Going slowly");
}
void brake()
{
System.out.println("Sudden Brake");
}
public static void main(String args[])// objects are always create in main method because JVM is
executed main method directly
{
Car bmw=new Car();
Car ferrari;
ferrari=new Car();
System.out.println(bmw.color);//calling variable
ferrari.color="block";//initializing a value through object
System.out.println(ferrari.color);
bmw.startCar();//calling method
ferrari.startCar();
}
}
Output:-
red
block
car Started
car Started
15.Constructors
In Java, a constructor is a block of codes similar to the method. It is called when an instance of the class is created.
At the time of calling constructor, memory for the object is allocated in the memory.
Every time an object is created using the new() keyword, at least one constructor is called.
It calls a default constructor if there is no constructor available in the class. In such case, Java compiler provides
a default constructor by default.
There are two types of constructors in Java: no-arg constructor, and parameterized constructor.
Note: It is called constructor because it constructs the values at the time of object creation. It is not necessary to
write a constructor for a class. It is because java compiler creates a default constructor if your class doesn't have
any.
Rules for creating Java constructor
There are two rules defined for the constructor.
Note: We can use access modifiers while declaring a constructor. It controls the object creation. In other words,
we can have private, protected, public or default constructor in Java.
Output:
Bike is created
Rule: If there is no constructor in a class, compiler automatically creates a default constructor.
The default constructor is used to provide the default values to the object like 0, null, etc., depending on the type.
Output:
0 null
0 null
Explanation:In the above class,you are not creating any constructor so compiler provides you a default
constructor. Here 0 and null values are provided by default constructor.
Java Parameterized Constructor
A constructor which has a specific number of parameters is called a parameterized constructor.
The parameterized constructor is used to provide different values to distinct objects. However, you can provide
the same values also.
Output:
111 Karan
222 Aryan
Output:
111 Karan 0
222 Aryan 25
A constructor must not have a return type. A method must have a return type.
The Java compiler provides a default constructor if you don't have The method is not provided by the compiler
any constructor in a class. in any case.
The constructor name must be same as the class name. The method name may or may not be same as
the class name.
16.Methods
What is a method in Java?
A method is a block of code or collection of statements or a set of code grouped together to perform a certain
task or operation. It is used to achieve the reusability of code. We write a method once and use it many times.
We do not require to write code again and again. It also provides the easy modification and readability of code,
just by adding or removing a chunk of code. The method is executed only when we call or invoke it.
Method Declaration
The method declaration provides information about method attributes, such as visibility, return-type, name, and
arguments. It has six components that are known as method header, as we have shown in the following figure.
Method Signature: Every method has a method signature. It is a part of the method declaration. It includes
the method name and parameter list.
Access Specifier: Access specifier or modifier is the access type of the method. It specifies the visibility of the
method. Java provides four types of access specifier:
o Public: The method is accessible by all classes when we use public specifier in our application.
o Private: When we use a private access specifier, the method is accessible only in the classes in which it is defined.
o Protected: When we use protected access specifier, the method is accessible within the same package or subclasses
in a different package.
o Default: When we do not use any access specifier in the method declaration, Java uses default access specifier by
default. It is visible only from the same package only.
Return Type: Return type is a data type that the method returns. It may have a primitive data type, object,
collection, void, etc. If the method does not return anything, we use void keyword.
Method Name: It is a unique name that is used to define the name of a method. It must be corresponding to the
functionality of the method. Suppose, if we are creating a method for subtraction of two numbers, the method
name must be subtraction(). A method is invoked by its name.
Parameter List: It is the list of parameters separated by a comma and enclosed in the pair of parentheses. It
contains the data type and variable name. If the method has no parameter, left the parentheses blank.
Method Body: It is a part of the method declaration. It contains all the actions to be performed. It is enclosed
within the pair of curly braces.
Naming a Method
While defining a method, remember that the method name must be a verb and start with a lowercase letter. If
the method name has more than two words, the first name must be a verb followed by adjective or noun. In the
multi-word method name, the first letter of each word must be in uppercase except the first word. For example:
It is also possible that a method has the same name as another method name in the same class, it is known
as method overloading.
Types of Method
There are two types of methods in Java:
o Predefined Method
o User-defined Method
Predefined Method
In Java, predefined methods are the method that is already defined in the Java class libraries is known as
predefined methods. It is also known as the standard library method or built-in method. We can directly use
these methods just by calling them in the program at any point. Some pre-defined methods are length(), equals(),
compareTo(), sqrt(), etc. When we call any of the predefined methods in our program, a series of codes related
to the corresponding method runs in the background that is already stored in the library.
Each and every predefined method is defined inside a class. Such as print() method is defined in
the java.io.PrintStream class. It prints the statement that we write inside the method. For
example, print("Java"), it prints Java on the console.
Demo.java
Output:
The maximum number is: 9
In the above example, we have used three predefined methods main(), print(), and max(). We have used these
methods directly without declaration because they are predefined. The print() method is a method
of PrintStream class that prints the result on the console. The max() method is a method of the Math class that
returns the greater of two numbers.
In the above method signature, we see that the method signature has access specifier public, non-access
modifier static, return type int, method name max(), parameter list (int a, int b). In the above example, instead
of defining the method, we have just invoked the method. This is the advantage of a predefined method. It makes
programming less complicated.
Similarly, we can also see the method signature of the print() method.
User-defined Method
The method written by the user or programmer is known as a user-defined method. These methods are modified
according to the requirement.
Let's create a user defined method that checks the number is even or odd. First, we will define the method.
We have defined the above method named findevenodd(). It has a parameter num of type int. The method does
not return any value that's why we have used void. The method body contains the steps to check the number is
even or odd. If the number is even, it prints the number is even, else prints the number is odd.
How to Call or Invoke a User-defined Method
Once we have defined a method, it should be called. The calling of a method in a program is simple. When we
call or invoke a user-defined method, the program control transfer to the called method.
1. import java.util.Scanner;
2. public class EvenOdd
3. {
4. public static void main (String args[])
5. {
6. //creating Scanner class object
7. Scanner scan=new Scanner(System.in);
8. System.out.print("Enter the number: ");
9. //reading value from the user
10. int num=scan.nextInt();
11. //method calling
12. findEvenOdd(num);
13. }
In the above code snippet, as soon as the compiler reaches at line findEvenOdd(num), the control transfer to the
method and gives the output accordingly.
Let's combine both snippets of codes in a single program and execute it.
EvenOdd.java
1. import java.util.Scanner;
2. public class EvenOdd
3. {
4. public static void main (String args[])
5. {
6. //creating Scanner class object
7. Scanner scan=new Scanner(System.in);
8. System.out.print("Enter the number: ");
9. //reading value from user
10. int num=scan.nextInt();
11. //method calling
12. findEvenOdd(num);
13. }
14. //user defined method
15. public static void findEvenOdd(int num)
16. {
17. //method body
18. if(num%2==0)
19. System.out.println(num+" is even");
20. else
21. System.out.println(num+" is odd");
22. }
23. }
Output 1:
Output 2:
Let's see another program that return a value to the calling method.
In the following program, we have defined a method named add() that sum up the two numbers. It has two
parameters n1 and n2 of integer type. The values of n1 and n2 correspond to the value of a and b, respectively.
Therefore, the method adds the value of a and b and store it in the variable s and returns the sum.
Addition.java
Output:
The main advantage of a static method is that we can call it without creating an object. It can access static data
members and also change the value of it. It is used to create an instance method. It is invoked by using the class
name. The best example of a static method is the main() method.
Display.java
Output:
InstanceMethodExample.java
Output:
o Accessor Method
o Mutator Method
Accessor Method: The method(s) that reads the instance variable(s) is known as the accessor method. We can
easily identify it because the method is prefixed with the word get. It is also known as getters. It returns the value
of the private field. It is used to get the value of the private field.
Example
Mutator Method: The method(s) read the instance variable(s) and also modify the values. We can easily identify
it because the method is prefixed with the word set. It is also known as setters or modifiers. It does not return
anything. It accepts a parameter of the same data type that depends on the field. It is used to set the value of the
private field.
Example
Student.java
Syntax
Demo.java
Output:
Abstract method...
17.Access control
The access modifiers in Java specifies the accessibility or scope of a field, method, constructor, or class. We can
change the access level of fields, constructors, methods, and class by applying the access modifier on it.
1. Private: The access level of a private modifier is only within the class. It cannot be accessed from outside the class.
2. Default: The access level of a default modifier is only within the package. It cannot be accessed from outside the
package. If you do not specify any access level, it will be the default.
3. Protected: The access level of a protected modifier is within the package and outside the package through child
class. If you do not make the child class, it cannot be accessed from outside the package.
4. Public: The access level of a public modifier is everywhere. It can be accessed from within the class, outside the
class, within the package and outside the package.
Understanding Java Access Modifiers
Let's understand the access modifiers in Java by a simple table.
Private Y N N N
Default Y Y N N
Protected Y Y Y N
Public Y Y Y Y
18.This keyword
this is a reference variable that refers to the current object.
Let's understand the problem if we don't use this keyword by the example given below:
1. class Student{
2. int rollno;
3. String name;
4. float fee;
5. Student(int rollno,String name,float fee){
6. rollno=rollno;
7. name=name;
8. fee=fee;
9. }
10. void display(){System.out.println(rollno+" "+name+" "+fee);}
11. }
12. class TestThis1{
13. public static void main(String args[]){
14. Student s1=new Student(111,"ankit",5000f);
15. Student s2=new Student(112,"sumit",6000f);
16. s1.display();
17. s2.display();
18. }}
Test it Now
Output:
0 null 0.0
0 null 0.0
In the above example, parameters (formal arguments) and instance variables are same. So, we are using this
keyword to distinguish local variable and instance variable.
Output:
If local variables(formal arguments) and instance variables are different, there is no need to use this keyword like
in the following program:
Output:
1. class A5{
2. void m(){
3. System.out.println(this);//prints same reference ID
4. }
5. public static void main(String args[]){
6. A5 obj=new A5();
7. System.out.println(obj);//prints the reference ID
8. obj.m();
9. }
10. }
Test it Now
Output:
A5@22b3ea59
A5@22b3ea59
Finalize() method
It is invoked each time before the object is garbage collected.
This method can be used to perform cleanup processing.
This method is defined in Object class as
Protected void finalize(){}
gc() method
It is used to invoke the garbage collector to perform cleanup processing.
The gc() is found in System and Runtime classes.
It is static method which is used to call finalize before destroying the object.
public static void gc(){}
Example Program:-
class Animal
{
Animal(){
System.out.println("Object is created");
}
protected void finalize()
{
System.out.println("Object is destroyed");
}
}
class AnimalDemo
{
public static void main(String args[])
{
Animal a=new Animal();
a=null;//1.By assigning a null
Animal a1=new Animal();
Animal a2=new Animal();
a1=a2;//2. By assigning reference to another
new Animal();//By anonymous object
System.gc();
}
}
Output:-
Object is created
Object is created
Object is created
Object is created
Object is destroyed
Object is destroyed
Object is destroyed
20.Overloading methods
Defination:-
If a class has multiple methods having same name but different in parameters, it is known as Method Overloading.
Note:- In Java, Method Overloading is not possible by changing the return type of the method only.
1) Method Overloading: changing no. of arguments
In this example, we have created two methods, first add() method performs addition of two numbers and second
add method performs addition of three numbers.
In this example, we are creating static methods so that we don't need to create instance for calling methods.
1. class Adder{
2. static int add(int a,int b){return a+b;}
3. static int add(int a,int b,int c){return a+b+c;}
4. }
5. class TestOverloading1{
6. public static void main(String[] args){
7. System.out.println(Adder.add(11,11));
8. System.out.println(Adder.add(11,11,11));
9. }}
Test it Now
Output:
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.
1. class Adder{
2. static int add(int a, int b){return a+b;}
3. static double add(double a, double b){return a+b;}
4. }
5. class TestOverloading2{
6. public static void main(String[] args){
7. System.out.println(Adder.add(11,11));
8. System.out.println(Adder.add(12.3,12.6));
9. }}
Test it Now
Output:
22
24.9
21.Parameter passing
There are different ways in which parameter data can be passed into and out of methods and
functions. Let us assume that a function B() is called from another function A(). In this case A is
called the “caller function” and B is called the “called function or callee function”. Also, the
arguments which A sends to B are called actual arguments and the parameters of B are called formal
arguments.
Types of parameters:
Formal Parameter: A variable and its type as they appear in the prototype of the function or
method.
Syntax:
function_name(datatype variable_name)
Actual Parameter: The variable or expression corresponding to a formal parameter that appears in
the function or method call in the calling environment.
Syntax:
func_name(variable name(s));
1.Pass by Value (or) call by value: In the pass by value concept, the method is called by passing a value. So, it is called
pass by value. It does not affect the original parameter.
In case of call by value original value is not changed.
Example:-
1. class Operation{
2. int data=50;
3.
4. void change(int data){
5. data=data+100;//changes will be in the local variable only
6. }
7.
8. public static void main(String args[]){
9. Operation op=new Operation();
10.
11. System.out.println("before change "+op.data);
12. op.change(500);
13. System.out.println("after change "+op.data);
14.
15. }
16. }
Output:
before change 50
after change 50
2.Pass by Reference (or) call by reference: In the pass by reference concept, the method is called using an alias or
reference of the actual parameter. So, it is called pass by reference. It forwards the unique identifier of the object to the
method. If we made changes to the parameter's instance member, it would affect the original value.
In case of call by reference original value is changed if we made changes in the called method. If we pass object
in place of any primitive value, original value will be changed. In this example we are passing object as a value.
Let's take a simple example:
1. class Operation2{
2. int data=50;
3.
4. void change(Operation2 op){
5. op.data=op.data+100;//changes will be in the instance variable
6. }
7.
8.
9. public static void main(String args[]){
10. Operation2 op=new Operation2();
11.
12. System.out.println("before change "+op.data);
13. op.change(op);//passing object
14. System.out.println("after change "+op.data);
15.
16. }
17. }
Output:
before change 50
after change 150
22.Recursion
a method that calls itself is known as a recursive method. And, this process is known as recursion.
A physical world example would be to place two parallel mirrors facing each other. Any object in
between them would be reflected recursively.
Hence, we use the if...else statement (or similar approach) to terminate the recursive call inside the
method.
Example: Factorial of a Number Using Recursion
class Factorial {
Output:
4 factorial = 24
In the above example, we have a method named factorial() . The factorial() is called from
the main() method. with the number variable passed as an argument.
Here, notice the statement,
return n * factorial(n-1);
The factorial() method is calling itself. Initially, the value of n is 4 inside factorial() . During the next
recursive call, 3 is passed to the factorial() method. This process continues until n is equal to 0.
When n is equal to 0, the if statement returns false hence 1 is returned. Finally, the accumulated
result is passed to the main() method.
Working of Factorial Program
The image below will give you a better idea of how the factorial program is executed using
recursion.
Factorial Program using Recursion
String can be created in number of ways, here are a few ways of creating string object.
String literal is a simple string enclosed in double quotes " ". A string literal is treated as a
String object.
System.out.println(s1);
Hello Java
We can create a new string object by using new operator that allocates memory for the
object.
System.out.println(s1);
}
Hello Java
Each time we create a String literal, the JVM checks the string pool first. If the string
literal already exists in the pool, a reference to the pool instance is returned. If string does
not exist in the pool, a new string object is created, and is placed in the pool. String
objects are stored in a special memory area known as string constant pool inside the
heap memory.
When we create a new string object using string literal, that string literal is added to the
string pool, if it is not present there already.
And, when we create another object with same string, then a reference of the string literal
already present in string pool is returned.
str2=str2.concat("world");
Concatenating String
Concat() method is used to add two or more string into a single string object. It is string
class method and returns a string object.
String s = "Hello";
System.out.println(str1);
Copy
HelloJava
2) Using + operator
Java uses "+" operator to concatenate two string objects into single one. It can also
concatenate numeric value with string object. See the below example.
String s = "Hello";
System.out.println(str1);
System.out.println(str2);
Copy
HelloJava
Java11
String Comparison
To compare string objects, Java provides methods and operators both. So we can
compare string in following three ways.
equals() method compares two strings for equality. Its general syntax is,
Copy
Example
It compares the content of the strings. It will return true if string matches, else
returns false.
String s = "Hell";
String s1 = "Hello";
String s2 = "Hello";
System.out.println(b);
b= s.equals(s1) ; //false
System.out.println(b);
Copy
true
false
2.Using == operator
The double equal (==) operator compares two object references to check whether they
refer to same instance. This also, will return true on successful match else returns false.
String s1 = "Java";
String s2 = "Java";
System.out.println(b);
Copy
true
false
Explanation
We are creating a new object using new operator, and thus it gets created in a non-pool
memory area of the heap. s1 is pointing to the String in string pool while s3 is pointing to
the String in heap and hence, when we compare s1 and s3, the answer is false.
String compareTo() method compares values and returns an integer value which tells if the
string compared is less than, equal to or greater than the other string. It compares the
String based on natural ordering i.e alphabetically. Its general syntax is.
Syntax:
Example:
String s1 = "Abhi";
String s2 = "Viraaj";
String s3 = "Abhi";
System.out.println(a);
System.out.println(a);
System.out.println(a);
-21
21
String class functions
The methods specified below are some of the most commonly used methods of
the String class in Java. We will learn about each method with help of small code
examples for better understanding.
1.charAt() method
String charAt() function returns the character located at the specified index.
System.out.println(str.charAt(2));
Output: u
NOTE: Index of a String starts from 0, hence str.charAt(2) means third character of the
String str.
2.equalsIgnoreCase() method
String equalsIgnoreCase() determines the equality of two Strings, ignoring their case (upper
or lower case doesn't matter with this method).
System.out.println(str.equalsIgnoreCase("JAVA"));
}
true
3.indexOf() method
String indexOf() method returns the index of first occurrence of a substring or a character.
indexOf() method has four override methods:
int indexOf(String str): It returns the index within this string of the first occurrence of
the specified substring.
int indexOf(int ch, int fromIndex): It returns the index within this string of the first
occurrence of the specified character, starting the search at the specified index.
int indexOf(int ch): It returns the index within this string of the first occurrence of the
specified character.
int indexOf(String str, int fromIndex): It returns the index within this string of the first
occurrence of the specified substring, starting at the specified index.
Example:
String str="StudyTonight";
String subString="Ton";
}
}
11
-1
NOTE: -1 indicates that the substring/Character is not found in the given String.
4.length() method
System.out.println(str.length());
5.replace() method
String replace() method replaces occurances of character with a specified new character.
System.out.println(str.replace('m','M'));
}
Change Me
6.substring() method
String substring() method returns a part of the string. substring() method has two override
methods.
The first argument represents the starting point of the subtring. If the substring() method is
called with only one argument, the subtring returns characters from specified starting
point to the end of original string.
If method is called with two arguments, the second argument specify the end point of
substring.
System.out.println(str.substring(4));
System.out.println(str.substring(4,7));
456789
456
7.toLowerCase() method
String toLowerCase() method returns string with all uppercase characters converted to
lowercase.
System.out.println(str.toLowerCase());
abcdef
8.toUpperCase() method
This method returns string with all lowercase character changed to uppercase.
System.out.println(str.toUpperCase());
ABCDEF
9.valueOf() method
String class uses overloaded version of valueOf() method for all primitive data types and
for type Object.
NOTE: valueOf() function is used to convert primitive data types into Strings.
System.out.println(s1);
35
10.toString() method
String toString() method returns the string representation of an object. It is declared in the
Object class, hence can be overridden by any java class. (Object class is super class of all
java classes).
System.out.println(c);
}
Whenever we will try to print any object of class Car, its toString() function will be called.
NOTE: If we don't override the toString() method and directly print the object, then it
would print the object id that contains some hashcode.
11.trim() method
This method returns a string from which any leading and trailing whitespaces has been
removed.
System.out.println(str.trim());
hello
12.contains()Method
String contains() method is used to check the sequence of characters in the given string. It
returns true if a sequence of string is found else it returns false.
boolean b = a.contains("studytonight.com");
System.out.println(b);
System.out.println(a.contains("javatpoint"));
true
false
13.endsWith() Method
String endsWith() method is used to check whether the string ends with the given suffix or
not. It returns true when suffix matches the string else it returns false.
System.out.println(a.endsWith("com"));
true
true
14.format() Method
String format() is a string method. It is used to the format of the given string.
%a floating point
%b Any type
%c character
%d integer
%e floating point
%f floating point
%g floating point
%h any type
%n none
%o integer
%s any type
%t Date/Time
%x integer
Hexadecimal Value: 7d
Char Value: a
15.getBytes() Method
String getBytes() method is used to get byte array of the specified string.
String a="studytonight";
byte[] b=a.getBytes();
for(int i=0;i<b.length;i++)
{
System.out.println(b[i]);
16.getChars() Method
String getChars() method is used to copy the content of the string into a char array.
System.out.println(ch);
catch(Exception ex)
System.out.println(ex);
Welcom
17.isEmpty() Method
String isEmpty() method is used to check whether the string is empty or not. It returns true
when length string is zero else it returns false.
{
String a="";
String b="studytonight";
System.out.println(a.isEmpty());
System.out.println(b.isEmpty());
true
false
18.join() Method
String join() method is used to join strings with the given delimiter. The given delimiter is
copied with each element
System.out.println(s);
System.out.println("Date: "+date1);
String time1 = String.join(":", "2","39","10");
System.out.println("Time: "+time1);
Welcome to studytonight.com
Date: 23/01/2020
Time: 2:39:10
19.startsWith() Method
String startsWith() is a string method in java. It is used to check whether the given string
starts with given prefix or not. It returns true when prefix matches the string else it
returns false.
System.out.println(str.startsWith("s"));
System.out.println(str.startsWith("t"));
System.out.println(str.startsWith("study",1));
}
true
false
false
Method Description
static String format(Locale l, String format, It returns formatted string with given
Object... args) locale.
StringBuffer Class
Java StringBuffer class is used to create mutable (modifiable) String objects. The StringBuffer class in Java is
the same as String class except it is mutable i.e. it can be changed.
Note: Java StringBuffer class is thread-safe i.e. multiple threads cannot access it simultaneously. So it is safe and
will result in an order.
StringBuffer() It creates an empty String buffer with the initial capacity of 16.
StringBuffer(int capacity) It creates an empty String buffer with the specified capacity as length.
StringBufferExample.java
1. class StringBufferExample{
2. public static void main(String args[]){
3. StringBuffer sb=new StringBuffer("Hello ");
4. sb.append("Java");//now original string is changed
5. System.out.println(sb);//prints Hello Java
6. }
7. }
Output:
Hello Java
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. It is available since JDK 1.5.
Constructor Description
StringBuilder() It creates an empty String Builder with the initial capacity of 16.
StringBuilder(int length) It creates an empty String Builder with the specified capacity as length.
StringBuilder Examples
.
StringBuilderExample.java
1. class StringBuilderExample{
2. public static void main(String args[]){
3. StringBuilder sb=new StringBuilder("Hello ");
4. sb.append("Java");//now original string is changed
5. System.out.println(sb);//prints Hello Java
6. }
7. }
Output:
Hello Java
2) String is slow and consumes more memory when we concatenate StringBuffer is fast and consumes less
too many strings because every time it creates new instance. memory when we concatenate t strings.
3) String class overrides the equals() method of Object class. So you StringBuffer class doesn't override the
can compare the contents of two strings by equals() method. equals() method of Object class.
4) String class is slower while performing concatenation operation. StringBuffer class is faster while performing
concatenation operation.
5) String class uses String constant pool. StringBuffer uses Heap memory
1) StringBuffer is synchronized i.e. thread safe. It StringBuilder is non-synchronized i.e. not thread
means two threads can't call the methods of safe. It means two threads can call the methods of
StringBuffer simultaneously. StringBuilder simultaneously.
2) StringBuffer is less efficient than StringBuilder. StringBuilder is more efficient than StringBuffer.
3) StringBuffer was introduced in Java 1.0 StringBuilder was introduced in Java 1.5