Unit 1 - Java

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 57

DEPARTMENT OF COMPUTATIONAL STUDIES

PROBLEM SOLVING USING JAVA


(A20CPT305)
III SEMSTER

Prepared By:
Dr. ANTONY PAUL RAJ.A M.Sc., M.Phil., B.Ed., Ph.D
Assistant Professor
Department of Computational Studies
School of Arts and Science, SMVEC
PROBLEM SOLVING USING JAVA
(A20CPT305)
UNIT I INTRODUCTION TO JAVA PROGRAMMING

The History and Evolution of Java – Byte code – Java buzzwords – Data types – Variables –
Arrays –operators – Control statements – Type conversion and casting- Basic Concepts of
OOPs – Concepts of classes and objects - Constructors – static keyword – Final with data –
Access control – This key word –Garbage collection – Nested classes and inner classes –
String class.

UNIT II INHERITANCE, PACKAGES AND INTERFACES

Inheritance: Basic concepts – Forms of inheritance – Super key word – method overriding –
Abstract classes – Dynamic method dispatch – The Object class. Packages: Defining –
Creating and Accessing –importing packages. Interfaces: Defining – Implementing –
Applying – Variables and extending interfaces.

UNIT III EXCEPTION HANDLING AND MULTITHREADING

Concepts of Exception handling – Types of exceptions – Creating own exception – Concepts


of Multithreading – creating multiple threads – Synchronization – Inter thread
communication. Enumeration: Auto boxing – Generics.

UNIT IV COLLECTIONS AND I/OSTREAM

Collections: List – Vector – Stack – Queue – De queue – Set – Sorted Set. Input / Output
Basics – Streams – Byte streams and Character streams – Reading and Writing Console –
Reading and Writing Files.

UNIT V EVENT DRIVEN PROGRAMMING AND JDBC

Events – Delegation event model – Event handling – Adapter classes. AWT: Concepts of
components –Font class – Color class and Graphics - Introduction to Swing - Layout
management - Swing Components -Java Database Connectivity – JDBC Connections –
JDBC Create Databases - Develop real time applications.
History of Java:

The history of Java is very interesting. Java was originally designed for interactive
television, but it was too advanced technology for the digital cable television industry at the
time. The history of Java starts with the Green Team. Java team members (also known as
Green Team), initiated this project to develop a language for digital devices such as set-top
boxes, televisions, etc. However, it was best suited for internet programming. Later, Java
technology was incorporated by Netscape.

The principles for creating Java programming were "Simple, Robust, Portable, Platform-
independent, Secured, High Performance, Multithreaded, Architecture Neutral, Object-
Oriented, Interpreted, and Dynamic". Java was developed by James Gosling, who is known
as the father of Java, in 1995. James Gosling and his team members started the project in the
early '90s.

Currently, Java is used in internet programming, mobile devices, games, e-business solutions,
etc. Following are given significant points that describe the history of Java.

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) Initially it was designed for small, embedded systems in electronic appliances like set-top
boxes.

3) Firstly, it was called "Greentalk" by James Gosling, and the file extension was .gt.

4) After that, it was called Oak and was developed as a part of the Green project.

Why Java was named as "Oak"?

Java History from Oak to Java

5) Why Oak? Oak is a symbol of strength and chosen as a national tree of many countries like
the U.S.A., France, Germany, Romania, etc.

6) In 1995, Oak was renamed as "Java" because it was already a trademark by Oak
Technologies.

Why Java Programming named "Java"?

7) Why had they choose the name Java for Java language? The team gathered to choose a
new name. The suggested words were "dynamic", "revolutionary", "Silk", "jolt", "DNA", etc.
They wanted something that reflected the essence of the technology: revolutionary, dynamic,
lively, cool, unique, and easy to spell, and fun to say. According to James Gosling, "Java was
one of the top choices along with Silk". Since Java was so unique, most of the team members
preferred Java than other names.
8) Java is an island in Indonesia where the first coffee was produced (called Java coffee). It is
a kind of espresso bean. Java name was chosen by James Gosling while having a cup of
coffee nearby his office.

9) Java is just a name, not an acronym.

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.

Evolution of java:

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 Mar 2014)
11. Java SE 9 (21st Sep 2017)
12. Java SE 10 (20th Mar 2018)
13. Java SE 11 (September 2018)
14. Java SE 12 (March 2019)
15. Java SE 13 (September 2019)
16. Java SE 14 (Mar 2020)
17. Java SE 15 (September 2020)
18. Java SE 16 (Mar 2021)
19. Java SE 18 (to be released by March 2022)
BYTE CODE:

 Java bytecode is the instruction set for the Java Virtual Machine.
 It acts similar to an assembler which is an alias representation of a C++ code.
 As soon as a java program is compiled, java bytecode is generated.
 In more apt terms, java bytecode is the machine code in the form of a .class file. With
the help of java bytecode we achieve platform independence in java.

Thus, we have realized that the bytecode implementation makes Java a platform-independent
language. This helps to add portability to Java which is lacking in languages like C or C++.
Portability ensures that Java can be implemented on a wide array of platforms like desktops,
mobile devices, severs and many more. Supporting this, Sun Microsystems captioned JAVA
as "write once, read anywhere" or "WORA" in resonance to thebytecode interpretation.

JAVA BUZZWORDS (or) FEATURES OF JAVA

The Java programming language is a high-level language that can be characterized by all of
the following buzzwords:

 Simple
 Object-oriented
 Distributed
 Interpreted
 Robust
 Secure
 Architecture neutral
 Portable
 High performance
 Multithreaded
 Dynamic
1. Simple:

 Java was designed to be easy for a professional programmer to learn and use
effectively.
 It’s simple and easy to learn if you already know the basic concepts of Object
Oriented Programming.
 Best of all, if you are an experienced C++ programmer, moving to Java will require
very little effort. Because Java inherits the C/C++ syntax and many of the object-
oriented features of C++, most programmers have little trouble learning Java.
 Java has removed many complicated and rarely-used features, for example, explicit
pointers, operator overloading, etc.

2. Object Oriented

 Java is true object-oriented language.


 Almost “Everything is an Object” paradigm. All program code and data reside within
objects and classes.
 The object model in Java is simple and easy to extend.
 Java comes with an extensive set of classes, arranged in packages that can be used in
our programs through inheritance.
 Object-oriented programming (OOPs) is a methodology that simplifies software
development and maintenance by providing some rules.

