Java Material
Java Material
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.
Java Example
Let's have a quick look at Java programming example. A detailed description of Hello Java example is available in
next page.
Simple.java
class Simple{
public static void main(String args[]){
System.out.println("Hello Java");
}
}
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
403 – Java Programming Language
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, JPA, etc.
2
403 – Java Programming Language
4) JavaFX
It is used to develop rich internet applications. It uses a lightweight user interface API.
A list of the most important features of the Java language is given below.
1. Simple
2. Object-Oriented
3. Portable
4. Platform independent
5. Secured
6. Robust
7. Architecture neutral
8. Interpreted
9. High Performance
10. Multithreaded
11. Distributed
12. Dynamic
3
403 – Java Programming Language
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++ (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.
Object-oriented
Java is an object-oriented programming language. Everything in Java is an object. Object-oriented means we
organize our software as a combination of different types of objects that incorporate both data and behavior.
Object-oriented programming (OOPs) is a methodology that simplifies software development and maintenance
by providing some rules.
1. Object
2. Class
3. Inheritance
4. Polymorphism
5. Abstraction
6. Encapsulation
Platform Independent
4
403 – Java Programming Language
Java is platform independent because it is different from other languages like C, C++, etc. which are compiled
into platform specific machines while Java is a write once, run anywhere language. A platform is the hardware or
software environment in which a program runs.
There are two types of platforms software-based and hardware-based. Java provides a software-based platform.
The Java platform differs from most other platforms in the sense that it is a software-based platform that runs
on top of other hardware-based platforms. It has two components:
1. Runtime Environment
2. API(Application Programming Interface)
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 bytecode. This bytecode is a platform-independent code
because it can be run on multiple platforms, i.e., Write Once and Run Anywhere (WORA).
Secured
Java is 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.
5
403 – Java Programming Language
Java language provides these securities by default. Some security can also be provided by an application
developer explicitly through SSL, JAAS, Cryptography, etc.
Robust
The English mining of Robust is strong. Java is robust because:
Architecture-neutral
Java is architecture neutral because there are no implementation dependent features, for example, the size of
primitive types is fixed.
In C programming, int data type occupies 2 bytes of memory for 32-bit architecture and 4 bytes of memory for
64-bit architecture. However, it occupies 4 bytes of memory for both 32 and 64-bit architectures in Java.
Portable
Java is portable because it facilitates you to carry the Java bytecode to any platform. It doesn't require any
implementation.
High-performance
Java is faster than other traditional interpreted programming languages because Java bytecode is "close" to
native code. It is still a little bit slower than a compiled language (e.g., C++). Java is an interpreted language that
is why it is slower than compiled languages, e.g., C, C++, etc.
Distributed
Java is distributed because it facilitates users to create distributed applications in Java. RMI and EJB are used for
creating distributed applications. This feature of Java makes us able to access files by calling the methods from
any machine on the internet.
6
403 – Java Programming Language
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.
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).
A list of top differences between C++ and Java are given below:
Mainly used for C++ is mainly used for system Java is mainly used for application programming. It
programming. is widely used in Windows-based, web-based,
enterprise, and mobile applications.
Design Goal C++ was designed for systems and Java was designed and created as an interpreter
applications programming. It was an for printing systems but later extended as a
extension of the C programming support network computing. It was designed to be
language. easy to use and accessible to a broader audience.
Goto C++ supports the goto statement. Java doesn't support the goto statement.
Multiple C++ supports multiple inheritance. Java doesn't support multiple inheritance through
inheritance class. It can be achieved by using interfaces in java.
7
403 – Java Programming Language
Operator C++ supports operator overloading. Java doesn't support operator overloading.
Overloading
Pointers C++ supports pointers. You can write Java supports pointer internally. However, you
a pointer program in C++. can't write the pointer program in java. It means
java has restricted pointer support in java.
Compiler and C++ uses compiler only. C++ is Java uses both compiler and interpreter. Java
Interpreter compiled and run using the compiler source code is converted into bytecode at
which converts source code into compilation time. The interpreter executes this
machine code so, C++ is platform bytecode at runtime and produces output. Java is
dependent. interpreted that is why it is platform-independent.
Call by Value and C++ supports both call by value and Java supports call by value only. There is no call by
Call by reference call by reference. reference in java.
Structure and C++ supports structures and unions. Java doesn't support structures and unions.
Union
Thread Support C++ doesn't have built-in support for Java has built-in thread support.
threads. It relies on third-party
libraries for thread support.
Documentation C++ doesn't support documentation Java supports documentation comment (/** ... */)
comment comments. to create documentation for java source code.
Virtual Keyword C++ supports virtual keyword so that Java has no virtual keyword. We can override all
we can decide whether or not to non-static methods by default. In other words,
override a function. non-static methods are virtual by default.
unsigned right C++ doesn't support >>> operator. Java supports unsigned right shift >>> operator
shift >>> that fills zero at the top for the negative numbers.
For positive numbers, it works same like >>
operator.
Inheritance Tree C++ always creates a new inheritance Java always uses a single inheritance tree because
tree. all classes are the child of the Object class in Java.
The Object class is the root of the inheritance tree
in java.
8
403 – Java Programming Language
Note
#include <iostream>
using namespace std;
int main()
{
cout << "Hello C++ Programming";
return 0;
}
Output:
class Simple{
public static void main(String args[]){
System.out.println("Hello Java");
}
}
Output:
Hello Java
9
403 – Java Programming Language
In this section, we will learn how to write the simple program of Java. We can write a simple hello Java program
easily after installing the JDK.
To create a simple Java program, you need to create a class that contains the main method. Let's understand the
requirement first.
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
class Simple{
public static void main(String args[]){
System.out.println("Hello Java");
}
}
Output:
Hello Java
10
403 – Java Programming Language
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:
11
403 – Java Programming Language
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:
To compile and run the above program, go to your current directory first; my current directory is c:\new. Write
here:
12
403 – Java Programming Language
1) By changing the sequence of the modifiers, method prototype is not changed in Java.
2) The subscript notation in the Java array can be used after type, before the variable or after the variable.
3) You can provide var-args support to the main() method by passing 3 ellipses (dots)
Let's see the simple code of using var-args in the main() method. We will learn about var-args later in the Java
New Features chapter.
1. class A{
2. static public void main(String... args){
3. System.out.println("hello java4");
4. }
5. };
13
403 – Java Programming Language
14
403 – Java Programming Language
Identifiers in Java
Identifiers in Java are symbolic names used for identification. They can be a class name, variable name, method
name, package name, constant name, and more. However,
In Java,There are some reserved words that can not be used as an identifier.
For every identifier there are some conventions that should be used before declaring them. Let's understand it
with a simple Java program:
15
403 – Java Programming Language
o A valid identifier must have characters [A-Z] or [a-z] or numbers [0-9], and underscore(_) or a dollar sign ($). for
example, @javatpoint is not a valid identifier because it contains a special character which is @.
o There should not be any space in an identifier. For example, java tpoint is an invalid identifier.
o An identifier should not contain a number at the starting. For example, 123javatpoint is an invalid identifier.
o An identifier should be of length 4-15 letters only. However, there is no limit on its length. But, it is good to follow
the standard conventions.
o We can't use the Java reserved keywords as an identifier such as int, float, double, char, etc. For example, int
double is an invalid identifier in Java.
o An identifier should not be any query language keywords such as SELECT, FROM, COUNT, DELETE, etc.
Literals in Java
In Java
, literal is a notation that represents a fixed value in the source code. In lexical analysis, literals of a given type are generally
known as tokens
Literals
In Java, literals are the constant values that appear directly in the program. It can be assigned directly to a
variable. Java has various types of literals. The following figure represents a literal.
16
403 – Java Programming Language
1. Integer Literal
2. Character Literal
3. Boolean Literal
4. String Literal
Integer Literals
Integer literals are sequences of digits. There are three types of integer literals:
o Decimal Integer: These are the set of numbers that consist of digits from 0 to 9. It may have a positive (+) or
negative (-) Note that between numbers commas and non-digit characters are not permitted. For example, 5678,
+657, -89, etc.
o Octal Integer: It is a combination of number have digits from 0 to 7 with a leading 0. For example, 045, 026,
17
403 – Java Programming Language
Real Literals
The numbers that contain fractional parts are known as real literals. We can also represent real literals in
exponent form. For example, 879.90, 99E-3, etc.
Backslash Literals
Java supports some special backslash character literals known as backslash literals. They are used in formatted
output. For example:
Character Literals
A character literal is expressed as a character or an escape sequence, enclosed in a single quote ('') mark. It is
always a type of char. For example, 'a', '%', '\u000d', etc.
String Literals
String literal is a sequence of characters that is enclosed between double quotes ("") marks. It may be alphabet,
numbers, special characters, blank space, etc. For example, "Jack", "12345", "\n", etc.
o Floating-point literals for float type end with F or f. For example, 6f, 8.354F, etc. It is a 32-bit float literal.
o Floating-point literals for double type end with D or d. It is optional to write D or d. For example, 6d, 8.354D, etc. It
is a 64-bit double literal.
o It can also be represented in the form of the exponent.
18
403 – Java Programming Language
Floating:
Decimal:
Invalid Literals
There is some invalid declaration of literals.
float g = 6_.674f;
float g = 6._674F;
long phoneNumber = 99_00_99_00_99_L;
int x = 77_;
int y = 0_x76;
int z = 0X_12;
int z = 0X12_;
19
403 – Java Programming Language
LiteralsExample.java
{
public static void main(String args[])
{
int count = 987;
float floatVal = 4534.99f;
double cost = 19765.567;
int hexaVal = 0x7e4;
int binary = 0b11010;
char alpha = 'p';
String str = "Java";
boolean boolVal = true;
int octalVal = 067;
String stuName = null;
char ch1 = '\u0021';
char ch2 = 1456;
System.out.println(count);
System.out.println(floatVal);
System.out.println(cost);
System.out.println(hexaVal);
20
403 – Java Programming Language
System.out.println(binary);
System.out.println(alpha);
System.out.println(str);
System.out.println(boolVal);
System.out.println(octalVal);
System.out.println(stuName);
System.out.println(ch1);
System.out.println("\t" +"backslash literal");
System.out.println(ch2);
}
}
Output:
987
4534.99
19765.567
2020
26
p
Java
true
55
null
!
backslash literal
?
Operators in Java
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.
additive +-
equality == !=
bitwise exclusive OR ^
bitwise inclusive OR |
logical OR ||
Ternary ternary ?:
o negating an expression
o inverting the value of a boolean
22
403 – Java Programming Language
Output:
10
12
12
10
}}
Output:
22
21
23
403 – Java Programming Language
}}
Output:
-11
9
false
true
Java Arithmetic Operators
Java arithmetic operators are used to perform addition, subtraction, multiplication, and division. They act as
basic mathematical operations.
Output:
15
5
50
2
0
Java Arithmetic Operator Example: Expression
public class OperatorExample{
public static void main(String args[]){
System.out.println(10*10/5+3-1*4/2);
}}
Output:
21
24
403 – Java Programming Language
Output:
2
5
2
25
403 – Java Programming Language
System.out.println(-20>>2);
System.out.println(-20>>>2);
}}
Output:
5
5
-5
1073741819
Java AND Operator Example: 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.
Output:
false
false
Java AND Operator Example: Logical && vs Bitwise &
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);//10 because second condition is not checked
System.out.println(a<b&a++<c);//false && true = false
System.out.println(a);//11 because second condition is checked
}}
26
403 – Java Programming Language
Output:
false
10
false
11
Java OR Operator Example: 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.
Output:
true
true
true
10
true
11
27
403 – Java Programming Language
int a=2;
int b=5;
int min=(a<b)?a:b;
System.out.println(min);
}}
Output:
Another Example:
Output:
28
403 – Java Programming Language
16
Java Assignment Operator Example
Output:
13
9
18
9
29
403 – Java Programming Language
short b=10;
a=(short)(a+b);//20 which is int now converted to short
System.out.println(a);
}}
Output:
20
Java Variables
A variable is a container which holds the value while the Java program
Variable is a name of memory location. There are three types of variables in java: local, instance and static.
Variable
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.
Types of Variables
There are three types of variables in Java
o local variable
o instance variable
o static variable
1) Local Variable
A variable declared inside the body of the method is called local variable. You can use this variable only within
that method and the other methods in the class aren't even aware that the variable exists.
30
403 – Java Programming Language
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.
Output:
20
31
403 – Java Programming Language
Java Keywords
Java keywords are also known as reserved words. Keywords are particular words that act as a key to a code.
These are predefined words by Java so they cannot be used as a variable or object name or class name.
1. abstract: Java abstract keyword is used to declare an abstract class. An abstract class can provide the
implementation of the interface. It can have abstract and non-abstract methods.
2. boolean:Java boolean keyword is used to declare a variable as a boolean type. It can hold True and False values
only.
3. break: Java break keyword is used to break the loop or switch statement. It breaks the current flow of the program
at specified conditions.
4. byte: Java byte keyword is used to declare a variable that can hold 8-bit data values.
5. case: Java case keyword is used with the switch statements to mark blocks of text.
6. catch: Java catch keyword is used to catch the exceptions generated by try statements. It must be used after the
try block only.
7. char: Java char keyword is used to declare a variable that can hold unsigned 16-bit Unicode characters
8. class: Java class keyword is used to declare a class.
9. continue: Java continue keyword is used to continue the loop. It continues the current flow of the program and
skips the remaining code at the specified condition.
10. default: Java default keyword is used to specify the default block of code in a switch statement.
11. do: Java do keyword is used in the control statement to declare a loop. It can iterate a part of the program several
times.
12. double: Java double keyword is used to declare a variable that can hold 64-bit floating-point number.
13. else: Java else keyword is used to indicate the alternative branches in an if statement.
14. enum: Java enum keyword is used to define a fixed set of constants. Enum constructors are always private or
default.
15. extends: Java extends keyword is used to indicate that a class is derived from another class or interface.
16. final: Java final keyword is used to indicate that a variable holds a constant value. It is used with a variable. It is
used to restrict the user from updating the value of the variable.
17. finally: Java finally keyword indicates a block of code in a try-catch structure. This block is always executed whether
an exception is handled or not.
18. float: Java float keyword is used to declare a variable that can hold a 32-bit floating-point number.
32
403 – Java Programming Language
19. for: Java for keyword is used to start a for loop. It is used to execute a set of instructions/functions repeatedly
when some condition becomes true. If the number of iteration is fixed, it is recommended to use for loop.
20. if: Java if keyword tests the condition. It executes the if block if the condition is true.
21. implements: Java implements keyword is used to implement an interface.
22. import: Java import keyword makes classes and interfaces available and accessible to the current source code.
23. instanceof: Java instanceof keyword is used to test whether the object is an instance of the specified class or
implements an interface.
24. int: Java int keyword is used to declare a variable that can hold a 32-bit signed integer.
25. interface: Java interface keyword is used to declare an interface. It can have only abstract methods.
26. long: Java long keyword is used to declare a variable that can hold a 64-bit integer.
27. native: Java native keyword is used to specify that a method is implemented in native code using JNI (Java Native
Interface).
28. new: Java new keyword is used to create new objects.
29. null: Java null keyword is used to indicate that a reference does not refer to anything. It removes the garbage
value.
30. package: Java package keyword is used to declare a Java package that includes the classes.
31. private: Java private keyword is an access modifier. It is used to indicate that a method or variable may be accessed
only in the class in which it is declared.
32. protected: Java protected keyword is an access modifier. It can be accessible within the package and outside the
package but through inheritance only. It can't be applied with the class.
33. public: Java public keyword is an access modifier. It is used to indicate that an item is accessible anywhere. It has
the widest scope among all other modifiers.
34. return: Java return keyword is used to return from a method when its execution is complete.
35. short: Java short keyword is used to declare a variable that can hold a 16-bit integer.
36. static: Java static keyword is used to indicate that a variable or method is a class method. The static keyword in
Java is mainly used for memory management.
37. strictfp: Java strictfp is used to restrict the floating-point calculations to ensure portability.
38. super: Java super keyword is a reference variable that is used to refer to parent class objects. It can be used to
invoke the immediate parent class method.
39. switch: The Java switch keyword contains a switch statement that executes code based on test value. The switch
statement tests the equality of a variable against multiple values.
40. synchronized: Java synchronized keyword is used to specify the critical sections or methods in multithreaded code.
41. this: Java this keyword can be used to refer the current object in a method or constructor.
33
403 – Java Programming Language
42. throw: The Java throw keyword is used to explicitly throw an exception. The throw keyword is mainly used to
throw custom exceptions. It is followed by an instance.
43. throws: The Java throws keyword is used to declare an exception. Checked exceptions can be propagated with
throws.
44. transient: Java transient keyword is used in serialization. If you define any data member as transient, it will not be
serialized.
45. try: Java try keyword is used to start a block of code that will be tested for exceptions. The try block must be
followed by either catch or finally block.
46. void: Java void keyword is used to specify that a method does not have a return value.
47. volatile: Java volatile keyword is used to indicate that a variable may change asynchronously.
48. while: Java while keyword is used to start a while loop. This loop iterates a part of the program several times. If the
number of iteration is not fixed, it is recommended to use the while loop.
1. Primitive data types: The primitive data types include boolean, char, byte, short, int, long, float and double.
2. Non-primitive data types: The non-primitive data types include Classes, Interfaces, and Arrays.
There are 8 types of primitive data types:obile Data Breach Affects Over 40 Million People
o boolean data type
o byte data type
o char data type
o short data type
o int data type
o long data type
o float data type
o double data type
34
403 – Java Programming Language
byte 0 1 byte
short 0 2 byte
int 0 4 byte
long 0L 8 byte
35
403 – Java Programming Language
The Boolean data type specifies one bit of information, but its "size" can't be defined precisely.
Example:
The byte data type is used to save memory in large arrays where the memory savings is most required. It saves
space because a byte is 4 times smaller than an integer. It can also be used in place of "int" data type.
Example:
The short data type can also be used to save memory just like byte data type. A short data type is 2 times smaller
than an integer.
Example:
The int data type is generally used as a default data type for integral values unless if there is no problem about
memory.
Example:
36
403 – Java Programming Language
The long data type is a 64-bit two's complement integer. Its value-range lies between -
9,223,372,036,854,775,808(-2^63) to 9,223,372,036,854,775,807(2^63 -1)(inclusive). Its minimum value is -
9,223,372,036,854,775,808and maximum value is 9,223,372,036,854,775,807. Its default value is 0. The long
data type is used when you need a range of values more than those provided by int.
Example:
Example:
float f1 = 234.5f
Example:
double d1 = 12.3
Example:
37
403 – Java Programming Language
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.
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:
In Java, the "if" statement is used to evaluate a condition. The control of the program is diverted depending upon
the specific condition. The condition of the If statement gives a Boolean value, either true or false. In Java, there
are four types of if-statements given below.
1. Simple if statement
2. if-else statement
3. if-else-if ladder
4. Nested if-statement
38
403 – Java Programming Language
1) Simple if statement:
It is the most basic statement among all control flow statements in Java. It evaluates a Boolean expression and
enables the program to enter a block of code if the expression evaluates to true.
Syntax:
if(condition) {
Consider the following example in which we have used the if statement in the java code.
Student.java
Student.java
Output:
x + y is greater than 20
2) if-else statement
is an extension to the if-statement, which uses another block of code, i.e., else block. The else block is executed if the
condition of the if-block is evaluated as false.
Syntax:
if(condition) {
statement 1; //executes when condition is true
39
403 – Java Programming Language
}
else{
statement 2; //executes when condition is false
}
Consider the following example.
Student.java
Output:
x + y is greater than 20
3) if-else-if ladder:
The if-else-if statement contains the if-statement followed by multiple else-if statements. In other words, we can
say that it is the chain of if-else statements that create a decision tree where the program may enter in the block
of code where the condition is true. We can also define an else statement at the end of the chain.
Syntax:
if(condition 1) {
statement 1; //executes when condition 1 is true
}
else if(condition 2) {
statement 2; //executes when condition 2 is true
}
else {
statement 2; //executes when all the conditions are false
}
40
403 – Java Programming Language
Student.java
Output:
Delhi
4. Nested if-statement
In nested if-statements, the if statement can contain a if or if-else statement inside another if or else-if
statement.
Syntax:
if(condition 1) {
statement 1; //executes when condition 1 is true
if(condition 2) {
statement 2; //executes when condition 2 is true
}
else{
statement 2; //executes when condition 2 is false
}
}
41
403 – Java Programming Language
Student.java
if(address.endsWith("India")) {
if(address.contains("Meerut")) {
System.out.println("Your city is Meerut");
}else if(address.contains("Noida")) {
System.out.println("Your city is Noida");
}else {
System.out.println(address.split(",")[0]);
}
}else {
System.out.println("You are not living in India");
}
}
}
Output:
Delhi
Switch Statement:
In Java, Switch statements
are similar to if-else-if statements. The switch statement contains multiple blocks of code called cases and a single case is
executed based on the variable which is being switched. The switch statement is easier to use instead of if-else-if
statements. It also enhances the readability of the program.
o The case variables can be int, short, byte, char, or enumeration. String type is also supported since version 7 of Java
o Cases cannot be duplicate
o Default statement is executed when any of the case doesn't match the value of expression. It is optional.
o Break statement terminates the switch block when the condition is satisfied.
It is optional, if not used, next case is executed.
o While using switch statements, we must notice that the case expression will be of the same type as the variable.
However, it will also be a constant value.
o
42
403 – Java Programming Language
syntax:
switch (expression){
case value1:
statement1;
break;
.
.
.
case valueN:
statementN;
break;
default:
default statement;
}
Consider the following example to understand the flow of the switch statement.
Student.java
Output:
43
403 – Java Programming Language
While using switch statements, we must notice that the case expression will be of the same type as the variable.
However, it will also be a constant value. The switch permits only int, string, and Enum type variables to be used.
Loop Statements
In programming, sometimes we need to execute the block of code repeatedly while some condition evaluates to
true. However, loop statements are used to execute the set of instructions in a repeated order. The execution of
the set of instructions depends upon a particular condition.
In Java, we have three types of loops that execute similarly. However, there are differences in their syntax and
condition checking time.
1. for loop
2. while loop
3. do-while loop
. It enables us to initialize the loop variable, check the condition, and increment/decrement in a single line of code. We use
the for loop only when we exactly know the number of times, we want to execute the block of code.
Syntax:
44
403 – Java Programming Language
Consider the following example to understand the proper functioning of the for loop in java.
Calculation.java
Output:
Syntax:
Consider the following example to understand the functioning of the for-each loop in Java.
Calculation.java
Output:
45
403 – Java Programming Language
is also used to iterate over the number of statements multiple times. However, if we don't know the number of iterations
in advance, it is recommended to use a while loop. Unlike for loop, the initialization and increment/decrement doesn't take
place inside the loop statement in while loop.
It is also known as the entry-controlled loop since the condition is checked at the start of the loop. If the
condition is true, then the loop body will be executed; otherwise, the statements after the loop will be executed.
Syntax:
while(condition){
//looping statements
}
The flow chart for the while loop is given in the following image.
Calculation .java
46
403 – Java Programming Language
System.out.println(i);
i = i + 2;
}
}
}
Output:
checks the condition at the end of the loop after executing the loop statements. When the number of iteration is not
known and we have to execute the loop at least once, we can use do-while loop.It is also known as the exit-controlled loop
since the condition is not checked in advance.
Syntax:
do
{
//statements
} while (condition);
The flow chart of the do-while loop is given in the following image.
Consider the following example to understand the functioning of the do-while loop in Java.
47
403 – Java Programming Language
Calculation.java
Output:
Jump Statements
Jump statements are used to transfer the control of the program to the specific statements. In other words,
jump statements transfer the execution control to the other part of the program. There are two types of jump
statements in Java, i.e., break and continue.
is used to break the current flow of the program and transfer the control to the next statement outside a loop or switch
statement. However, it breaks only the inner loop in the case of the nested loop.
The break statement cannot be used independently in the Java program, i.e., it can only be written inside the
loop or switch statement.
Consider the following example in which we have used the break statement with the for loop.
48
403 – Java Programming Language
BreakExample.java
public class BreakExample {
public static void main(String[] args) {
for(int i = 0; i<= 10; i++) {
System.out.println(i);
if(i==6) {
break;
}
}
}
}
Output:
0
1
2
3
4
5
6
Calculation.java
49
403 – Java Programming Language
Output:
0
1
2
3
4
5
doesn't break the loop, whereas, it skips the specific part of the loop and jumps to the next iteration of the loop
immediately.
Consider the following example to understand the functioning of the continue statement in Java.
Output:
0
1
2
3
5
1
2
3
5
2
3
5
50
403 – Java Programming Language
Type casting
Convert a value from one data type to another data type is known as type casting.
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.
51
403 – Java Programming Language
WideningTypeCastingExample.java
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.
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.
52
403 – Java Programming Language
NarrowingTypeCastingExample.java
Output
53
403 – Java Programming Language
For Example, Pen is an object. Its name is Reynolds; color is white, known as its state. It is
used to write, so writing is its behavior.
An object is an instance of a class. A class is a template or blueprint from which objects are
created. So, an object is the instance(result) of a class.
Object Definitions:
o Fields
o Methods
o Constructors
o Blocks
o Nested class and interface
1
403 – Java Programming Language
A variable which is created inside the class but outside the method is known as an instance
variable. Instance variable doesn't get memory at compile time. It gets memory at runtime
when an object or instance is created. That is why it is known as an instance variable.
Method in Java
In Java, a method is like a function which is used to expose the behavior of an object.
Advantage of Method
o Code Reusability
o Code Optimization
The new keyword is used to allocate memory at runtime. All objects get memory in Heap
memory area.
In this example, we have created a Student class which has two data members id and name. We
are creating the object of the Student class by new keyword and printing the object's value.
File: Student.java
2
403 – Java Programming Language
Output:
0
null
Object and Class Example: main outside the class
In real time development, we create classes and use it from another class. It is a better approach
than previous one. Let's see a simple example, where we are having main() method in another
class.
We can have multiple classes in different Java files or single Java file. If you define multiple
classes in a single Java source file, it is a good idea to save the file name with the class name
which has main() method.
File: TestStudent1.java
Output:
0
null
3
403 – Java Programming Language
1. By reference variable
2. By method
3. By constructor
Initializing an object means storing data into the object. Let's see a simple example where we
are going to initialize the object through a reference variable.
File: TestStudent2.java
class Student{
int id;
String name;
}
class TestStudent2{
public static void main(String args[]){
Student s1=new Student();
s1.id=101;
s1.name="Sonoo";
System.out.println(s1.id+" "+s1.name);//printing members with a white space
}
}
Output:
101 Sonoo
We can also create multiple objects and store information in it through reference variable.
File: TestStudent3.java
class Student{
int id;
String name;
}
class TestStudent3{
public static void main(String args[]){
4
403 – Java Programming Language
Output:
101 Sonoo
102 Amit
2) Object and Class Example: Initialization through method
In this example, we are creating the two objects of Student class and initializing the value to
these objects by invoking the insertRecord method. Here, we are displaying the state (data) of
the objects by invoking the displayInformation() method.
File: TestStudent4.java
class Student{
int rollno;
String name;
void insertRecord(int r, String n){
rollno=r;
name=n;
}
void displayInformation()
{
System.out.println(rollno+" "+name);
}
}
class TestStudent4{
public static void main(String args[]){
Student s1=new Student();
5
403 – Java Programming Language
File: TestEmployee.java
class Employee{
int id;
String name;
float salary;
void insert(int i, String n, float s) {
id=i;
name=n;
salary=s;
}
void display(){System.out.println(id+" "+name+" "+salary);}
}
public class TestEmployee {
public static void main(String[] args) {
Employee e1=new Employee();
Employee e2=new Employee();
Employee e3=new Employee();
e1.insert(101,"ajeet",45000);
e2.insert(102,"irfan",25000);
e3.insert(103,"nakul",55000);
6
403 – Java Programming Language
Output:
File: TestAccount.java
7
403 – Java Programming Language
Output:
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.
8
403 – Java Programming Language
There are many non-access modifiers, such as static, abstract, synchronized, native, volatile,
transient, etc. Here, we are going to learn the access modifiers only.
Private Y N N N
Default Y Y N N
Protected Y Y Y N
Public Y Y Y Y
1) Private
In this example, we have created two classes A and Simple. A class contains private data
member and private method. We are accessing these private members from outside the class,
so there is a compile-time error.
class A{
private int data=40;
private void msg(){System.out.println("Hello java");}
}
9
403 – Java Programming Language
If you make any class constructor private, you cannot create the instance of that class from
outside the class. For example:
class A{
private A(){}//private constructor
void msg(){System.out.println("Hello java");}
}
public class Simple{
public static void main(String args[]){
A obj=new A();//Compile Time Error
}
}
Note: A class cannot be private or protected except nested class.
2) Default
If you don't use any modifier, it is treated as default by default. The default modifier is
accessible only within package. It cannot be accessed from outside the package. It provides
more accessibility than private. But, it is more restrictive than protected, and public.
In this example, we have created two packages pack and mypack. We are accessing the A class
from outside its package, since A class is not public, so it cannot be accessed from outside the
package.
//save by A.java
package pack;
class A{
void msg(){System.out.println("Hello");}
}
10
403 – Java Programming Language
In the above example, the scope of class A and its method msg() is default so it cannot be
accessed from outside the package.
3) Protected
The protected access modifier is accessible within package and outside the package but
through inheritance only.
The protected access modifier can be applied on the data member, method and constructor. It
can't be applied on the class.
In this example, we have created the two packages pack and mypack. The A class of pack
package is public, so can be accessed from outside the package. But msg method of this
package is declared as protected, so it can be accessed from outside the class only through
inheritance.
//save by A.java
package pack;
public class A{
protected void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.*;
class B extends A{
public static void main(String args[]){
11
403 – Java Programming Language
4) Public
The public access modifier is accessible everywhere. It has the widest scope among all other
modifiers.
//save by A.java
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
Output:Hello
If you are overriding any method, overridden method (i.e. declared in subclass) must not be
more restrictive.
class A{
protected void msg(){System.out.println("Hello java");}
}
12
403 – Java Programming Language
The default modifier is more restrictive than protected. That is why, there is a compile-time
error.
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.
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.
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.
13
403 – Java Programming Language
In this example, we are creating the no-arg constructor in the Bike class. It will be invoked at the
time of object creation.
Output:
Bike is created
Rule: If there is no constructor in a class, compiler automatically creates a default constructor.
14
403 – Java Programming Language
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.
The parameterized constructor is used to provide different values to distinct objects. However,
you can provide the same values also.
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.
15
403 – Java Programming Language
Output:
111 Karan
222 Aryan
Constructor overloading in Java is a technique of having more than one constructor with
different parameter lists. They are arranged in a way that each constructor performs a different
task. They are differentiated by the compiler by the number of parameters in the list and their
types.
16
403 – Java Programming Language
Output:
111 Karan 0
222 Aryan 25
There are many differences between constructors and methods. They are given below.
A constructor must not have a return type. A method must have a return type.
The Java compiler provides a default constructor if The method is not provided by the
you don't have any constructor in a class. compiler in any case.
The constructor name must be same as the class The method name may or may not
name. be same as the class name.
17
403 – Java Programming Language
There is no copy constructor in Java. However, we can copy the values from one object to
another like copy constructor in C++.
There are many ways to copy the values of one object into another in Java. They are:
o By constructor
o By assigning the values of one object into another
o By clone() method of Object class
In this example, we are going to copy the values of one object into another using Java
constructor.
//Java program to initialize the values from one object to another object.
class Student6{
int id;
String name;
//constructor to initialize integer and string
Student6(int i,String n){
id = i;
name = n;
}
//constructor to initialize another object
Student6(Student6 s){
id = s.id;
name =s.name;
}
void display(){System.out.println(id+" "+name);}
Output:
18
403 – Java Programming Language
We can copy the values of one object into another by assigning the objects values to another
object. In this case, there is no need to create the constructor.
class Student7{
int id;
String name;
Student7(int i,String n){
id = i;
name = n;
}
Student7(){}
void display(){System.out.println(id+" "+name);}
Output:
111 Karan
111 Karan
19
403 – Java Programming Language
The idea behind inheritance in Java is that you can create new classes that are built upon
existing classes. When you inherit from an existing class, you can reuse methods and fields of
the parent class. Moreover, you can add new methods and fields in your current class also.
Inheritance represents the IS-A relationship which is also known as a parent-child relationship.
The extends keyword indicates that you are making a new class that derives from an existing
class. The meaning of "extends" is to increase the functionality.
In the terminology of Java, a class which is inherited is called a parent or superclass, and the
new class is called child or subclass.
As displayed in the above figure, Programmer is the subclass and Employee is the superclass.
The relationship between the two classes is Programmer IS-A Employee. It means that
Programmer is a type of Employee.
class Employee{
float salary=40000;
20
403 – Java Programming Language
On the basis of class, there can be three types of inheritance in java: single, multilevel and
hierarchical.
In java programming, multiple and hybrid inheritance is supported through interface only. We
will learn about interfaces later.
21
403 – Java Programming Language
When a class inherits another class, it is known as a single inheritance. In the example given
below, Dog class inherits the Animal class, so there is the single inheritance.
File: TestInheritance.java
class Dog {
void bark(){System.out.println("barking...");}
}
class TestInheritance extends Dog{
public static void main(String args[]){
Dog d=new Dog();
d.bark();
}}
Output:
barking...
When there is a chain of inheritance, it is known as multilevel inheritance. As you can see in
the example given below, BabyDog class inherits the Dog class which again inherits the
Animal class, so there is a multilevel inheritance.
File: TestInheritance2.java
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class BabyDog extends Dog{
void weep(){System.out.println("weeping...");}
}
class TestInheritance2{
public static void main(String args[]){
BabyDog d=new BabyDog();
22
403 – Java Programming Language
Output:
weeping...
barking...
eating...
When two or more classes inherits a single class, it is known as hierarchical inheritance. In the
example given below, Dog and Cat classes inherits the Animal class, so there is hierarchical
inheritance.
File: TestInheritance3.java
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class Cat extends Animal{
void meow(){System.out.println("meowing...");}
}
class TestInheritance3{
public static void main(String args[]){
Cat c=new Cat();
c.meow();
c.eat();
//c.bark();//C.T.Error
}}
Output:
meowing...
eating...
23
403 – Java Programming Language
To reduce the complexity and simplify the language, multiple inheritance is not supported in
java.
Consider a scenario where A, B, and C are three classes. The C class inherits A and B classes.
If A and B classes have the same method and you call it from child class object, there will be
ambiguity to call the method of A or B class.
Since compile-time errors are better than runtime errors, Java renders compile-time error if you
inherit 2 classes. So whether you have same method or different, there will be compile time
error.
class A{
void msg(){System.out.println("Hello");}
}
class B{
void msg(){System.out.println("Welcome");}
}
class C extends A,B{//suppose if it were
Polymorphism in Java
Polymorphism is the greek word whose meaning is “same object having different
behaviour”.
Polymorphism in Java is a concept by which we can perform a single action in different
ways. Polymorphism is derived from 2 Greek words: poly and morphs. The word "poly"
means many and "morphs" means forms. So polymorphism means many forms.
We can perform polymorphism in java by method overloading and method overriding.
There are two types of polymorphism in Java:
1. compile-time polymorphism
2. runtime polymorphism.
24
403 – Java Programming Language
Method overloading is one of the way java supports static polymorphism. Here we have two
definitions of the same method add() which add method would be called is determined by the
parameter list at the compile time. That is the reason this is also known as compile time
polymorphism.
class SimpleCalculator
{
int add(int a, int b)
{
return a+b;
}
int add(int a, int b, int c)
{
return a+b+c;
}
}
public class Demo
{
public static void main(String args[])
{
SimpleCalculator obj = new SimpleCalculator();
System.out.println(obj.add(10, 20));
System.out.println(obj.add(10, 20, 30));
}
}
Output:
30
60
25
403 – Java Programming Language
class ABC{
public void myMethod(){
System.out.println("Overridden Method");
}
}
public class XYZ extends ABC{
Method Overloading
Method Overloading is a feature that allows a class to have multiple methods with the same
name but with different number, sequence or type of parameters. In short multiple methods
with same name but with different signatures. For example the signature of method add(int
a, int b) having two int parameters is different from signature of method add(int a, int b, int
c) having three int parameters.
26
403 – Java Programming Language
add(int, int)
add(int, int, int)
2. Data type of parameters.
For example:
add(int, int)
add(int, float)
3. Sequence of Data type of parameters.
For example:
add(int, float)
add(float, int)
Invalid case of method overloading:
Parameters list doesn‟t mean the return type of the method, for example if two methods have
same name, same parameters and have different return type, then this is not a valid method
overloading example. This will throw a compilation error.
In this example, we are overloading the method add() based on the data type of parameters.
We have two methods with the name add() but the type of parameters are different. The first
variation of add() has two int params while the second variation of method add() has two float
params.
class DisplayOverloading2
{
//two int parameters
27
403 – Java Programming Language
class JavaExample
{
public static void main(String args[])
{
DisplayOverloading2 obj = new DisplayOverloading2();
//This will call the method add with two int params
System.out.println(obj.add(5, 15));
//This will call the method add with two float params
System.out.println(obj.add(5.5f, 2.5f));
}
}
Output:
20
8.0
Method overriding
Declaring a method in sub class which is already present in parent class is known as method
overriding. Overriding is done so that a child class can give its own implementation to a
method which is already provided by the parent class. In this case the method in parent class is
called overridden method and the method in child class is called overriding method. In this
guide, we will see what is method overriding in Java and why we use it.
Method Overriding Example
Lets take a simple example to understand this. We have two classes: A child class Boy and a
parent class Human. The Boy class extends Human class. Both the classes have a common
28
403 – Java Programming Language
The purpose of Method Overriding is clear here. Child class wants to give its own
implementation so that when it calls this method, it prints Boy is eating instead of Human is
eating.
class Human{
//Overridden method
public void eat()
{
System.out.println("Human is eating");
}
}
class Boy extends Human{
//Overriding method
public void eat(){
System.out.println("Boy is eating");
}
public static void main( String args[]) {
Boy obj = new Boy();
//This will call the child class version of eat()
obj.eat();
}
}
Output:
Boy is eating
Advantage of method overriding
The main advantage of method overriding is that the class can give its own specific
implementation to a inherited method without even modifying the parent class code.
This is helpful when a class has several child classes, so if a child class needs to use the parent
class method, it can use it and the other classes that want to have different implementation can
use overriding feature to make changes without touching the parent class code.
Abstract method
Method which has no body has to be declare as abstract method.
Abstract class
When there is one or more abstract method in a class then that class should be declared
as abstract class.
To declare a class as abstract, use abstract keyword in front of class keyword.
We cannot create an object of abstract class, it is only used for inheritance purpose.
29
403 – Java Programming Language
30
403 – Java Programming Language
31
403 – Java Programming Language
INTERFACE
An interface in Java is a blueprint of a class. It has static constants and abstract methods.
The interface in Java is a mechanism to achieve abstraction. There can be only abstract
methods in the Java interface, not method body. It is used to achieve abstraction and
multiple inheritance in Java.
In other words, you can say that interfaces can have abstract methods and variables. It cannot
have a method body.
There are mainly three reasons to use interface. They are given below.
32
403 – Java Programming Language
Syntax:
interface <interface_name>{
// declare constant fields
// declare methods that abstract
// by default.
}
Java Interface Example
interface printable{
void print();
}
class A6 implements printable{
public void print(){System.out.println("Hello");}
In this example, the Drawable interface has only one method. Its implementation is provided
by Rectangle and Circle classes. In a real scenario, an interface is defined by someone else, but
its implementation is provided by different implementation providers. Moreover, it is used by
someone else. The implementation part is hidden by the user who uses the interface.
File: TestInterface1.java
33
403 – Java Programming Language
Output:
drawing circle
Let's see another example of java interface which provides the implementation of Bank
interface.
File: TestInterface2.java
interface Bank{
float rateOfInterest();
}
class SBI implements Bank{
public float rateOfInterest(){return 9.15f;}
}
class PNB implements Bank{
public float rateOfInterest(){return 9.7f;}
}
class TestInterface2{
public static void main(String[] args){
Bank b=new SBI();
System.out.println("ROI: "+b.rateOfInterest());
}}
Output:
ROI: 9.15
34
403 – Java Programming Language
interface Printable{
void print();
}
interface Showable{
void show();
}
class A7 implements Printable,Showable{
public void print(){System.out.println("Hello");}
public void show(){System.out.println("Welcome");}
As we have explained in the inheritance chapter, multiple inheritance is not supported in the
case of class because of ambiguity. However, it is supported in case of an interface because
there is no ambiguity. It is because its implementation is provided by the implementation class.
For example:
35
403 – Java Programming Language
Output:
Hello
As you can see in the above example, Printable and Showable interface have same methods but
its implementation is provided by class TestTnterface1, so there is no ambiguity.
Interface inheritance
interface Printable{
void print();
}
interface Showable extends Printable{
void show();
}
class TestInterface4 implements Showable{
public void print(){System.out.println("Hello");}
public void show(){System.out.println("Welcome");}
36
403 – Java Programming Language
Output:
Hello
Welcome
Note: An interface can have another interface which is known as a nested interface. We will
learn it in detail in the nested classes chapter. For example:
interface printable{
void print();
interface MessagePrintable{
void msg();
}
}
CLASS INTERFACE
Variables declared in class may be Variables declared in interface are
constant. always constant.
methods declared in a class may methods declared in an interface
have body or may not have body. have no body.
we can make abstract methods using Methods declared within an interface
abstract keyword. will be abstract by default
We can use public, private, protected We can use only public or default
or default access sprcifier in class access specifier in an interface
We can only declared reference
We can create object of class
variable of an interface
We have to use extends keyword to We have to use implements keyword
inherit the class into another class to implement interface into class
We cannot inherit more than one We can implement more than one
class in a class interface into a class.
37
403 – Java Programming Language
Sometimes a method needs to refer to the object that invokes it, to allow. Java defines
„This‟
keyword.
„This‟ can be used inside any method to refer to the current object.
„This‟ keyword is always referenced to the object on which method was invoked.
We can use „This‟ keyword anywhere. It is one type of self referential structure.
A reference to an object of current class is always permitted.
Example:
class Student{
int rollno;
String name;
float fee;
Student(int rollno,String name,float fee){
this.rollno=rollno;
this.name=name;
this.fee=fee;
}
void display(){System.out.println(rollno+" "+name+" "+fee);}
}
class TestThis2{
public static void main(String args[]){
Student s1=new Student(111,"ankit",5000f);
Student s2=new Student(112,"sumit",6000f);
s1.display();
s2.display();
}}
super keyword:
The super keyword in Java is a reference variable which is used to refer immediate parent
class object.
Whenever you create the instance of subclass, an instance of parent class is created implicitly
which is referred by super reference variable.
38
403 – Java Programming Language
We can use super keyword to access the data member or field of parent class. It is used if
parent class and child class have same fields.
class Animal{
String color="white";
}
class Dog extends Animal{
String color="black";
void printColor(){
System.out.println(color);//prints color of Dog class
System.out.println(super.color);//prints color of Animal class
}
}
class TestSuper1{
public static void main(String args[]){
Dog d=new Dog();
d.printColor();
}}
Output:
black
white
In the above example, Animal and Dog both classes have a common property color. If we print
color property, it will print the color of current class by default. To access the parent property,
we need to use super keyword.
The super keyword can also be used to invoke parent class method. It should be used if
subclass contains the same method as parent class. In other words, it is used if method is
overridden.
class Animal{
void eat(){System.out.println("eating...");}
39
403 – Java Programming Language
Output:
eating...
barking...
In the above example Animal and Dog both classes have eat() method if we call eat() method
from Dog class, it will call the eat() method of Dog class by default because priority is given to
local.
The super keyword can also be used to invoke the parent class constructor. Let's see a simple
example:
class Animal{
Animal(){System.out.println("animal is created");}
}
class Dog extends Animal{
Dog(){
super();
System.out.println("dog is created");
}
}
class TestSuper3{
public static void main(String args[]){
40
403 – Java Programming Language
Output:
animal is created
dog is created
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.
Moreover, Java provides the feature of anonymous arrays which is not available in C/C++.
Advantages
o Code Optimization: It makes the code optimized, we can retrieve or sort the data
efficiently.
o Random access: We can get any data located at an index position.
Disadvantages
o 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.
41
403 – Java Programming Language
arrayRefVar=new datatype[size];
Example of Java Array
Let's see the simple example of java array, where we are going to declare, instantiate, initialize
and traverse an 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
42
403 – Java Programming Language
We can declare, instantiate and initialize the java array together by:
class Testarray1{
public static void main(String args[]){
int a[]={33,3,4,5};//declaration, instantiation and initialization
//printing array
for(int i=0;i<a.length;i++)//length is the property of array
System.out.println(a[i]);
}}
Output:
33
3
4
5
We can pass the java array to method so that we can reuse the same logic on any array.
Let's see the simple example to get the minimum number of an array using a method.
class Testarray2{
//creating a method which receives an array as a parameter
static void min(int arr[]){
int min=arr[0];
for(int i=1;i<arr.length;i++)
if(min>arr[i])
min=arr[i];
System.out.println(min);
}
public static void main(String args[]){
int a[]={33,3,4,5};//declaring and initializing an array
min(a);//passing array to method
}}
Output:
43
403 – Java Programming Language
In such case, data is stored in row and column based index (also known as matrix form).
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
Let's see the simple example to declare, instantiate, initialize and print the 2Dimensional 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]+" ");
}
44
403 – Java Programming Language
Output:
123
245
445
Output:
45
403 – Java Programming Language
class Testarray5{
public static void main(String args[]){
//creating two matrices
int a[][]={{1,3,4},{3,4,5}};
int b[][]={{1,3,4},{3,4,5}};
//creating another matrix to store the sum of two matrices
int c[][]=new int[2][3];
//adding and printing addition of 2 matrices
for(int i=0;i<2;i++){
for(int j=0;j<3;j++){
c[i][j]=a[i][j]+b[i][j];
System.out.print(c[i][j]+" ");
}
System.out.println();//new line
}
}}
Output:
268
6 8 10
In the case of matrix multiplication, a one-row element of the first matrix is multiplied by all
the columns of the second matrix which can be understood by the image given below.
46
403 – Java Programming Language
Let's see a simple example to multiply two matrices of 3 rows and 3 columns.
Output:
47
403 – Java Programming Language
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.
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:
48
403 – Java Programming Language
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.
49
Unit 3. Basic Concepts of Strings and Exceptions
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:
char[] ch={'k','i','r','t','a','n'};
String s=new String(ch);
is same as:
String s="kirtan";
Java String class provides a lot of methods to perform operations on strings such as
compare(), concat(), equals(), split(), length(), replace(), substring() etc.
CharSequence Interface
1
Unit 3. Basic Concepts of Strings and Exceptions
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 StringBuffer and
StringBuilder classes.
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.
1. By string literal
2. By new keyword
1) String Literal
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:
String s1="Welcome";
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.
Note: String objects are stored in a special memory area known as the "string constant
pool".
To make Java more memory efficient (because no new objects are created if it exists already
in the string constant pool).
2
Unit 3. Basic Concepts of Strings and Exceptions
2) By new keyword
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).
char ch[]={'s','t','r','i','n','g','s'};
String s2=new String(ch);//converting char array to string
System.out.println(s1);
System.out.println(s2);
System.out.println(s3);
}}
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.
A String is an unavoidable type of variable while writing any application program. String
references are used to store various attributes like username, password, etc. In Java, String
objects are immutable. Immutable simply means unmodifiable or unchangeable.
3
Unit 3. Basic Concepts of Strings and Exceptions
Once String object is created its data or state can't be changed but a new String object is created.
Let's try to understand the concept of immutability by the example given below:
class Testimmutablestring{
public static void main(String args[]){
String s="Sachin";
s.concat(" Tendulkar");//concat() method appends the string at the end
System.out.println(s);//will print Sachin because strings are immutable objects
} }
Output:
Sachin
Now it can be understood by the diagram given below. Here Sachin is not changed but a new
object is created with Sachin Tendulkar. That is why String is known as immutable.
As you can see in the above figure that two objects are created but s reference variable still
refers to "Sachin" not to "Sachin Tendulkar".
But if we explicitly assign it to the reference variable, it will refer to "Sachin Tendulkar" object.
String s="Sachin";
s=s.concat(" Tendulkar");
System.out.println(s);
Sachin Tendulkar
In such a case, s points to the "Sachin Tendulkar". Please notice that still Sachin object is not
modified.
4
Unit 3. Basic Concepts of Strings and Exceptions
Why String objects are immutable in Java?
As Java uses the concept of String literal. Suppose there are 5 reference variables, all refer to
one object "Sachin". If one reference variable changes the value of the object, it will be affected
by all the reference variables. That is why String objects are immutable in Java.
The reason behind the String class being final is because no one can override the methods of
the String class. So that it can provide the same features to the new String objects as well as to
the old ones.
The java.lang.String class provides many useful methods to perform operations on sequence
of char values.
1. charAt()
The Java String class charAt() method returns a char value at the given index number.
The index number starts from 0 and goes to n-1, where n is the length of the string. It
returns StringIndexOutOfBoundsException, if the given index number is greater than or
equal to this string length or a negative number.
Syntax
The method accepts index as a parameter. The starting index is 0. It returns a character at a
specific index position in a string. It throws StringIndexOutOfBoundsException if the index
is a negative value or greater than this string length.
String s="Sachin";
System.out.println(s.charAt(0));//S
System.out.println(s.charAt(3));//h
S
h
2. concat()
5
Unit 3. Basic Concepts of Strings and Exceptions
The Java String class concat() method combines specified string at the end of this string. It
returns a combined string. It is like appending another string.
Signature
Parameter
Returns
combined string
Sachin Tendulkar
The above Java program, concatenates two String objects s1 and s2 using concat() method
and stores the result into s3 object.
3. equals()
The Java String class equals() method compares the two given strings based on the content
of the string. If any character is not matched, it returns false. If all characters are matched, it
returns true.
The String equals() method overrides the equals() method of the Object class.
Returns
6
Unit 3. Basic Concepts of Strings and Exceptions
String s2="kirtan";
String s3="KIRTAN";
String s4="MIHIKA";
System.out.println(s1.equals(s2));//true because content and case is same
System.out.println(s1.equals(s3));//false because case is not same
System.out.println(s1.equals(s4));//false because content is not same
true
false
false
4. indexOf()
The Java String class indexOf() method returns the position of the first occurrence of the
specified character or string in a specified string.
Signature
There are four overloaded indexOf() method in Java. The signature of indexOf() methods are
given below:
1 int indexOf(int ch) It returns the index position for the given char
value
2 int indexOf(int ch, int fromIndex) It returns the index position for the given char
value and from index
3 int indexOf(String substring) It returns the index position for the given
substring
4 int indexOf(String substring, int It returns the index position for the given
fromIndex) substring and from index
Parameters
fromIndex: The index position from where the index of the char value or substring is returned.
7
Unit 3. Basic Concepts of Strings and Exceptions
Returns
//passing substring
int index1=s1.indexOf("is");//returns the index of is substring
int index2=s1.indexOf("index");//returns the index of index substring
System.out.println(index1+" "+index2);//2 8
28
5
3
We observe that when a searched string or character is found, the method returns a non-
negative value. If the string or character is not found, -1 is returned. We can use this property
to find the total count of a character present in the given string.
5. lastIndexOf()
The Java String class lastIndexOf() method returns the last index of the given character value
or substring. If it is not found, it returns -1. The index counter starts from zero.
Signature
There are four types of lastIndexOf() method in Java. The signature of the methods are given
below:
8
Unit 3. Basic Concepts of Strings and Exceptions
1 int lastIndexOf(int ch) It returns last index position for the given char
value
2 int lastIndexOf(int ch, int fromIndex) It returns last index position for the given char
value and from index
3 int lastIndexOf(String substring) It returns last index position for the given
substring
4 int lastIndexOf(String substring, int It returns last index position for the given
fromIndex) substring and from index
Parameters
fromIndex: index position from where index of the char value or substring is retured
Returns
Here, we are finding the last index from the string by specifying fromIndex.
9
Unit 3. Basic Concepts of Strings and Exceptions
19
19
-1
6. isEmpty()
The Java String class isEmpty() method checks if the input string is empty or not. Note that
here empty means the number of characters contained in a string is zero.
Returns
String s1="";
String s2="kirtan";
System.out.println(s1.isEmpty());
System.out.println(s2.isEmpty());
10
Unit 3. Basic Concepts of Strings and Exceptions
true
false
7. join()
The Java String class join() method returns a string joined with a given delimiter. In the String
join() method, the delimiter is copied for each element. The join() method is included in the
Java string since JDK 1.8.
Signature
Parameters
Returns
Exception Throws
String joinString1=String.join("-","welcome","to","javaworld");
System.out.println(joinString1);
welcome-to-javaworld
8. length()
The Java String class length() method finds the length of a string. The length of the Java
string is the same as the Unicode code units of the string.
Signature
11
Unit 3. Basic Concepts of Strings and Exceptions
Specified by
CharSequence interface
Returns
Length of characters. In other words, the total number of characters present in the string.
String s1="kirtanpatel";
String s2="python";
System.out.println("string length is: "+s1.length());//11 is the length of kirtanpatel
stringSystem.out.println("string length is: "+s2.length());//6 is the length of python
string
9. split()
The java string split() method splits this string against given regular expression and returns a
char array.
Signature
Parameter
limit : limit for the number of strings in array. If it is zero, it will returns all the strings matching
regex.
Returns
array of strings
12
Unit 3. Basic Concepts of Strings and Exceptions
System.out.println(w);
}
java
string
split
method
by
kirtan
Output
Return Value :
Welcome
To
java
10.substring()
The Java String class substring() method returns a part of the string.
We pass beginIndex and endIndex number position in the Java substring method where
beginIndex is inclusive, and endIndex is exclusive. In other words, the beginIndex starts from
0, whereas the endIndex starts from 1.
Signature
13
Unit 3. Basic Concepts of Strings and Exceptions
If we don't specify endIndex, the method will return all the characters from startIndex.
Parameters
Returns
specified string
Exception Throws
kirtan
rtan
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: begin 5, end 15,
length 6
11.trim()
The Java String class trim() method eliminates leading and trailing spaces. The Unicode
value of space character is '\u0020'. The trim() method in Java string checks this Unicode value
before and after the string, if it exists then the method removes the spaces and returns the
omitted string.
Signature
14
Unit 3. Basic Concepts of Strings and Exceptions
The signature or syntax of the String class trim() method is given below:
Returns
The Java String toUpperCase() method converts this String into uppercase letter and String
toLowerCase() method into lowercase letter.
String s="Sachin";
System.out.println(s.toUpperCase());//SACHIN
System.out.println(s.toLowerCase());//sachin
System.out.println(s);//Sachin(no change in original)
SACHIN
sachin
13. startsWith() and endsWith()
Sachin
The method startsWith() checks whether the String starts with the letters passed as arguments
and endsWith() method checks whether the String ends with the letters passed as arguments.
String s="Sachin";
System.out.println(s.startsWith("Sa"));//true
System.out.println(s.endsWith("n"));//true
true
true
14. replace()
The String class replace() method replaces all occurrence of first sequence of character with
second sequence of character.
15
Unit 3. Basic Concepts of Strings and Exceptions
String s1="Java is a programming language. Java is a platform. Java is an Island.";
String replaceString=s1.replace("Java","Kava");//replaces all occurrences of "Java" to "Kava
"
System.out.println(replaceString);
String comparision
The String class equals() method compares the original content of the string. It compares
values of string for equality. String class provides the following two methods:
o public boolean equals(Object another) compares this string to the specified object.
true
true
false
In the above code, two strings are compared using equals() method of String class. And the
16
Unit 3. Basic Concepts of Strings and Exceptions
result is printed as boolean values, true or false.
String s1="Sachin";
String s2="SACHIN";
System.out.println(s1.equals(s2));//false
System.out.println(s1.equalsIgnoreCase(s2));//true
false
true
In the above program, the methods of String class are used. The equals() method returns true
if String objects are matching and both strings are of same case. equalsIgnoreCase() returns
true regardless of cases of strings.
2) By Using == operator
String s1="Sachin";
String s2="Sachin";
String s3=new String("Sachin");
System.out.println(s1==s2);//true (because both refer to same instance)
System.out.println(s1==s3);//false(because s3 refers to instance created in nonpool)
true
false
The String class compareTo() method compares values lexicographically and returns an
integer value that describes if first string is less than, equal to or greater than second string.
String s1="Sachin";
String s2="Sachin";
String s3="Ratan";
17
Unit 3. Basic Concepts of Strings and Exceptions
System.out.println(s1.compareTo(s2));//0
System.out.println(s1.compareTo(s3));//1(because s1>s3)
System.out.println(s3.compareTo(s1));//-1(because s3 < s1 )
0
1
-1
In Java, String concatenation forms a new String that is the combination of multiple strings.
There are two ways to concatenate strings in Java:
String s="Sachin"+"Tendulkar";
System.out.println(s);//Sachin Tendulkar
Output:
In Java, String concatenation is implemented through the StringBuilder (or StringBuffer) class
and it's append method. String concatenation operator produces a new String by appending the
second operand onto the end of the first operand. The String concatenation operator can
concatenate not only String but primitive values also. For Example:
String s=50+30+"Sachin"+40+40;
System.out.println(s);//80Sachin4040
1.
80Sachin4040
Note: After a string literal, all the + will be treated as string concatenation operator.
The String concat() method concatenates the specified string to the end of current string.
Syntax:
public String concat(String another)
18
Unit 3. Basic Concepts of Strings and Exceptions
String s1="Sachin ";
String s2="Tendulkar";
String s3=s1.concat(s2);
System.out.println(s3);//Sachin Tendulkar
Sachin Tendulkar
The above Java program, concatenates two String objects s1 and s2 using concat() method
and stores the result into s3 object.
Hello World
In the above code snippet, s1, s2 and s are declared as objects of StringBuilder class. s stores
the result of concatenation of s1 and s2 using append() method.
String.format() method allows to concatenate multiple strings using format specifier like %s
followed by the string values or objects.
Hello World
The String.join() method is available in Java version 8 and all the above versions. String.join()
19
Unit 3. Basic Concepts of Strings and Exceptions
method accepts arguments first a separator and an array of String objects.
Hello World
In the above code snippet, the String object s stores the result of String.join("",s1,s2) method.
A separator is specified inside quotation marks followed by the String objects or array of String
objects.
toString() Method
If you want to represent any object as a string, toString() method comes into existence.
If you print any object, Java compiler internally invokes the toString() method on the object.
So overriding the toString() method, returns the desired output, it can be the state of an object
etc. depending on your implementation.
By overriding the toString() method of the Object class, we can return values of the object, so
we don't need to write much code.
Output
20
Unit 3. Basic Concepts of Strings and Exceptions
10
The second implementation is when you call the member method of the relevant class
by passing the value as an argument. The example below shows how to do this
class HelloWorld {
public static void main( String args[] ) {
//Integer
System.out.println(Integer.toString(12));
// Long
System.out.println(Long.toString(123213123));
// Booleam
System.out.println(Boolean.toString(false));
}
}
Output
11.0
12
123213123
false
import java.io.*;
class vowel
{
public static void main(String args[])throws IOException
{
DataInputStream dis=new DataInputStream(System.in);
int cnt=0;
21
Unit 3. Basic Concepts of Strings and Exceptions
System.out.println("enter string");
String st=dis.readLine();
for(int i=0;i<st.length();i++)
{
char t=st.charAt(i);
if(t=='a' || t=='e' || t=='o' || t=='i' || t=='u' ||
t=='A' || t=='E' || t=='O' || t=='I' || t=='U')
cnt++;
}
System.out.println("total vowels:- "+cnt);
}
}
class sort1
{
public static void main(String args[])
{
String st[]={"w","p","a","k","z"};
for(int i=0;i<st.length;i++)
{
for(int j=i+1;j<st.length;j++)
{
if(st[i].compareTo(st[j])>0)
{
String t=st[i];
st[i]=st[j];
st[j]=t;
}
}
}
for(String t:st)
{
System.out.println(t);
}
}
}
22
Unit 3. Basic Concepts of Strings and Exceptions
Example 3: (write a program to find words beginning with ‘p’ chatacter in inputted
string)
import java.io.*;
class search1
{
public static void main(String args[])throws IOException
{
DataInputStream dis=new DataInputStream(System.in);
System.out.println("enter string");
String st=dis.readLine();
String t[]=st.split(" ");
for(int i=0;i<t.length;i++)
{
if(t[i].startsWith("p"))
System.out.println(t[i]);
}
}
}
23
Unit 3. Basic Concepts of Strings and Exceptions
Java 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.
StringBuffer() It creates an empty String buffer with the initial capacity of 16.
public insert(int offset, String It is used to insert the specified string with this
synchronized s) string at the specified position. The insert()
StringBuffer method is overloaded like insert(int, char),
insert(int, boolean), insert(int, int), insert(int,
float), insert(int, double) etc.
public delete(int startIndex, int It is used to delete the string from specified
synchronized endIndex) startIndex and endIndex.
StringBuffer
24
Unit 3. Basic Concepts of Strings and Exceptions
public char charAt(int index) It is used to return the character at the specified
position.
public int length() It is used to return the length of the string i.e.
total number of characters.
A String that can be modified or changed is known as mutable String. StringBuffer and
StringBuilder classes are used for creating mutable strings.
The append() method concatenates the given argument with this String.
StringBufferExample.java
class StringBufferExample{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello ");
sb.append("Java");//now original string is changed
System.out.println(sb);//prints Hello Java
}
}
Output:
Hello Java
The insert() method inserts the given String with this string at the given position.
StringBufferExample2.java
class StringBufferExample2{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello ");
25
Unit 3. Basic Concepts of Strings and Exceptions
sb.insert(1,"Java");//now original string is changed
System.out.println(sb);//prints HJavaello
}
}
Output:
HJavaello
The replace() method replaces the given String from the specified beginIndex and endIndex.
StringBufferExample3.java
class StringBufferExample3{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello");
sb.replace(1,3,"Java");
System.out.println(sb);//prints HJavalo
}
}
Output:
HJavalo
The delete() method of the StringBuffer class deletes the String from the specified beginIndex to
endIndex.
StringBufferExample4.java
class StringBufferExample4{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello");
sb.delete(1,3);
System.out.println(sb);//prints Hlo
}
}
Output:
26
Unit 3. Basic Concepts of Strings and Exceptions
Hlo
The reverse() method of the StringBuilder class reverses the current String.
StringBufferExample5.java
class StringBufferExample5{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello");
sb.reverse();
System.out.println(sb);//prints olleH
}
}
Output:
olleH
The capacity() method of the StringBuffer class returns the current capacity of the buffer. The
default capacity of the buffer is 16. If the number of character increases from its current capacity,
it increases the capacity by (oldcapacity*2)+2. For example if your current capacity is 16, it will
be (16*2)+2=34.
StringBufferExample6.java
class StringBufferExample6{
public static void main(String args[]){
StringBuffer sb=new StringBuffer();
System.out.println(sb.capacity());//default 16
sb.append("Hello");
System.out.println(sb.capacity());//now 16
sb.append("java is my favourite language");
System.out.println(sb.capacity());//now (16*2)+2=34 i.e (oldcapacity*2)+2
}
}
Output:
16
16
34
27
Unit 3. Basic Concepts of Strings and Exceptions
7) StringBuffer ensureCapacity() method
The ensureCapacity() method of the StringBuffer class ensures that the given capacity is the
minimum to the current capacity. If it is greater than the current capacity, it increases the capacity
by (oldcapacity*2)+2. For example if your current capacity is 16, it will be (16*2)+2=34.
StringBufferExample7.java
class StringBufferExample7{
public static void main(String args[]){
StringBuffer sb=new StringBuffer();
System.out.println(sb.capacity());//default 16
sb.append("Hello");
System.out.println(sb.capacity());//now 16
sb.append("java is my favourite language");
System.out.println(sb.capacity());//now (16*2)+2=34 i.e (oldcapacity*2)+2
sb.ensureCapacity(10);//now no change
System.out.println(sb.capacity());//now 34
sb.ensureCapacity(50);//now (34*2)+2
System.out.println(sb.capacity());//now 70
}
}
Output:
16
16
34
34
70
2) String is slow and consumes more memory StringBuffer is fast and consumes
when we concatenate too many strings less memory when we concatenate
because every time it creates new instance. t strings.
28
Unit 3. Basic Concepts of Strings and Exceptions
3) String class overrides the equals() method of StringBuffer class doesn't override
Object class. So you can compare the the equals() method of Object
contents of two strings by equals() method. class.
5) String class uses String constant pool. StringBuffer uses Heap memory
In this tutorial, we will learn about Java exceptions, it's types, and the difference between checked
and unchecked exceptions.
In Java, an exception is an event that disrupts the normal flow of the program. It is an object which
is thrown at runtime.
The core advantage of exception handling is to maintain the normal flow of the application. An
exception normally disrupts the normal flow of the application; that is why we need to handle
exceptions. Let's consider a scenario:
statement 1;
statement 2;
statement 3;
statement 4;
statement 5;//exception occurs
statement 6;
statement 7;
statement 8;
statement 9;
statement 10;
29
Unit 3. Basic Concepts of Strings and Exceptions
Suppose there are 10 statements in a Java program and an exception occurs at statement 5; the rest
of the code will not be executed, i.e., statements 6 to 10 will not be executed. However, when we
perform exception handling, the rest of the statements will be executed. That is why we use
exception handling in Java.
The java.lang.Throwable class is the root class of Java Exception hierarchy inherited by two
subclasses: Exception and Error. The hierarchy of Java Exception classes is given below:
1. Checked Exception
2. Unchecked Exception
3. Error
30
Unit 3. Basic Concepts of Strings and Exceptions
Difference between Checked and Unchecked Exceptions
1) Checked Exception
The classes that directly inherit the Throwable class except RuntimeException and Error are
known as checked exceptions. For example, IOException, SQLException, etc. Checked
exceptions are checked at compile-time.
2) Unchecked Exception
The classes that inherit the RuntimeException are known as unchecked exceptions. For example,
ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException, etc. Unchecked
exceptions are not checked at compile-time, but they are checked at runtime.
3) Error
Java provides five keywords that are used to handle the exception. The following table describes
each.
Keyword Description
try The "try" keyword is used to specify a block where we should place
an exception code. It means we can't use try block alone. The try
block must be followed by either catch or finally.
finally The "finally" block is used to execute the necessary code of the
program. It is executed whether an exception is handled or not.
Let's see an example of Java Exception Handling in which we are using a try-catch statement to
handle the exception.
31
Unit 3. Basic Concepts of Strings and Exceptions
JavaExceptionExample.java
In the above example, 100/0 raises an ArithmeticException which is handled by a try-catch block.
There are given some scenarios where unchecked exceptions may occur. They are as follows:
int a=50/0;//ArithmeticException
2) A scenario where NullPointerException occurs
If we have a null value in any variable, performing any operation on the variable throws a
NullPointerException.
String s=null;
System.out.println(s.length());//NullPointerException
3) A scenario where NumberFormatException occurs
String s="abc";
int i=Integer.parseInt(s);//NumberFormatException
32
Unit 3. Basic Concepts of Strings and Exceptions
4) A scenario where ArrayIndexOutOfBoundsException occurs
When an array exceeds to it's size, the ArrayIndexOutOfBoundsException occurs. there may be
other reasons to occur ArrayIndexOutOfBoundsException. Consider the following statements.
Java try block is used to enclose the code that might throw an exception. It must be used within
the method.
If an exception occurs at the particular statement in the try block, the rest of the block code will
not execute. So, it is recommended not to keep the code in try block that will not throw an
exception.
Java catch block is used to handle the Exception by declaring the type of exception within the
parameter. The declared exception must be the parent class exception ( i.e., Exception) or the
generated exception type. However, the good approach is to declare the generated type of
exception.
The catch block must be used after the try block only. You can use multiple catch block with a
single try block.
The JVM firstly checks whether the exception is handled or not. If exception is not handled, JVM
provides a default exception handler that performs the following tasks:
33
Unit 3. Basic Concepts of Strings and Exceptions
o Prints out exception description.
o Prints the stack trace (Hierarchy of methods where the exception occurred).
o Causes the program to terminate.
But if the application programmer handles the exception, the normal flow of the application is
maintained, i.e., rest of the code is executed.
Example 1
TryCatchExample1.java
}
}
Output:
As displayed in the above example, the rest of the code is not executed (in such case, the rest of
the code statement is not printed).
There might be 100 lines of code after the exception. If the exception is not handled, all the code
below the exception won't be executed.
Let's see the solution of the above problem by a java try-catch block.
Example 2
TryCatchExample2.java
34
Unit 3. Basic Concepts of Strings and Exceptions
{
int data=50/0; //may throw exception
}
//handling the exception
catch(ArithmeticException e)
{
System.out.println(e);
}
System.out.println("rest of the code");
}
}
Output:
java.lang.ArithmeticException: / by zero
rest of the code
Consider the example 1 in which InvalidAgeException class extends the Exception class.
Using the custom exception, we can have your own exception and message. Here, we have passed
a string to the constructor of superclass i.e. Exception class that can be obtained using
getMessage() method on the object we have created.
In this section, we will learn how custom exceptions are implemented and used in Java programs.
Java exceptions cover almost all the general type of exceptions that may occur in the
programming. However, we sometimes need to create custom exceptions.
In order to create custom exception, we need to extend Exception class that belongs to java.lang
package.
35
Unit 3. Basic Concepts of Strings and Exceptions
Consider the following example, where we create a custom exception named
WrongFileNameException:
Let's see a simple example of Java custom exception. In the following code, constructor of
InvalidAgeException takes a string as an argument. This string is passed to constructor of parent
class Exception using the super() method. Also the constructor of Exception class can be called
without using a parameter and calling super() method is not mandatory.
Example 2:
TestCustomException.java
36
Unit 3. Basic Concepts of Strings and Exceptions
catch (MyCustomException ex)
{
System.out.println("Caught the exception");
System.out.println(ex.getMessage());
}
Output:
We specify the exception object which is to be thrown. The Exception has some message with it
that provides the error description. These exceptions may be related to user inputs, server, etc.
We can throw either checked or unchecked exceptions in Java by throw keyword. It is mainly used
to throw a custom exception. We will discuss custom exceptions later in this section.
We can also define our own set of conditions and throw an exception explicitly using throw
keyword. For example, we can throw ArithmeticException if we divide a number by another
number. Here, we just need to set the condition and throw exception using throw keyword.
37
Unit 3. Basic Concepts of Strings and Exceptions
Where the Instance must be of type Throwable or subclass of Throwable. For example, Exception
is the sub class of Throwable and the user-defined exceptions usually extend the Exception class.
In this example, we have created a method named validate() that accepts an integer as a parameter.
If the age is less than 18, we are throwing the ArithmeticException otherwise print a message
welcome to vote.
TestThrow1.java
In this example, we have created the validate method that takes integer value as a parameter. If the
age is less than 18, we are throwing the ArithmeticException otherwise print a message welcome
to vote.
Output:
38
Unit 3. Basic Concepts of Strings and Exceptions
The above code throw an unchecked exception. Similarly, we can also throw unchecked and user
defined exceptions.
Note: If we throw unchecked exception from a method, it is must to handle the exception or
declare in throws clause.
If we throw a checked exception using throw keyword, it is must to handle the exception using
catch block or the method must declare it using throws declaration.
TestThrow2.java
import java.io.*;
}
//main method
public static void main(String args[]){
try
{
method();
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
System.out.println("rest of the code...");
}
39
Unit 3. Basic Concepts of Strings and Exceptions
}
Output:
TestThrow3.java
40
Unit 3. Basic Concepts of Strings and Exceptions
}
Output:
Exception Handling is mainly used to handle the checked exceptions. If there occurs any
unchecked exception such as NullPointerException, it is programmers' fault that he is not
checking the code before it being used.
Let's see the example of Java throws clause which describes that checked exceptions can be
propagated by throws keyword.
Testthrows1.java
41
Unit 3. Basic Concepts of Strings and Exceptions
import java.io.IOException;
class Testthrows1{
void m()throws IOException{
throw new IOException("device error");//checked exception
}
void n()throws IOException{
m();
}
void p(){
try{
n();
}catch(Exception e){System.out.println("exception handled");}
}
public static void main(String args[]){
Testthrows1 obj=new Testthrows1();
obj.p();
System.out.println("normal flow...");
}
}
Output:
exception handled
normal flow...
Rule: If we are calling a method that declares an exception, we must either caught or declare the
exception.
1. Case 1: We have caught the exception i.e. we have handled the exception using try/catch
block.
2. Case 2: We have declared the exception i.e. specified throws keyword with the method.
In case we handle the exception, the code will be executed fine whether exception occurs during
the program or not.
Testthrows2.java
import java.io.*;
class M{
42
Unit 3. Basic Concepts of Strings and Exceptions
void method()throws IOException{
throw new IOException("device error");
}
}
public class Testthrows2{
public static void main(String args[]){
try{
M m=new M();
m.method();
}catch(Exception e){System.out.println("exception handled");}
System.out.println("normal flow...");
}
}
Output:
exception handled
normal flow...
Case 2: Declare Exception
o In case we declare the exception, if exception does not occur, the code will be executed fine.
o In case we declare the exception and the exception occurs, it will be thrown at runtime
because throws does not handle the exception.
Testthrows3.java
import java.io.*;
class M{
void method()throws IOException{
System.out.println("device operation performed");
}
}
class Testthrows3{
public static void main(String args[])throws IOException{//declare exception
M m=new M();
m.method();
System.out.println("normal flow...");
43
Unit 3. Basic Concepts of Strings and Exceptions
}
}
Output:
B) If exception occurs
Testthrows4.java
import java.io.*;
class M{
void method()throws IOException{
throw new IOException("device error");
}
}
class Testthrows4{
public static void main(String args[])throws IOException{//declare exception
M m=new M();
m.method();
System.out.println("normal flow...");
}
}
Output:
44
Unit 3. Basic Concepts of Strings and Exceptions
2. Type of Using throw keyword, we can Using throws keyword, we can
exception only propagate unchecked declare both checked and
exception i.e., the checked unchecked exceptions. However,
exception cannot be the throws keyword can be used to
propagated using throw only. propagate checked exceptions only.
4. Declaration throw is used within the throws is used with the method
method. signature.
Along with this, there are many differences between final, finally and finalize. A list of differences
between final, finally and finalize are given below:
1. Definition final is the keyword and finally is the block in finalize is the method
access modifier which Java Exception in Java which is used
is used to apply Handling to execute to perform clean up
restrictions on a class, the important code processing just before
method or variable. whether the exception object is garbage
occurs or not. collected.
45
Unit 3. Basic Concepts of Strings and Exceptions
3. Functionality (1) Once declared, final (1) finally block runs finalize method
variable becomes the important code performs the cleaning
constant and cannot be even if exception activities with respect
modified. occurs or not. to the object before its
(2) final method cannot (2) finally block destruction.
be overridden by sub cleans up all the
class. resources used in try
(3) final class cannot be block
inherited.
Let's consider the following example where we declare final variable age. Once declared it cannot
be modified.
FinalExampleTest.java
46
Unit 3. Basic Concepts of Strings and Exceptions
}
Output:
In the above example, we have declared a variable final. Similarly, we can declare the methods
and classes final using the final keyword.
Let's see the below example where the Java code throws an exception and the catch block handles
that exception. Later the finally block is executed after the try-catch block. Further, the rest of the
code is also executed normally.
FinallyExample.java
Output:
47
Unit 3. Basic Concepts of Strings and Exceptions
FinalizeExample.java
Output:
48
Unit 4. Threads and Packages
A Thread is a very light-weighted process, or we can say the smallest part of the process that allows a
program to operate more efficiently by running multiple tasks simultaneously.
In order to perform complicated tasks in the background, we used the Thread concept in Java. All the tasks
are executed without affecting the main program. In a program or process, all the threads have their own
separate path for execution, so each thread of a process is independent.
Another benefit of using thread is that if a thread gets an exception or an error at the time of its execution, it
doesn't affect the execution of the other threads. All the threads share a common memory and have their own
stack, local variables and program counter. When multiple threads are executed in parallel at the same time, this
process is known as Multithreading.
o Feature through which we can perform multiple activities within a single process.
o Lightweight process.
o Series of executed statements.
o Nested sequence of method calls.
1
Unit 4. Threads and Packages
Process Thread
Processes are independent of each other and Threads are interdependent and share memory.
hence don't share a memory or other resources.
Each process is treated as a new process bythe The operating system takes all the user-level threadsas a
operating system. single process.
If one process gets blocked by the operating If any user-level thread gets blocked, all of its peer
system, then the other process can continue the threads also get blocked because OS takes all of them as
execution. a single process.
Context switching between two processes Context switching between the threads is fastbecause
takes much time as they are heavy compared to they are very lightweight.
thread.
The data segment and code segment ofeach Threads share data segment and code segment with their
process are independent of the other. peer threads; hence are the same for other threads also.
The operating system takes more time to Threads can be terminated in very little time.
terminate a process.
New process creation is more time takingas A thread needs less time for creation.
each new process takes all the resources.
When an instance of a thread is created and is executed by calling start() method of Threadclass, the
thread goes into runnable state.
When sleep() or wait() method is called by Thread class, the thread enters into non-runnablestate.
From non-runnable state, thread comes back to runnable state and continues execution of statements. When
the thread comes out of run() method, it dies. These state transitions of athread are called Thread life cycle in
Java.
2
Unit 4. Threads and Packages
A thread is a path of execution in a program that enters in any one of the following five statesduring its life
cycle. The five states are as follows:
1. New
2. Runnable
3. Running
4. Blocked (Non-runnable state)
5. Dead
1. New (Newborn State): When we create a thread object using Thread class, thread is bornand is known
to be in Newborn state. That is, when a thread is born, it enters into new state the start() method has not
been called yet on the instance.
In other words, Thread object exists but it cannot execute any statement because it is not anexecution of thread.
Only start() method can be called on a new thread; otherwise,
an IllegalThreadStateException will be thrown.
3
Unit 4. Threads and Packages
2. Runnable state: Runnable state means a thread is ready for execution. When the start() method is
called on a new thread, thread enters into a runnable state.
In runnable state, thread is ready for execution and is waiting for availability of the processor(CPU time).
That is, thread has joined queue (line) of threads that are waiting for execution. If all threads have equal
priority, CPU allocates time slots for thread execution on the basis of first-come, first-serve manner. The
process of allocating time to threads is known as time slicing. A thread can come into runnable state from
running, waiting, or new states.
3. Running state: Running means Processor (CPU) has allocated time slot to thread for its execution.
When thread scheduler selects a thread from the runnable state for execution, it goes into running state.
Look at the above figure.
In running state, processor gives its time to the thread for execution and executes its run method. This is
the state where thread performs its actual functions. A thread can come intorunning state only from
runnable state.
A running thread may give up its control in any one of the following situations and can enterinto the blocked
state.
When sleep() method is invoked on a thread to sleep for specified time period, the threadis out of
queue during this time period. The thread again reenters into the runnable state as soon as this time
period is elapsed.
When a thread is suspended using suspend() method for some time in order to satisfy some
conditions. A suspended thread can be revived by using resume() method.
When wait() method is called on a thread to wait for some time. The thread in wait statecan be run
again using notify() or notifyAll() method.
5. Dead state: A thread dies or moves into dead state automatically when its run() method completes the
execution of statements. That is, a thread is terminated or dead when a threadcomes out of run() method. A
thread can also be dead when the stop() method is called.
During the life cycle of thread in Java, a thread moves from one state to another state in a variety of ways.
This is because in multithreading environment, when multiple threads areexecuting, only one thread can use
CPU at a time.
All other threads live in some other states, either waiting for their turn on CPU or waiting forsatisfying some
conditions. Therefore, a thread is always in any of the five states.
4
Unit 4. Threads and Packages
1. Thread class:
Thread class provide constructors and methods to create and perform operations on a thread.Thread class
5
Unit 4. Threads and Packages
2. Runnable interface:
The Runnable interface should be implemented by any class whose instances are intended tobe executed by a
thread. Runnable interface have only one method named run().
Starting a thread:
The start() method of Thread class is used to start a newly created thread. It performs thefollowing tasks:
thread is running...
6
Unit 4. Threads and Packages
t1.start();
}
}
Output:
thread is running...
If you are not extending the Thread class, your class object would not be treated as a thread object. So you
need to explicitly create the Thread class object. We are passing the object of your class that implements
Runnable so that your class run() method may execute.
3) Using the Thread Class: Thread(String Name)
We can directly use the Thread class to spawn new threads using the constructors definedabove.
th1.start();
String str = th1.getName();
System.out.println(str);
7
Unit 4. Threads and Packages
}
}
Output:
My new thread
Now the thread is running ...
A component of Java that decides which thread to run or execute and which thread to wait is called a thread
scheduler in Java. In Java, a thread is only chosen by a thread scheduler if it is in the runnable state.
However, if there is more than one thread in the runnable state, it is up to the thread scheduler to pick one of
the threads and ignore the other ones.
There are some criteria that decide which thread will execute first. There are two factors for scheduling a
thread i.e. Priority and Time of arrival.
Priority: Priority of each thread lies between 1 to 10. If a thread has a higher priority, it means that thread has
got a better chance of getting picked up by the thread scheduler.
Time of Arrival: Suppose two threads of the same priority enter the runnable state, then priority cannot be
the factor to pick a thread from these two threads. In such a case, arrival time of thread is considered by the
thread scheduler. A thread that arrived first gets the preference over the other threads.
Thread.sleep()
The Java Thread class provides the two variant of the sleep() method. First one accepts only an one
arguments, whereas the other variant accepts two arguments. The method sleep() is being used to halt the
working of a thread for a given amount of time. The time up to which the thread remains in the sleeping state
is known as the sleeping time of the thread. After the sleeping time is over, the thread starts its execution
from where it has left.
The sleep() Method Syntax:
The Thread.sleep() method can be used with any thread. It means any other thread or the main thread can
invoke the sleep() method.
Parameters:
8
Unit 4. Threads and Packages
mls: The time in milliseconds is represented by the parameter mls. The duration for which the thread will
sleep is given by the method sleep().
n: It shows the additional time up to which the programmer or developer wants the thread to be in the
sleeping state. The range of n is from 0 to 999999.
Whenever the Thread.sleep() methods execute, it always halts the execution of the currentthread.
Whenever another thread does interruption while the current thread is already in the sleepmode, then the
InterruptedException is thrown.
If the system that is executing the threads is busy, then the actual sleeping time of the thread is generally
more as compared to the time passed in arguments. However, if the system executing the sleep() method has
less load, then the actual sleeping time of the thread is almostequal to the time passed in the argument.
t1.start();
t2.start();
}
}
Output:
9
Unit 4. Threads and Packages
1
1
2
2
3
3
4
4
As you know well that at a time only one thread is executed. If you sleep a thread for thespecified time,
the thread scheduler picks up another thread and so on.
try
{
for (int j = 0; j < 5; j++)
{
// The main thread sleeps for the 1000 milliseconds, which is 1 sec
// whenever the loop runs
Thread.sleep(1000);
10
Unit 4. Threads and Packages
Output:
0
1
2
3
4
Example of the sleep() Method in Java: When the sleeping time is -ive
Thread.sleep(-100);
No. After starting a thread, it can never be started again. If you does so, an
IllegalThreadStateException is thrown. In such case, thread will run once but for second time, it will throw
exception.
Output:
running
Exception in thread "main" java.lang.IllegalThreadStateException
11
Unit 4. Threads and Packages
running...
12
Unit 4. Threads and Packages
{
Thread.sleep(500);
}
catch(InterruptedException e)
{
System.out.println(e);
}
System.out.println(i);
}
}
public static void main(String args[])
{
TestCallRun2 t1=new TestCallRun2();
TestCallRun2 t2=new TestCallRun2();
t1.run();
t2.run();
}
}
1
2
3
4
1
2
3
As we can see in the above program that there is no context-switching because here t1 and t2 will be treated as
normal object not thread object.
13
Unit 4. Threads and Packages
public final int getPriority(): The java.lang.Thread.getPriority() method returns the priorityof the given
thread.
public final void setPriority(int newPriority): The java.lang.Thread.setPriority() method updates or assign
the priority of the thread to newPriority. The method throws IllegalArgumentException if the value
newPriority goes out of the range, which is 1 (minimum) to 10 (maximum).
Default priority of a thread is 5 (NORM_PRIORITY). The value of MIN_PRIORITY is 1 and the value of
MAX_PRIORITY is 10.
14
Unit 4. Threads and Packages
Thread.currentThread().setPriority(10);
Output:
Note: If there are two threads that have the same priority, then one can not predict which thread will get the
chance to execute first. The execution then is dependent on the thread scheduler'salgorithm (First Come First
Serve, Round-Robin, etc.)
15
Unit 4. Threads and Packages
t2.start();
t3.start();
}
}
Output:
task one
task one
task one
Output:
task one
task one
16
Unit 4. Threads and Packages
FileName: TestMultitasking3.java
Output:
task one
task two
FileName: TestMultitasking4.java
class TestMultitasking4{
public static void main(String args[]){
17
Unit 4. Threads and Packages
Output:
task one
task two
FileName: TestMultitasking5.java
class TestMultitasking5{
public static void main(String args[]){
Runnable r1=new Runnable(){
public void run(){
System.out.println("task one");
}
};
Runnable r2=new Runnable(){
public void run(){
System.out.println("task two");
}
};
18
Unit 4. Threads and Packages
Output:
task one
task two
FileName: OddEvenExample.java
19
Unit 4. Threads and Packages
}
System.out.print(contr + " ");
contr = contr + 1;
notify();
}
}
}
public void displayEvenNumber()
{
synchronized (this)
{
while (contr < NUM)
{
while (contr % 2 == 1)
{
try
{
wait();
}
catch (InterruptedException ex)
{
ex.printStackTrace();
}
}
System.out.print(contr + " ");
contr = contr +1;
notify();
}
}
}
public static void main(String[] argvs)
{
NUM = 20;
OddEvenExample oe = new OddEvenExample();
Thread th1 = new Thread(new Runnable()
{
20
Unit 4. Threads and Packages
Output:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
21
Unit 4. Threads and Packages
Java Package
A java package is a group of similar types of classes, interfaces and sub-packages.
Package in java can be categorized in two form, built-in package and user-defined package.
There are many built-in packages such as java, lang, awt, javax, swing, net, io, util, sql etc.
Here, we will have the detailed learning of creating and using user-defined packages.
1) Java package is used to categorize the classes and interfaces so that they can be easily maintained.
//save as Simple.java
package mypack;
public class Simple{
public static void main(String args[]){
System.out.println("Welcome to package");
}
}
22
Unit 4. Threads and Packages
If you are not using any IDE, you need to follow the syntax given below:
For example
javac -d . Simple.java
The -d switch specifies the destination where to put the generated class file. You can use any directory name
like /home (in case of Linux), d:/abc (in case of windows) etc. If you want to keep the package within the same
directory, you can use . (dot).
You need to use fully qualified name e.g. mypack.Simple etc to run the class.
1. import package.*;
2. import package.classname;
3. fully qualified name.
1) Using packagename.*
If you use package.* then all the classes and interfaces of this package will be accessible but not subpackages.
The import keyword is used to make the classes and interface of another package accessible to the current
package.
23
Unit 4. Threads and Packages
}
//save by B.java
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
Output:Hello
2) Using packagename.classname
If you import package.classname then only declared class of this package will be accessible.
24
Unit 4. Threads and Packages
It is generally used when two packages have same class name e.g. java.util and java.sql packages contain Date
class.
If you import a package, all the classes and interface of that package will be imported excluding the classes and
interfaces of the subpackages. Hence, you need to import the subpackage as well.
Note: Sequence of the program must be package then import then class.
25
Unit 5. Data Structure Implementation and Applet Classes
Linked List
o Linked List can be defined as collection of objects called nodes that arerandomly
stored in the memory.
o A node contains two fields i.e. data stored at that particular address and thepointer
which contains the address of the next node in the memory.
o The last node of the list contains pointer to the null.
The list is not required to be contiguously present in the memory. The node can reside any
where in the memory and linked together to make a list. This achieves optimized utilization
of space.
list size is limited to the memory size and doesn't need to be declared in advance.
Empty node can not be present in the linked list.
We can store values of primitive types or objects in the singly linked list.
Till now, we were using array data structure to organize the group of elements that are to
be stored individually in the memory. However, Array has several advantages and
disadvantages which must be known in order to decide the data structure which will be
used throughout the program.
1. The size of array must be known in advance before using it in the program.
2. Increasing size of the array is a time taking process. It is almost impossible to expand
the size of the array at run time.
3. All the elements in the array need to be contiguously stored in the memory. Inserting
any element in the array needs shifting of all its predecessors.
Linked list is the data structure which can overcome all the limitations of an array.Using linked
list is useful because,
1. It allocates the memory dynamically. All the nodes of linked list are non-
contiguously stored in the memory and linked together with the help of pointers.
2. Sizing is no longer a problem since we do not need to define its size at the time of
declaration. List grows as per the program's demand and limited to the available
memory space.
Unit 5. Data Structure Implementation and Applet Classes
A singly linked list is a unidirectional linked list. So, you can only traverse it inone direction,
i.e., from head node to tail node.
A doubly linked list is a bi-directional linked list. So, you can traverse it in bothdirections.
Unlike singly linked lists, its nodes contain one extra pointer called the previous pointer.
This pointer points to the previous node.
A circular Linked list is a unidirectional linked list. So, you can traverse it in only one
direction. But this type of linked list has its last node pointing to the head node. So while
traversing, you need to be careful and stop traversing whenyou revisit the head node.
A circular doubly linked list is a mixture of a doubly linked list and a circular linked list. Like the
doubly linked list, it has an extra pointer called the previouspointer, and similar to the circular
linked list, its last node points at the head node. This type of linked list is the bi-directional list. So,
you can traverse it in both directions.
Singly linked list can be defined as the collection of ordered set of elements. The number of
elements may vary according to need of the program. A node in the singly linked list consist
of two parts: data part and link part. Data part of the node stores actual information that is to
be represented by the node while the link part of the node stores the address of its
immediate successor.
One way chain or singly linked list can be traversed only in one direction. In other words, we
can say that each node contains only next pointer, therefore we can nottraverse the list in the
reverse direction.
Consider an example where the marks obtained by the student in three subjects are stored
in a linked list as shown in the figure.
In the above figure, the arrow represents the links. The data part of every node contains the
marks obtained by the student in the different subject. The last node in the list is identified
by the null pointer which is present in the address part of the last node. We can have as
many elements we require, in the data part of the list.
Unit 5. Data Structure Implementation and Applet Classes
The insertion into a singly linked list can be performed at different positions. Based on the
position of the new node being inserted, the insertion is categorized into the following
categories.
SN Operation Description
1 Insertion at It involves inserting any element at the front of the list.We just
beginning need to a few link adjustments to make the new node as the
head of the list.
2 Insertion at endof It involves insertion at the last of the linked list. The new
the list node can be inserted as the only node in the list or it can be
inserted as the last one. Different logics are implemented in
each scenario.
3 Insertion after It involves insertion after the specified node of the linked list.
specified node We need to skip the desired number of nodes in order to
reach the node after which the new node will be inserted. .
The Deletion of a node from a singly linked list can be performed at different positions.
Based on the position of the node being deleted, the operation is categorized into the
following categories.
SN Operation Description
2 Deletion at the It involves deleting the last node of the list. The list can
end of the list either be empty or full. Different logic is implemented for
the different scenarios.
3 Deletion after It involves deleting the node after the specified node in the
specified node list. we need to skip the desired number of nodes to reach
the node after which the node will be deleted. This requires
traversing through the list.
Unit 5. Data Structure Implementation and Applet Classes
We traverse a circular singly linked list until we reach the same node where we started. The
circular singly liked list has no beginning and no ending. There is no null value present in the
next part of any of the nodes.
Circular linked list are mostly used in task maintenance in operating systems. There are
many examples where circular linked list are being used in computer science including
browser surfing where a record of pages visited in the past by the user, is maintained in the
form of circular linked lists and can be accessed again on clicking the previous button.
In the following image, memory representation of a circular linked list containing marks of a
student in 4 subjects. However, the image shows a glimpse of how the circular list is being
stored in the memory. The start or head of the list is pointingto the element with the index 1
and containing 13 marks in the data part and 4 inthe next part. Which means that it is linked
with the node that is being stored at 4th index of the list.
Unit 5. Data Structure Implementation and Applet Classes
However, due to the fact that we are considering circular linked list in the memory therefore
the last node of the list contains the address of the first node of the list.
We can also have more than one number of linked list in the memory with the different
start pointers pointing to the different start nodes in the list. The last node is identified by
its next part which contains the address of the start node of the list. We must be able to
identify the last node of any linked list so that we can
find out the number of iterations which need to be performed while traversing thelist.
SN Operation Description
2 Insertion at the end Adding a node into circular singly linked list atthe end.
Unit 5. Data Structure Implementation and Applet Classes
SN Operation Description
1 Deletion at Removing the node from circular singly linked list atthe
beginning beginning.
2 Deletion at the Removing the node from circular singly linked list atthe end.
end
3 Searching Compare each element of the node with the given item and
return the location at which the item is present in the list
otherwise return null.
Array elements store in a contiguous Linked list elements can be stored anywherein
memory location. the memory or randomly stored.
Array works with a static memory. Here The Linked list works with dynamic memory.
static memory means that the memorysize is Here, dynamic memory means that the
fixed and cannot be changed at therun time. memory size can be changed at the run time
according to our requirements.
Array elements are independent of each Linked list elements are dependent on each
other. other. As each node contains the address ofthe
next node so to access the next node, we need
to access its previous node.
Array takes more time while performing Linked list takes less time while performingany
any operation like insertion, deletion, etc. operation like insertion, deletion, etc.
Accessing any element in an array is faster as Accessing an element in a linked list is slower
the element in an array can be directly as it starts traversing from the first element of
accessed through the index. the linked list.
Memory utilization is inefficient in the array. Memory utilization is efficient in the case of a
For example, if the size of the array is 6, and linked list as the memory can be allocated or
array consists of 3 elements only then the deallocated at the run time according to our
rest of the space will be unused. requirement.
Java Applet
Applet is a special type of program that is embedded in the webpage to generate the dynamic
content. It runs inside the browser and works at client side.
Advantage of Applet
Drawback of Applet
Hierarchy of Applet
As displayed in the above diagram, Applet class extends Panel. Panel class extends Container which is the
subclass of Component.
1. Applet is initialized.
2. Applet is started.
3. Applet is painted.
4. Applet is stopped.
5. Applet is destroyed.
The java.applet.Applet class 4 life cycle methods and java.awt.Component class provides 1 life
cycle methods for an applet.
java.applet.Applet class
For creating any applet java.applet.Applet class must be inherited. It provides 4 life cycle
methods of applet.
1. public void init(): is used to initialized the Applet. It is invoked only once.
2. public void start(): is invoked after the init() method or browser is maximized. It is used
to start the Applet.
3. public void stop(): is used to stop the Applet. It is invoked when Applet is stop or
browser is minimized.
4. public void destroy(): is used to destroy the Applet. It is invoked only once.
java.awt.Component class
1. public void paint(Graphics g): is used to paint the Applet. It provides Graphics class
object that can be used for drawing oval, rectangle, arc etc.
1. By html file.
2. By appletViewer tool (for testing purpose).
To execute the applet by html file, create an applet and compile it. After that create an html file
and place the applet code in html file. Now click the html file.
//First.java
import java.applet.Applet;
import java.awt.Graphics;
public class First extends Applet{
public void paint(Graphics g){
g.drawString("welcome",150,150);
}
}
Note: class must be public because its object is created by Java Plugin software that resides on
the browser.
myapplet.html
<html>
<body>
<applet code="First.class" width="300" height="300">
</applet>
</body>
</html>
c:\>javac First.java
c:\>appletviewer First.java
c:\>appletviewer myapplet.html
g.drawString("Welcome",50, 50);
g.drawLine(20,30,20,300);
g.drawRect(70,100,30,30);
g.fillRect(170,100,30,30);
g.drawOval(70,200,30,30);
g.setColor(Color.pink);
g.fillOval(170,200,30,30);
g.drawArc(90,150,30,30,30,270);
g.fillArc(270,150,30,30,0,180);
}
}
myapplet.html
<html>
<body>
<applet code="GraphicsDemo.class" width="300" height="300">
</applet>
</body>
</html>
myapplet.html
<html>
<body>
<applet code="DisplayImage.class" width="300" height="300">
</applet>
</body>
</html>
Parameter in Applet
We can get any information from the HTML file as a parameter. For this purpose, Applet class
provides a method named getParameter(). Syntax:
g.drawString(str,50, 50);
}
}
myapplet.html
<html>
<body>
<applet code="UseParam.class" width="300" height="300">
<param name="msg" value="Welcome to applet">
</applet>
</body>
</html>