Basic concepts of OOPs are: Object, Class, Inheritance, Polymorphism, Abstraction


and Encapsulation

3. Distributed

 Java is designed fa or distributed environment of the Internet. Its used for creating
applications on networks.
 Java applications can access remote objects on the Internet as easily as they can do in
the local system.
 Java enables multiple programmers at multiple remote locations to collaborate and
work together on a single project.
 Java is designed for the distributed environment of the Internet because it handles
TCP/IP protocols.

4. Compiled and Interpreted

 Usually, a computer language is either compiled or Interpreted. Java combines both


this approach and makes it a two-stage system.
 Compiled: Java enables the creation of cross-platform programs by compiling into an
intermediate representation called Java Bytecode.
 Interpreted: Bytecode is then interpreted, which generates machine code that can be
directly executed by the machine that provides a Java Virtual machine.
5. Robust

 It provides many features that make the program execute reliably in a variety of
environments.
 Java is a strictly typed language. It checks code both at compile time and runtime.
 Java takes care of all memory management problems with garbage collection.
 Java, with the help of an exception handling, captures all types of serious errors and
eliminates any risk of crashing the system.

6. Secure

 Java provides a “firewall” between a networked application and your computer.


 When a Java Compatible Web browser is used, downloading can be done safely
without fear of viral infection or malicious intent.
 Java achieves this protection by confining a Java program to the Java execution
environment and not allowing it to access other parts of the computer.

7. Architecture Neutral

 Java language and Java Virtual Machine helped in achieving the goal of “write once;
run anywhere, any time, forever.”
 Changes and upgrades in operating systems, processors and system resources will not
force any changes in Java Programs.

8. Portable

 Java Provides a way to download programs dynamically to all the various types of
platforms connected to the Internet.
 It helps in generating Portable executable code.

9. High Performance

 Java performance is high because of the use of bytecode.


 The bytecode was used so that it was easily translated into native machine code.

10. Multithreaded

 Multithreaded Programs handled multiple tasks simultaneously, which was helpful in


creating interactive, networked programs.
 Java run-time system comes with tools that support multiprocess synchronization used
to construct smoothly interactive systems.

11. Dynamic

 Java is capable of linking in new class libraries, methods, and objects.


 Java programs carry with them substantial amounts of run-time type information that
is used to verify and resolve accesses to objects at runtime. This makes it possible to
dynamically linkcode in a safe and expedient manner.
DATA TYPES

Data types specify the different sizes and values that can be stored in the variable.
There are two types of data types in Java:
 Primitive data types: The primitive data types include boolean, char, byte,
short, int, long, float and double.

 Non-primitive data types: The non-primitive data types include Classes,


Interfaces, and Arrays.
Byte Data Type:
 Byte data type is a 8-bit signed two.s complement integer.
 Minimum value is -128 (-2^7)
 Maximum value is 127 (inclusive)(2^7 -1)
 Default value is 0
 Byte data type is used to save space in large arrays, mainly in place of
integers, since a byte is four times smaller than an int. Example : byte a = 100
, byte b = -50
Short Data Type:
 Short data type is a 16-bit signed two's complement integer.
 Minimum value is -32,768 (-2^15)
 Maximum value is 32,767(inclusive) (2^15 -1)
 Short data type can also be used to save memory as byte data type. A short is 2
times
 smaller than an int
 Default value is 0. Example : short s= 10000 , short r = -20000
Int Data Type
 Int data type is a 32-bit signed two's complement integer.
 Minimum value is - 2,147,483,648.(-2^31)
 Maximum value is 2,147,483,647(inclusive).(2^31 -1)
 Int is generally used as the default data type for integral values unless there is
a concern about memory.
 The default value is 0. Example : int a = 100000, int b = -200000
Long Data Type
 Long data type is a 64-bit signed two's complement integer.
 Minimum value is -9,223,372,036,854,775,808.(-2^63)
 Maximum value is 9,223,372,036,854,775,807 (inclusive). (2^63 -1)
 This type is used when a wider range than int is needed.
 Default value is 0L. Example : int a = 100000L, int b = -200000L
Float Data Type:
 Float data type is a single-precision 32-bit IEEE 754 floating point.
 Float is mainly used to save memory in large arrays of floating point numbers.
 Default value is 0.0f.
 Float data type is never used for precise values such as currency.
 Example : float f1 = 234.5f
Double Data Type
 double data type is a double-precision 64-bit IEEE 754 floating point.
 This data type is generally used as the default data type for decimal values.
generally the default choice.
 Double data type should never be used for precise values such as currency.
 Default value is 0.0d.
 Example : double d1 = 123.4
Boolean Data type:
 boolean data type represents one bit of information.
 There are only two possible values : true and false.
 This data type is used for simple flags that track true/false conditions.
 Default value is false.
 Example : boolean one = true
Char Data Type
 char data type is a single 16-bit Unicode character.
 Minimum value is '\u0000' (or 0).
 Maximum value is '\uffff' (or 65,535 inclusive).
 Char data type is used to store any character.
 Example . char letterA ='A'

JAVA VARIABLES

A variable is the name of a reserved area allocated in memory. In other words, it is a name of
the memory location. It is a combination of "vary + able" which means its value can be
changed.

Reserved Area
a

50

RAM
int a=50;//Here a is variable

Types of Variables

There are three types of variables in Java:

o local variable
o instance variable
o static variables
1) Local Variable:

 A variable declared inside the body of the method is called local variable. You can
use this variable only within that method and the other methods in the class aren't
even aware that the variable exists.
 A local variable cannot be defined with "static" keyword.

2) Instance Variable:

 A variable declared inside the class but outside the body of the method, is called
an instance variable. It is not declared as static.
 It is called an instance variable because its value is instance-specific and is not
shared among instances.

3) Static variable:

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


You can create a single copy of the static variable and share it among all the
instances of the class.
 Memory allocation for static variables happens only once when the class is loaded
in the memory.

Example to understand the types of variables in java


public class A
{
static int m=100;//static variable
void method()
{
int n=90;//local variable
}
public static void main(String args[])
{
int data=50;//instance variable
}
}//end of class

JAVA ARRAYS:

 Normally, an array is a collection of similar type of elements which has contiguous


memory location.
 Java array is an object which contains elements of a similar data type. Additionally,
The elements of an array are stored in a contiguous memory location. It is a data
structure where we store similar elements. We can store only a fixed set of elements
in a Java array.
 Array in Java is index-based, the first element of the array is stored at the 0th index,
2nd element is stored on 1st index and so on.
 Unlike C/C++, we can get the length of the array using the length member. In C/C++,
we need to use the sizeof() operator.
 In Java, array is an object of a dynamically generated class. Java array inherits the
Object class, and implements the Serializable as well as Cloneable interfaces. We can
store primitive values or objects in an array in Java. Like C/C++, we can also create
single dimentional or multidimentional arrays in Java.
 Moreover, Java provides the feature of anonymous arrays which is not available in
C/C++.

Java array Advantages:

 Code Optimization: It makes the code optimized, we can retrieve or sort the data
efficiently.
 Random access: We can get any data located at an index position.

Disadvantages:

 Size Limit: We can store only the fixed size of elements in the array. It doesn't
grow its size at runtime. To solve this problem, collection framework is used in
Java which grows automatically.

Types of Array in java:

There are two types of array.

 Single Dimensional Array


 Multidimensional Array

Single Dimensional Array in Java:

Syntax to Declare an Array in Java

dataType[] arr; (or)

dataType[]arr; (or)

dataTypearr[];

Instantiation of an Array in Java:

arrayRefVar=new datatype[size];

Example of Java Array:

//Java Program to illustrate how to declare, instantiate, initialize

//and traverse the Java array.

class Testarray{

public static void main(String args[]){


int a[]=new int[5];//declaration and instantiation

a[0]=10;//initialization

a[1]=20;

a[2]=70;

a[3]=40;

a[4]=50;

//traversing array

for(int i=0;i<a.length;i++)//length is the property of array

System.out.println(a[i]);

}}

Output:

10 20 70 40 50

Multidimensional Array in Java:


In such case, data is stored in row and column based index (also known as matrix form).
Syntax to Declare Multidimensional Array in Java
dataType[][] arrayRefVar; (or)
dataType[][]arrayRefVar; (or)
dataTypearrayRefVar[][]; (or)
dataType[]arrayRefVar[];
Example to instantiate Multidimensional Array in Java
int[][] arr=new int[3][3];//3 row and 3 column

Example to initialize Multidimensional Array in Java:


arr[0][0]=1;
arr[0][1]=2;
arr[0][2]=3;
arr[1][0]=4;
arr[1][1]=5;
arr[1][2]=6;
arr[2][0]=7;
arr[2][1]=8;
arr[2][2]=9;
Example of Multidimensional Java Array
//Java Program to illustrate the use of multidimensional array
class Testarray3{
public static void main(String args[]){
//declaring and initializing 2D array
int arr[][]={{1,2,3},{2,4,5},{4,4,5}};
//printing 2D array
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
System.out.print(arr[i][j]+" ");
}
System.out.println();
}
}}

Output:
123
245
445

OPERATORS IN JAVA

Operator in Java is a symbol that is used to perform operations. For example: +, -, *, / etc.

There are many types of operators in Java which are given below:

o Unary Operator,
o Arithmetic Operator,
o Shift Operator,
o Relational Operator,
o Bitwise Operator,
o Logical Operator,
o Ternary Operator and
o Assignment Operator.

Java Unary Operator:


The Java unary operators require only one operand. Unary operators are used to perform
various operations i.e..incrementing/decrementing a value by one negating an
expressioninverting the value of a Boolean.
Java Unary Operator Example: ++ and --
public class OperatorExample{
public static void main(String args[])
{
int x=10;
System.out.println(x++);//10 (11)
System.out.println(++x);//12
System.out.println(x--);//12 (11)

System.out.println(--x);//10 }} Output: 10 12 12 10
Java Arithmetic Operators:
Java arithmetic operators are used to perform addition, subtraction, multiplication, and
division. They act as basic mathematical operations.
Java Arithmetic Operator Example
public class OperatorExample{
public static void main(String args[]){
int a=10;
int b=5;
System.out.println(a+b);//15
System.out.println(a-b);//5
System.out.println(a*b);//50
System.out.println(a/b);//2
System.out.println(a%b);//0
}}
Output: 15 5 50 2 0

Java Left Shift Operator:


The Java left shift operator << is used to shift all of the bits in a value to the left side of a
specified number of times.
Java Left Shift Operator Example
public class OperatorExample{
public static void main(String args[]){
System.out.println(10<<2);//10*2^2=10*4=40
System.out.println(10<<3);//10*2^3=10*8=80
System.out.println(20<<2);//20*2^2=20*4=80
System.out.println(15<<4);//15*2^4=15*16=240
}}
Output: 40 80 80 240

Java Right Shift Operator:


The Java right shift operator >> is used to move the value of the left operand to right by the
number of bits specified by the right operand.
Java Right Shift Operator Example
public OperatorExample{
public static void main(String args[]){
System.out.println(10>>2);//10/2^2=10/4=2
System.out.println(20>>2);//20/2^2=20/4=5
System.out.println(20>>3);//20/2^3=20/8=2
}}
Output: 2 5 2
Java AND Operator (Logical && and Bitwise &):
 The logical && operator doesn't check the second condition if the first condition is
false. It checks the second condition only if the first one is true.
 The bitwise & operator always checks both conditions whether first condition is true
or false.
EXAMPLE:
public class OperatorExample{
public static void main(String args[]){
int a=10;
int b=5;
int c=20;
System.out.println(a<b&&a<c);//false && true = false
System.out.println(a<b&a<c);//false & true = false
}}
Output:
false
false
Java OR Operator (Logical || and Bitwise |):
 The logical || operator doesn't check the second condition if the first condition is
true. It checks the second condition only if the first one is false.
 The bitwise | operator always checks both conditions whether first condition is
true or false.
EXAMPLE:
public class OperatorExample{
public static void main(String args[]){
int a=10;
int b=5;
int c=20;
System.out.println(a>b||a<c);//true || true = true
System.out.println(a>b|a<c);//true | true = true
//|| vs |
System.out.println(a>b||a++<c);//true || true = true
System.out.println(a);//10 because second condition is not checked
System.out.println(a>b|a++<c);//true | true = true
System.out.println(a);//11 because second condition is checked
}}
Output:
true
true
true
10
true
11

Java Ternary Operator:


Java Ternary operator is used as one line replacement for if-then-else statement and used
a lot in Java programming. It is the only conditional operator which takes three operands.
Java Ternary Operator Example
public class OperatorExample{
public static void main(String args[]){
int a=2;
int b=5;
int min=(a<b)?a:b;
System.out.println(min);
}}
Output:
2
Another Example:
public class OperatorExample{
public static void main(String args[]){
int a=10;
int b=5;
int min=(a<b)?a:b;
System.out.println(min);
}}
Output:
5

Java Assignment Operator:


Java assignment operator is one of the most common operators. It is used to assign the
value on its right to the operand on its left.
Java Assignment Operator Example
public class OperatorExample{
public static void main(String args[]){
int a=10;
int b=20;
a+=4;//a=a+4 (a=10+4)
b-=4;//b=b-4 (b=20-4)
System.out.println(a);
System.out.println(b);
}}
Output:
14
16

JAVA CONTROL STATEMENTS | CONTROL FLOW IN JAVA

Java compiler executes the code from top to bottom. The statements in the code are executed
according to the order in which they appear. However, Java provides statements that can be
used to control the flow of Java code. Such statements are called control flow statements. It is
one of the fundamental features of Java, which provides a smooth flow of program.
Java provides three types of control flow statements.

1. Decision Making statements


o if statements
o switch statement
2. Loop statements
o do while loop
o while loop
o for loop
o for-each loop
3. Jump statements
o break statement
o continue statement

Decision-Making statements:

As the name suggests, decision-making statements decide which statement to execute and
when. Decision-making statements evaluate the Boolean expression and control the program
flow depending upon the result of the condition provided. There are two types of decision-
making statements in Java, i.e., If statement and switch statement.

1) If Statement:

The Java if statement is used to test the condition. It checks boolean condition: true or false.
There are various types of if statement in Java.

 if statement
 if-else statement
 if-else-if ladder
 nested if statement

Java if Statement

The Java if statement tests the condition. It executes the if block if condition is true.

Syntax:

if(condition){

//code to be executed }

Example:
//Java Program to demonstate the use of if statement.
public class IfExample {
public static void main(String[] args) {
//defining an 'age' variable
int age=20;
//checking the age
if(age>18){
System.out.print("Age is greater than 18");
}
}
}
Output:
Age is greater than 18.
Java if-else Statement:
The Java if-else statement also tests the condition. It executes the if block if condition is true
otherwise else block is executed.
Syntax:
if(condition){
//code if condition is true
}else{
//code if condition is false
}
Example:
//A Java Program to demonstrate the use of if-else statement.
//It is a program of odd and even number.
public class IfElseExample {
public static void main(String[] args) {
//defining a variable
int number=13;
//Check if the number is divisible by 2 or not
if(number%2==0){
System.out.println("even number");
}else{
System.out.println("odd number");
}
}
}

Output:
odd number
````````````````````````````````````````````````````````````````````````````````````````````````
Leap Year Example:
A year is leap, if it is divisible by 4 and 400. But, not by 100.
public class LeapYearExample {
public static void main(String[] args) {
int year=2020;
if(((year % 4 ==0) && (year % 100 !=0)) || (year % 400==0)){
System.out.println("LEAP YEAR");
}
else{
System.out.println("COMMON YEAR");
}
}
}

Output:
LEAP YEAR

Java if-else-if ladder Statement:


The if-else-if ladder statement executes one condition from multiple statements.
Syntax:
if(condition1){
//code to be executed if condition1 is true
}else if(condition2){
//code to be executed if condition2 is true
}
else if(condition3){
//code to be executed if condition3 is true
}
...
else{
//code to be executed if all the conditions are false
}
Example:
//Java Program to demonstrate the use of If else-if ladder.
//It is a program of grading system for fail, D grade, C grade, B grade, A grade and A+.
public class IfElseIfExample {
public static void main(String[] args) {
int marks=65;
if(marks<50){
System.out.println("fail");
}
else if(marks>=50 && marks<60){
System.out.println("D grade");
}
else if(marks>=60 && marks<70){
System.out.println("C grade");
}
else if(marks>=70 && marks<80){
System.out.println("B grade");
}
else if(marks>=80 && marks<90){
System.out.println("A grade");
}else if(marks>=90 && marks<100){
System.out.println("A+ grade");
}else{
System.out.println("Invalid!");
}
}
}
Output: C grade
````````````````````````````````````````````````````````````````````````````````````````````````
Program to check POSITIVE, NEGATIVE or ZERO:
public class PositiveNegativeExample {
public static void main(String[] args) {
int number=-13;
if(number>0){
System.out.println("POSITIVE");
}else if(number<0){
System.out.println("NEGATIVE");
}else{
System.out.println("ZERO");
}
}
}
Output:
NEGATIVE

Java Nested if statement:


The nested if statement represents the if block within another if block. Here, the inner if block
condition executes only when outer if block condition is true.
Syntax:
if(condition){
//code to be executed
if(condition){
//code to be executed
}
}
Example:
//Java Program to demonstrate the use of Nested If Statement.
public class JavaNestedIfExample {
public static void main(String[] args) {
//Creating two variables for age and weight
int age=20;
int weight=80;
//applying condition on age and weight
if(age>=18){
if(weight>50){
System.out.println("You are eligible to donate blood");
}
}
}}
Output:
You are eligible to donate blood

SWITCH STATEMENT:

Syntax:
switch(expression){
case value1:
//code to be executed;
break;
case value2:
//code to be executed;
break;
......
default:
code to be executed if all cases are not matched;
}
Example:
SwitchExample.java
public class SwitchExample {
public static void main(String[] args) {
//Declaring a variable for switch expression
int number=20;
//Switch expression
switch(number){
//Case statements
case 10: System.out.println("10");
break;
case 20: System.out.println("20");
break;
case 30: System.out.println("30");
break;
//Default case statement
default:System.out.println("Not in 10, 20 or 30");
}
}
}
output:
20
LOOPING:

for Loop:

A simple for loop is the same as C/C++. We can initialize the variable, check condition and
increment/decrement value. It consists of four parts:

 Initialization: It is the initial condition which is executed once when the loop starts.
Here, we can initialize the variable, or we can use an already initialized variable. It is
an optional condition.
 Condition: It is the second condition which is executed each time to test the condition
of the loop. It continues execution until the condition is false. It must return boolean
value either true or false. It is an optional condition.
 Increment/Decrement: It increments or decrements the variable value. It is an optional
condition.
 Statement: The statement of the loop is executed each time until the second condition
is false.
Syntax:

for(initialization; condition; increment/decrement){


//statement or code to be executed }
Example:
//Java Program to demonstrate the example of for loop
public class ForExample {
public static void main(String[] args) {
//Code of Java for loop
for(int i=1;i<=10;i++){
System.out.println(i);
}
}
}
Output:

1 2 3 4 5 6 7 8 9 10

Java for-each Loop

The for-each loop is used to traverse array or collection in Java. It is easier to use than simple
for loop because we don't need to increment value and use subscript notation.

It works on the basis of elements and not the index. It returns element one by one in the
defined variable.

Syntax:
for(data_type variable : array_name){
//code to be executed
}
Example:
//Java For-each loop example which prints the elements of the array
public class ForEachExample {
public static void main(String[] args) {
//Declaring an array
int arr[]={12,23,44,56,78};
//Printing array using for-each loop
for(int i:arr){
System.out.println(i);
}
}
}
Output:
12 23 44 56 78

WHILE LOOP:
 The Java while loop is used to iterate a part of the program repeatedly until the
specified Boolean condition is true. As soon as the Boolean condition becomes false,
the loop automatically stops.
 The while loop is considered as a repeating if statement. If the number of iteration is
not fixed, it is recommended to use the while loop.
Syntax:
while (condition){
//code to be executed
Increment / decrement statement ;
}
EXAMPLE:
public class WhileExample {
public static void main(String[] args) {
int i=1;
while(i<=10){
System.out.println(i);
i++;
}
}
}
Output: 1 2 3 4 5 6 7 8 9 10

Java do-while Loop:


 The Java do-while loop is used to iterate a part of the program repeatedly, until the
specified condition is true. If the number of iteration is not fixed and you must have to
execute the loop at least once, it is recommended to use a do-while loop.
 Java do-while loop is called an exit control loop. Therefore, unlike while loop and for
loop, the do-while check the condition at the end of loop body. The Java do-while
loop is executed at least once because condition is checked after loop body.
Syntax:
do{
//code to be executed / loop body
//update statement
}while (condition);
Example:
public class DoWhileExample {
public static void main(String[] args) {
int i=1;
do{
System.out.println(i);
i++;
}while(i<=10);
}
}
Output: 1 2 3 4 5 6 7 8 9 10
Continue Statement

The continue statement is used in loop control structure when you need to jump to the next
iteration of the loop immediately. It can be used with for loop or while loop.

SYNTAX:

jump-statement;
continue;
Example:
//Java Program to demonstrate the use of continue statement
//inside the for loop.
public class ContinueExample {
public static void main(String[] args) {
//for loop
for(int i=1;i<=10;i++){
if(i==5){
//using continue statement
continue;//it will skip the rest statement
}
System.out.println(i);
}
} }
Output: 1 2 3 4 6 7 8 9 10

Break Statement

When a break statement is encountered inside a loop, the loop is immediately


terminated and the program control resumes at the next statement following the
loop.

Syntax:

jump-statement; break;

Example:
BreakExample.java
//Java Program to demonstrate the use of break statement
//inside the for loop.
public class BreakExample {
public static void main(String[] args) {
//using for loop
for(int i=1;i<=10;i++){
if(i==5){
//breaking the loop
break;
}
System.out.println(i);
}
}
}
Output:
1
2
3
4
TYPE CONVERSION AND CASTING

In Java, type casting is a method or process that converts a data type into another data type in
both ways manually and automatically. The automatic conversion is done by the compiler
and manual conversion performed by the programmer. Type Casting in Java

Type casting: Convert a value from one data type to another data type is known as type
casting.
Types of Type Casting
There are two types of type casting:
 Widening Type Casting

 Narrowing Type Casting

 Widening Type Casting

Converting a lower data type into a higher one is called widening type casting. It is also
known as implicit conversion or casting down. It is done automatically. It is safe because
there is no chance to lose data. It takes place when:
 Both data types must be compatible with each other.

 The target type must be larger than the source type.

byte -> short -> char -> int -> long -> float -> double
For example, the conversion between numeric data type to char or Boolean is not done
automatically. Also, the char and Boolean data types are not compatible with each other. Let's
see an example.
Widening Type Casting Example.java
public class WideningTypeCastingExample
{
public static void main(String[] args)
{
int x = 7;
//automatically converts the integer type into long type
long y = x;
//automatically converts the long type into float type
float z = y;
System.out.println("Before conversion, int value "+x);
System.out.println("After conversion, long value "+y);
System.out.println("After conversion, float value "+z);
}
}
Output
Before conversion, the value is: 7
After conversion, the long value is: 7
After conversion, the float value is: 7.0
In the above example, we have taken a variable x and converted it into a long type. After
that, the long type is converted into the float type.

 Narrowing Type Casting

Converting a higher data type into a lower one is called narrowing type casting. It is also
known as explicit conversion or casting up. It is done manually by the programmer. If we do
not perform casting then the compiler reports a compile-time error.

double -> float -> long -> int -> char -> short -> byte
In the following example, we have performed the narrowing type casting two times. First,
we have converted the double type into long data type after that long data type is converted
into int type.
NarrowingTypeCastingExample.java
public class NarrowingTypeCastingExample
{
public static void main(String args[])
{
double d = 166.66;
//converting double data type into long data type
long l = (long)d;
//converting long data type into int data type
int i = (int)l;
System.out.println("Before conversion: "+d);
System.out.println("After conversion into long type: "+l); //fractional part lost
System.out.println("After conversion into int type: "+i); //fractional part lost
}
}
Output
Before conversion: 166.66
After conversion into long type: 166
After conversion into int type: 166

BASIC CONCEPTS OF OOPS:

OOPs (Object-Oriented Programming System):

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

o Object
o Class
o Inheritance
o Polymorphism
o Abstraction
o Encapsulation
Object

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

An Object can be defined as an instance of a class. An object contains an address and takes
up some space in memory. Objects can communicate without knowing the details of each
other's data or code. The only necessary thing is the type of message accepted and the type of
response returned by the objects.

Example: A dog is an object because it has states like color, name, breed, etc. as well as
behaviors like wagging the tail, barking, eating, etc.

Class

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

A class can also be defined as a blueprint from which you can create an individual object.
Class doesn't consume any space.

Inheritance

When one object acquires all the properties and behaviors of a parent object, it is known as
inheritance. It provides code reusability. It is used to achieve runtime polymorphism. There
are different levels of inheritance such as.
Polymorphism

If one task is performed in different ways, it is known as polymorphism. For example: to


convince the customer differently, to draw something, for example, shape, triangle, rectangle,
etc.

In Java, we use method overloading and method overriding to achieve polymorphism.

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 are known as encapsulation.
For example, a capsule, it is wrapped with different medicines.

A java class is the example of encapsulation. Java bean is the fully encapsulated class
because all the data members are private here.

OBJECTS AND CLASSES IN JAVA:

DEFINING A CLASS

 Def: In the real world, you'll often find many individual objects. Collection of
objects is called class.
 A class is a user-defined data type with a template that serves to define its properties.
once the class type has been defined, we can create “variable s” of that type using
declarations that are similar to the basic type declarations.
 In java, these variables are termed as instances are of classes, which are the actual
objects.
 The basic form of a class definition is:

Class Syntax:-

Class classname
{
type instance-variable1 ;
type instance-variable2 ;
….. FIELDS DECLARATION
…..
type instance-variableN ;

type methodname1 (parameter-list )


{
// body of method
}
type methodname2 (parameter-list )
{
// body of method Method DECLARATION
}
.....
…..
type methodnameN (parameter-list )
{
// body of method
}
}
 Everything inside the square brackets is optional. This means that the following
would be a valid class definition:
Class Empty
{
}
 Because the body is empty, this class does not contain any properties and therefore
cannot do anything.
 we can,however compile it and even create object using it.
 C++ programeres may note that there is no semicolon after closing brace.
 FIELDS DECLARATION:-

 Data is encapsulated in a class by placing data fields inside the body of the class
definition.
 These variables are called instance variables because they are created whenever an
object of the class is instantiated.
 We can declare the instance variable exactly the same way as we declare local
variables.
 Examples:
Class box
{
double height;
double width;
}
 The class box contains double integer type instance variables. It allowed to
declare them in one line as
 double length, width;
 Remember these variables are only declared and therefore no storage space has
been created in the memory.

 Simple class

 Here is a class called Box that defines three instance variables: width, height, and
depths.
 Currently, Box does not contain any methods (but some will be added soon).
class Box
{
double width;
double height;
double depth;
}
 As stated, a class defines a new type of data.
 In this case, the new data type is called Box.
 You will use this name to declare objects of type Box.
 It is important to remember that a class declaration only creates a template; it does not
create an actual object.
 Thus, the preceding code does not cause any objects of type Box to come into
existence.
 To actually create a Box object, you will use a statement like the following:
 Box mybox = new Box(); // create a Box object called mybox
 After this statement executes, mybox will be an instance of Box.
 Thus, it will have “physical” reality.
 For the moment, don’t worry about the details of this statement.
 Again, each time you create an instance of a class, you are creating an object that
contains its own copy of each instance variable defined by the class.
 Thus, every Box object will contain its own copies of the instance variables width,
height, and depth.
 To access these variables, you will use the dot (.) operator. The dot operator links the
name of the object with the name of an instance variable.
 For example, to assign the width variable of mybox the value 100, you would use the
following statement:
 mybox.width = 100;

/* A program that uses the Box class. Call this file BoxDemo.java */
class Box
{
double width;
double height;
double depth;
}
 // This class declares an object of type Box.
class BoxDemo
{
public static void main(String args[])
{
Box b1 = new Box();
double vol;
b1.width = 10;
b1.height = 20;
b1.depth = 15;
vol = b1.width * b1.height * b1.depth;
System.out.println("Volume is " + vol);
}
}
 You should call the file that contains this program BoxDemo.java, because the main(
) method is in the class called BoxDemo, not the class called Box.
 When you compile this program, you will find that two .class files have been created,
one for Box and one for BoxDemo.
 The Java compiler automatically puts each class into its own .class file. It is not
necessary for both the Box and the BoxDemo class to actually be in the same source
file.
 You could put each class in its own file, called Box.java and BoxDemo.java,
respectively.
 To run this program, you must execute BoxDemo.class.
 When you do, you will see the following output:
 Volume is 3000.0

 CREATING OBJECTS

 As pointed out earlier, an object in java is essentially a block of memory that


contains space to store all the instance variables.
 Creating an object is also referred to as instantiating an object.
 Object in java are created using the new operator.
 The new operator creates an object of the specified class and returns a reference to
that object.
 Here is an example of creating an object of type Box.
 Box b1; // declare reference to object
 B1 = new Box(); // allocate a Box object
 The first statement declares a variables to hold the object reference and the second
one actually assigns the object reference to the variable.
 The first line declares b1 as a reference to an object of type Box.
 After this line executes, b1 contains the value null, which indicates that it does not
yet point to an actual object.
 Any attempt to use b1 at this point will result in a compile-time error.
 The next line allocates an actual object and assigns a reference to it to b1.
 After the second line executes, you can use b1 as if it were a Box object.
 But in reality, b1 simply holds the memory address of the actual Box object. The
effect of these two lines of code is depicted in Figure

 Assigning Object Reference Variables

 Object reference variables act differently than you might expect when an assignment
takes place.
 For example, what do you think the following fragment does?
 Box b1 = new Box();
 Box b2 = b1;
 You might think that b2 is being assigned a reference to a copy of the object referred
to by b1.
 That is, you might think that b1 and b2 refer to separate and distinct objects.
 However, this would be wrong. Instead, after this fragment executes, b1 and b2 will
both refer to the same object.
 The assignment of b1 to b2 did not allocate any memory or copy any part of the
original object. It simply makes b2 refer to the same object as does b1.
 Thus, any changes made to the object through b2 will affect the object to which b1 is
referring, since they are the same object.
 This situation is depicted here:
 Although b1 and b2 both refer to the same object, they are not linked in any other
way.
 For example, a subsequent assignment to b1 will simply unhook b1 from the original
object without affecting the object or affecting b2. For example:
 Box b1 = new Box();
 Box b2 = b1;
 // ...
 b1 = null;
 Here, b1 has been set to null, but b2 still points to the original object.

 METHODS DECLARATION

 A class with only data fields has no life.


 The objects created by such a class cannot respond to any messages.
 We must therefore and methods that are necessary for manipulating
 The data contained in the class.
 Methods are declared inside the body of the class but immediately after the
declaration of instance variables.
 The general form of a methods declaration is
Type methodname ( parameter-list )
{
Method-body;
}
 Method declarations have four basic parts:
 The name of the method(method name)
 The type of the value the method returns(type)
 A list of parameters(parameter-list)
 The body of the method
 The type specifies the type of value the method would return.
 This could be a simple data type such as ant as well as any class type.
 It could even be void type, if the method does not return any value.
 The method name is a valid identifier.
 The parameter list is always enclosed in parentheses.
 This list contains variable names and types of all the values we want to give to the
method as input.
 The variable in the list are separated by commas. In case where no input data are
required, the declaration must retain the empty parentheses ex:
( int m, float x, float y) // three parameter
() //empty list
 Example:
// This program includes a method inside the box class.
class Box
{ double width;
double height;
double depth;
void volume()
{
System.out.print("Volume is ");
System.out.println(width * height * depth);
}
}
class DemoBox
{
public static void main(String args[])
{
Box b1 = new Box();
// assign values to mybox1's instance variables
b1.width = 10;
b1.height = 20;
b1.depth = 15;
// display volume of first box
b1.volume();
}
}
Output:-
Volume is 3000.0
Constructors in Java:

 In Java, a constructor is a block of codes similar to the method. It is called when an


instance of the class is created. At the time of calling constructor, memory for the
object is allocated in the memory.
 It is a special type of method which is used to initialize the object.
 Every time an object is created using the new() keyword, at least one constructor is
called.
 It calls a default constructor if there is no constructor available in the class. In such
case, Java compiler provides a default constructor by default.
 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.


 Constructor name must be the same as its class name
 A Constructor must have no explicit return type
 A Java constructor cannot be abstract, static, final, and synchronized
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.

Types of Java constructors

There are two types of constructors in Java:


1. Default constructor (no-arg constructor)
2. Parameterized constructor

Java Default Constructor


A constructor is called "Default Constructor" when it doesn't have any parameter.
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 at
the time of object creation.
//Java Program to create and call a default constructor
class Bike1{
//creating a default constructor
Bike1(){System.out.println("Bike is created");}
//main method
public static void main(String args[]){
//calling a default constructor
Bike1 b=new Bike1();
}
}
Output:
Bike is created
Rule: If there is no constructor in a class, compiler automatically creates a default
constructor.
Java default constructor
Q) What is the purpose of a default constructor?
The default constructor is used to provide the default values to the object like 0, null, etc.,
depending on the type.
Example of default constructor that displays the default values
//Let us see another example of default constructor
//which displays the default values
class Student3{
int id;
String name;
//method to display the value of id and name
void display(){System.out.println(id+" "+name);}

public static void main(String args[]){


//creating objects
Student3 s1=new Student3();
Student3 s2=new Student3();
//displaying values of the object
s1.display();
s2.display();
}
}
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.
Why use the parameterized constructor?
The parameterized constructor is used to provide different values to distinct objects.
However, you can provide the same values also.

Example of parameterized constructor


In this example, we have created the constructor of Student class that have two parameters.
We can have any number of parameters in the constructor.

//Java Program to demonstrate the use of the parameterized constructor.


class Student4{
int id;
String name;
//creating a parameterized constructor
Student4(int i,String n){
id = i;
name = n;
}
//method to display the values
void display(){System.out.println(id+" "+name);}
public static void main(String args[]){
//creating objects and passing values
Student4 s1 = new Student4(111,"Karan");
Student4 s2 = new Student4(222,"Aryan");
//calling method to display the values of object
s1.display();
s2.display();
} }
Output: 111 Karan
222 Aryan
Java static keyword

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

The static can be:

1. Variable (also known as a class variable)


2. Method (also known as a class method)
3. Block
4. Nested class

Java static variable

the declaration any variable as static, it is known as a static variable.

o The static variable can be used to refer to the common property of all objects (which
is not unique for each object), for example, the company name of employees, college
name of students, etc.
o The static variable gets memory only once in the class area at the time of class
loading.

Advantages of static variable

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

Example of static variable

//Java Program to demonstrate the use of static variable

class Student{

int rollno;//instance variable

String name;

static String college ="ITS";//static variable

//constructor

Student(int r, String n){

rollno = r;
name = n;

//method to display the values

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

//Test class to show the values of objects

public class TestStaticVariable1{

public static void main(String args[]){

Student s1 = new Student(111,"Karan");

Student s2 = new Student(222,"Aryan");

//we can change the college of all objects by the single line of code

//Student.college="BBDIT";

s1.display();

s2.display();

Output:

111 Karan ITS

222 Aryan ITS

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:

 variable
 method
 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.

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.

EXAMPLE:

class Bike9{

final int speedlimit=90;//final variable

void run(){

speedlimit=400;

public static void main(String args[]){

Bike9 obj=new Bike9();

obj.run();

}//end of class

Output:Compile Time Error.

Access Modifiers (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.

There are four types of Java access modifiers:

1. Private: The access level of a private modifier is only within the class. It cannot be
accessed from outside the class.
2. Default: The access level of a default modifier is only within the package. It cannot
be accessed from outside the package. If you do not specify any access level, it will be
the default.
3. Protected: The access level of a protected modifier is within the package and outside
the package through child class. If you do not make the child class, it cannot be
accessed from outside the package.
4. Public: The access level of a public modifier is everywhere. It can be accessed from
within the class, outside the class, within the package and outside the package.

this keyword :

In Java, this is a reference variable that refers to the current object.

Here is given the 6 usage of java this keyword.

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


 this can be used to invoke current class method (implicitly)
 this() can be used to invoke current class constructor.
 this can be passed as an argument in the method call.
 this can be passed as argument in the constructor call.
 this can be used to return the current class instance from the method.

EXAMPLE:

class Student{
int rollno;
String name;
float fee;
Student(int rollno,Stringname,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.0

112 sumit 6000.0

Java Garbage Collection:

In java, garbage means unreferenced objects.

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


other words, 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 is
performed automatically. So, java provides better memory management.

Advantage of Garbage Collection:

 It makes java memory efficient because 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 to
make extra efforts.

How can an object be unreferenced?

There are many ways:

1) By nulling the reference


2) By assigning a reference to another
3) By anonymous object etc.

1) By nulling a reference:

Employee e=new Employee();

e=null;
2) By assigning a reference to another:

Employee e1=new Employee();

Employee e2=new Employee();

e1=e2;//now the first object referred by e1 is available for garbage collection

3) By anonymous object:

new Employee();

finalize() method:

The finalize() method 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(){}

Note: The Garbage collector of JVM collects only those objects that are created by new
keyword. So if you have created any object without new, you can use finalize method to
perform cleanup processing (destroying remaining objects).

gc() method

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(){}

Note: Garbage collection is performed by a daemon thread called Garbage Collector(GC).


This thread calls the finalize() method before object is garbage collected.

Example of garbage collection :

public 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();
}
}
Output: object is garbage collected

object is garbage collected


Java Inner Classes (Nested Classes):

 Java inner class or nested class is a class that is declared inside the class or interface.
 We use inner classes to logically group classes and interfaces in one place to be more
readable and maintainable.
 Additionally, it can access all the members of the outer class, including private data
members and methods.

Syntax of Inner class :

class Java_Outer_class{

//code

class Java_Inner_class{

//code

Advantage of Java inner classes:

There are three advantages of inner classes in Java. They are as follows:

 Nested classes represent a particular type of relationship that is it can access all the
members (data members and methods) of the outer class, including private.
 Nested classes are used to develop more readable and maintainable code because it
logically group classes and interfaces in one place only.
 Code Optimization: It requires less code to write.

Need of Java Inner class:

 Sometimes users need to program a class in such a way so that no other class can
access it. Therefore, it would be better if you include it within other classes.
 If all the class objects are a part of the outer object then it is easier to nest that class
inside the outer class. That way all the outer class can access all the objects of the
inner class.

Difference between nested class and inner class in Java

An inner class is a part of a nested class. Non-static nested classes are known as inner classes.

Types of Nested classes:

There are two types of nested classes non-static and static nested classes. The non-static
nested classes are also known as inner classes.
 Non-static nested class (inner class)

1) Member inner class


2) Anonymous inner class
3) Local inner class

 Static nested class

Java Member Inner class

A non-static class that is created inside a class but outside a method is called member inner
class. It is also known as a regular inner class. It can be declared with access modifiers like
public, default, private, and protected.

Syntax:
class Outer{
//code
class Inner{
//code
}
}
Java Member Inner Class Example
In this example, we are creating a msg() method in the member inner class that is accessing
the private data member of the outer class.

TestMemberOuter1.java
class TestMemberOuter1{
private int data=30;
class Inner{
void msg(){System.out.println("data is "+data);}
}
public static void main(String args[]){
TestMemberOuter1 obj=new TestMemberOuter1();
TestMemberOuter1.Inner in=obj.new Inner();
in.msg();
}
}
Output:
data is 30
Java Anonymous inner class
Java anonymous inner class is an inner class without a name and for which only a single
object is created. An anonymous inner class can be useful when making an instance of an
object with certain "extras" such as overloading methods of a class or interface, without
having to actually subclass a class.

In simple words, a class that has no name is known as an anonymous inner class in Java. It
should be used if you have to override a method of class or interface. Java Anonymous inner
class can be created in two ways:

Class (may be abstract or concrete).


Interface
Java anonymous inner class example using class
TestAnonymousInner.java

abstract class Person{


abstract void eat();
}
class TestAnonymousInner{
public static void main(String args[]){
Person p=new Person(){
void eat(){System.out.println("nice fruits");}
};
p.eat();
}
}

Output:
nice fruits

Java Local inner class


A class i.e., created inside a method, is called local inner class in java. Local Inner Classes
are the inner classes that are defined inside a block. Generally, this block is a method body.
Sometimes this block can be a for loop, or an if clause. Local Inner classes are not a member
of any enclosing classes. They belong to the block they are defined within, due to which local
inner classes cannot have any access modifiers associated with them. However, they can be
marked as final or abstract. These classes have access to the fields of the class enclosing it.
If you want to invoke the methods of the local inner class, you must instantiate this class
inside the method.

Java local inner class example


LocalInner1.java

public class localInner1{


private int data=30;//instance variable
void display(){
class Local{
void msg(){System.out.println(data);}
}
Local l=new Local();
l.msg();
}
public static void main(String args[]){
localInner1 obj=new localInner1();
obj.display();
}
}
Output:
30

JAVA STRING:

In Java, string is basically an object that represents sequence of char values. An array of
characters works same as Java string. For example:

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

is same as:

String s="javatpoint";

Java String class provides a lot of methods to perform operations on strings such as
compare(), concat(), equals(), split(), length(), replace(), compareTo(), intern(), substring()
etc.

The java.lang.String class


implements Serializable, Comparable and CharSequence interfaces.

Char Sequence Interface

The Char Sequence interface is used to represent the sequence of characters. String, String
Buffer and String Builder classes implement it. It means, we can create strings in Java by
using these three classes.

The Java String is immutable which means it cannot be changed. Whenever we change any
string, a new instance is created. For mutable strings, you can use String Buffer and String
Builder classes.

What is String in Java?

Generally, String is a sequence of characters. But in Java, string is an object that represents a
sequence of characters. The java.lang.String class is used to create a string object.

How to create a string object?

There are two ways to create String object:

1. By string literal
2. By new keyword
1) String Literal

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

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 the 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";//It doesn't create a new instance

In the above example, only one object will be created. Firstly, JVM will not find any string
object with the value "Welcome" in string constant pool that is why it will create a new
object. After that it will find the string with the value "Welcome" in the pool, it will not
create a new object but will return the reference to the same instance.

2) By new keyword
String s=new String("Welcome");//creates two objects and one reference variable

In such case, JVM will create a new string object in normal (non-pool) heap memory, and the
literal "Welcome" will be placed in the string constant pool. The variable s will refer to the
object in a heap (non-pool).

Java String Example

StringExample.java

1. public class StringExample{


2. public static void main(String args[]){
3. String s1="java";//creating string by Java string literal
4. char ch[]={'s','t','r','i','n','g','s'};
5. String s2=new String(ch);//converting char array to string
6. String s3=new String("example");//creating Java string by new keyword
7. System.out.println(s1);
8. System.out.println(s2);
9. System.out.println(s3);
10. }}

Output:

java
strings
example

The above code, converts a char array into a String object. And displays the String
objects s1, s2, and s3 on console using println() method.

Java String class methods

The java.lang.String class provides many useful methods to perform operations on sequence
of char values.
Example
String txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
System.out.println("The length of the txt string is: " + txt.length());

String txt = "Hello World";


System.out.println(txt.toUpperCase()); // Outputs "HELLO WORLD"
System.out.println(txt.toLowerCase()); // Outputs "hello world"

String txt = "Please locate where 'locate' occurs!";


System.out.println(txt.indexOf("locate")); // Outputs 7

String firstName = "John";


String lastName = "Doe";
System.out.println(firstName + " " + lastName);

You might also like