Java Full Notes
Java Full Notes
Application
According to Sun, 3 billion devices run Java. There are many devices where
Java is currently used. Some of them are as follows:
There are mainly 4 types of applications that can be created using Java
programming:
1) Standalone 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
4) Mobile Application
4) JavaFX
Java has become a popular and useful programming language because of its
excellent features, which play a very important role in contributing to the
popularity of this language. The Java features are called “Java BuzzWords”.
Sun MicroSystems officially describes Java with the following list of features:
Apart from the removal of these confusing and ambiguous concepts, there is a
provision of Automatic Garbage Collection, in which there is no need to remove
the unreferenced objects explicitly.
Java is familiar because:
It has a base of familiar languages like C and C++ and contains many
features of these languages.
It removes the drawbacks, complexities and confusing elements of C/C++.
So if you have good knowledge of C/C++, you will find Java familiar and easy
to understand.
Java Virtual Machine (JVM) then executes this bytecode which is executable on
many operating systems and is portable.
Platform Independent
The Java compiler never converts the source code to machine code like that of
the C/C++ compiler.
Instead, it converts the source code into an intermediate code called the byte
code and this byte code is further translated to machine-dependent form
by another layer of software called JVM (Java Virtual Machine).
Therefore, JVM can execute bytecode on any platform or OS on which it is
present, regardless of the fact that on which machine the bytecode was
generated.
This is where the “Write Once, run anywhere” (WORA) slogan for Java comes
in, which means that we can develop applications on one environment (OS)
and run on any other environment without doing any modification in the
code.
Portable
Java is “portable” refers to the SE (Standard Edition) version. The portability
actually comes from architecture-neutrality.
In C/C++, the source code may run slightly differently on different
hardware platforms, but Java simplifies it. You can run Java bytecode on any
hardware that has a compliant JVM which can convert the bytecode according
to that particular machine.
In Java, the size of the primitive data types is machine-independent, which
were dependent in the case of C/C++. So, these provisions make Java programs
portable among different platforms such as Windows, Unix, Solaris, and Mac.
Moreover, any changes and updates made in Operating Systems, Processors
and System resources will not enforce any changes in Java programs.
Architectural Neutral
It is based on the ‘Write-once-run-anywhere’ (WORA) or ‘Write-once-run-
everywhere’ (WORE) approach.
Byte-code is not dependent on any machine architecture and Java Virtual
Machine (JVM) can easily translate bytecode into a machine-specific code.
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.
Object-Oriented
Java strongly supports the concepts of Object-Oriented Programming due to
which it is called a pure object-oriented language.
Java supports major Object-Oriented programming features like Encapsulation,
Abstraction, and Inheritance.
Almost everything in Java is an object. All programs and data live within objects
and classes. ‘Objects’ model Java rather than the ‘processes’. Java comes with
an extensible set of classes organized in packages.
For example, we cannot develop an executable program in Java without making
use of the class. This indicates that Java very strictly applies the principle of
Encapsulation.
Robust
Java is robust as it is capable of handling run-time errors, supports automatic
garbage collection and exception handling, and avoids explicit pointer concept.
Java has a strong memory management system. It helps in eliminating errors as
it checks the code during both compile and runtime.
Java is garbage-collected language – JVM automatically deallocates the memory
blocks and programmers do not have to worry about deleting the memory
manually as in case of C/C++.
Java also provides the concept of exception handling which identifies runtime
errors and eliminates them.
In Java, any runtime error encountered by the JVM is never passed directly to
the underlying system rather immediately terminates the program stopping it
from causing any harm to the underlying system.
Secure
Security is an important issue for any programming language as there is a threat
of malicious activities and viruses. Java supports access modifiers to check
memory access and also ensures that no viruses enter an applet.
Java is a more secure language as compared to C/C++, as it does not allow a
programmer to explicitly create pointers. Thus in Java, we can not gain access
to a particular variable if we do not initialize it properly.
Programs run in a virtual machine sandbox – A separate environment that
allows users to execute their applications without affecting the underlying
system.
It has a bytecode verifier that checks the code fragments for any illegal code that
violates the access right.
Distributed
In Java, we can split a program into many parts and store these parts on
different computers. A Java programmer sitting on a machine can access
another program running on the other machine.
Java comes with an extensive library of classes for interacting, using TCP/IP
protocols such as HTTP and FTP, which makes creating network connections
much easier than in C/C++.
Java is interactive because its code supports effective CUI (Character User
Interface) and GUI (Graphical User Interface) programs. It greatly improves
the interactive performance of graphical applications.
High Performance
The performance of Java is impressive for an interpreted language because of its
intermediate bytecode.
Java provides high performance with the use of “JIT – Just In Time compiler”,
in which the compiler compiles the code on-demand basis, that is, it
compiles only that method which is being called. This saves time and makes
it more efficient.
Java architecture is also designed in such a way that it reduces overheads during
runtime. The inclusion of multithreading enhances the overall execution speed
of Java programs.
Bytecodes generated by the Java compiler are highly optimized, so Java
Virtual Machine can execute them much faster.
Dynamic and Extensible
Java is dynamic and extensible means with the help of OOPs, we can add classes
and add new methods to classes, creating new classes through subclasses. This
makes it easier for us to expand our own classes and even modify them.
Java gives the facility of dynamically linking new class libraries, methods, and
objects. It is highly dynamic as it can adapt to its evolving environment.
Java even supports functions written in other languages such as C and C++ to
be written in Java programs. These functions are called “native methods”. These
methods are dynamically linked at runtime.
JDK, JRE and JVM
JVM (Java Virtual Machine) is a very important part of both JDK and JRE
because it is contained or inbuilt in both. Whatever Java program you run
using JRE or JDK goes into JVM and JVM is responsible for executing the
java program line by line, hence it is also known as an interpreter.
Basic Structure of a Java Program
A Java program consists of different sections. Some of them are mandatory but
some are optional. The optional section can be excluded from the program
depending upon the requirements of the programmer.
Documentation Section
It is used to improve the readability of the program. It consists of comments in
Java which include basic information such as the method’s usage or
functionality to make it easier for the programmer to understand it while
reviewing or debugging the code. A Java comment is not necessarily limited to
a confined space, it can appear anywhere in the code.
The compiler ignores these comments during the time of execution and is solely
meant for improving the readability of the Java program.
Single-line Comment
Multi-line Comment
Documentation Comment
Multi-line Comment:
Java programmer can use C/C++ comment style that begins with delimiter /*
and ends with */. All the text written between the delimiter is ignored by the
compiler. This style of comments can be used on part of a line, a whole line or
more commonly to define multi-line comment. For example.
/* Calculate sum of
two numbers and
it is a multiline comment */
Documentation comments:
This comment style is new in Java. Such comments begin with delimiter /**
and end with */. The compiler also ignores this type of comments just like it
ignores comments that use / * and */. The main purpose of this type of comment
is to automatically generate program documentation. The javadoc tool
reads these comments and uses them to prepare your program's
documentation in HTML format. For example.
Package Statement
A package is a collection of classes, interfaces and sub-packages. A sub
package contains collection of classes, interfaces and sub-sub packages etc.
package institute;
This statement declares that all classes and interfaces defined in this source file
are part of the institute package. Only one package declaration can appear in
the source file.
Import statements
Java contains many predefined classes that are stored into packages. In order
to refer these standard predefined classes in your program, you need to use
fully qualified name (i.e. Packagename.className). But this is a very tedious
task as one need to retype the package path name along with the classname. So
a better alternative is to use an import statement.
An import statement is used for referring classes that are declared in other
packages. The import statement is written after a package statement but before
any class definition. You can import a specific class or all the classes of the
package.
Example If you want to import Date class of java.util package using import
statement then write.
import java.util.Date;
This statement allows the programmer to use the simple classname Date rather
than fully qualified classname java.util.Date in the code.
Unlike package statement, you can specify more than one import statement in
your program.
Example
interface stack
{
void push(int item); // Insert item into stack
int pop(); // Delete an item from stack
}
Class Definition:
Java program may contain multiple class definition. Classes are primary
feature of Java program. The classes are used to map real world problems.
class Addition
{
void add(String args[])
{
int a=2, b=3, c;
c=a+b;
System.out.println(c);
}
}
Identifiers are the basic building blocks of a Java program. We use identifiers
to give names to the different parts of the program such as variables, objects,
classes, methods, arrays, etc.
Keywords are the reserved words in Java that convey a different meaning to
the compiler. We cannot use the keywords as normal identifier names but only
for a special purpose. In Java, there are 51 keywords.
Literals in Java
A literal in Java refers to the constants or the data items that have fixed values.
There are different types of Literals in Java. They are Numeric, Floating,
character, strings, boolean, null. They are also divided further into
subcategories. Let’s discuss them separately:
a. Numeric Literals
i. Integer Literals: Integer literals are the whole numbers without fractional
part and they are the number of base 10. For example, 34, 76, 9896, etc.
ii. Binary Literals: Binary literals are the number with base 2. For example,
0101, 0011, 011, etc.
iii. Octal Literals: Octal literals are the numbers with base 8. They must not
contain 8 and 9. For example, 77, 565, 450, etc.
iv. Hexadecimal Literals: Hexadecimal literals are the numbers with base 16.
They can contain the digits from 0 to 9 and alphabets from A to F. For
Example, AC87, 1F7B, 24D6, etc.
b. Floating-point Literals
i. Single quoted character: The single-quoted character encloses all the uni-
length characters within single quotes. Example- ‘z’,’j’, ‘A’, etc.
ii. Escape Sequences: These are the characters that come after backslash and
perform a specific function when printed on the screen such as a tab, creating
a new line, etc. Example: ’\n’, ‘\b’, ‘\t’, etc.
iii. Unicode Representation: We can represent it by specifying the concerned
Unicode value of the character after ‘\u’. For Example- ‘\u0067’, etc.
d. Boolean literals
A boolean literal has only two values: true and false. These values are formed
from ASCII letters. Example: true, false.
e. String Literals
The String-literals are the multiple character constants enclosed within double
quotes “ ”. For example, “java tutorial”, “HelloWorld”, “\abc”, etc.
Java Is a Strongly Typed Language: It is important to state at the outset that
Java is a strongly typed language. Indeed, part of Java's safety and robustness
comes from this fact.
First, every variable has a type, every expression has a type, and every type
is strictly defined. Second, all assignments, whether explicit or via parameter
passing in method calls, are checked for type compatibility. There are no
automatic coercions or conversions of conflicting types as in some languages.
The Java compiler checks all expressions and parameters to ensure that the
types are compatible. Any type mismatches are errors that must be corrected
before the compiler will finish compiling the class.
Data types specify the different sizes and values that can be stored in the
variable.
• There are two types of data types in Java:
Primitive data types: The primitive data types include boolean,
char, byte, short, int, long, float and double.
Non-primitive data types: The non-primitive data types
include Classes, Interfaces, and Arrays.
Primitive Data Types
1. Data types are predefined by the Java language.
2. Predefined data types are Reserved keyword so we cannot use them as
variable name inside program/application
3. Primitive values do not share state with other primitive values.
4. Total Number of Primitive Data Types in Java Programming is 8
5. All Primitive Data Types have respective Wrapper Classes i.e Integer is
wrapper class for primitive type int
Data Type and Other Details
–9,223,372,036,854,775,808 to
long 64
9,223,372,036,854,775,807
Example:
byte a = 10, byte b = -20
short s = 10000, short r = -5000
int a = 100000, int b = -200000
long a = 100000L, long b = -200000L
Float Data Type :
1. Floating Data Type is used to store float value.
2. Floating Data Type is Primitive Data Type in Java Programming Language.
3. Floating Data Type have respective Wrapper Class – “Float or Double“.
4. float Data Type Can store 2 types of Values:
1. Float
2. Double
float:
It occupy 4 bytes in memory.
Values are represented with approximately 7 decimal digits accuracy
Double:
It occupy 8 bytes in memory.
Values are represented with approximately 17 decimal digits accuracy.
class CharDemo2
{
public static void main(String args[])
{
char ch1;
ch1 = 'P';
System.out.println("ch1 contains " + ch1);
ch1++; // increment ch1
System.out.println("ch1 is now " + ch1);
}
}
Output :
ch1 contains P
ch1 is now Q
These are built-in data types These are created by the users
A variable in Java is a container that holds the value during the execution of Java
program. In other words, Variable is the name of the memory location reserved for storing
value. Each variable in Java has a specific type that determines size of the memory.
The size of the memory reserved depends on the data type.
From the image, it can be easily perceived that while declaring a variable we need to take
care of two things that while de
In this way, a name can only be given to a memory location. It can be assigned values in
two ways:
Variable Initialization
Assigning value by taking input
1. Local Variables
2. Instance Variables
3. Static Variables
1. Local Variables
Arithmetic Operqators
Relational (or) Comparision Operators
Logical Operators
Assignment Operators
Bitwise Operators
Conditional Operators
Arithmetic Operators
In java, arithmetic operators are used to performing basic mathematical operations
like addition, subtraction, multiplication, division, modulus, increment, decrement,
etc.,
+ Addition 10 + 5 = 15
- Subtraction 10 - 5 = 5
* Multiplication 10 * 5 = 50
/ Division 10 / 5 = 2
++ Increment a++
Example
result = a + b;
System.out.println("Addition : " + a + " + " + b + " = " + result);
result = a - b;
System.out.println("Subtraction : " + a + " - " + b + " = " + result);
result = a * b;
System.out.println("Multiplucation : " + a + " * " + b + " = " + result);
result = b / a;
System.out.println("Division : " + b + " / " + a + " = " + result);
result = b % a;
System.out.println("Modulus : " + b + " % " + a + " = " + result);
result = ++a;
System.out.println("Pre-increment : ++a = " + result);
result = b--;
System.out.println("Post-decrement : b-- = " + result);
}
}
< Returns TRUE if the first value is smaller than second 10 < 5 is
value otherwise returns FALSE FALSE
> Returns TRUE if the first value is larger than second 10 > 5 is
value otherwise returns FALSE TRUE
Operator Meaning Example
<= Returns TRUE if the first value is smaller than or equal 10 <= 5 is
to second value otherwise returns FALSE FALSE
>= Returns TRUE if the first value is larger than or equal 10 >= 5 is
to second value otherwise returns FALSE TRUE
Example
a = 10<5;
System.out.println("10 < 5 is " + a);
a = 10>5;
System.out.println("10 > 5 is " + a);
a = 10<=5;
System.out.println("10 <= 5 is " + a);
a = 10>=5;
System.out.println("10 >= 5 is " + a);
a = 10==5;
System.out.println("10 == 5 is " + a);
a = 10!=5;
System.out.println("10 != 5 is " + a);
}
}
Logical Operators
The logical operators are the symbols that are used to combine multiple
conditions into one condition. The following table provides information
about logical operators.
& Logical AND - Returns TRUE if all conditions are TRUE false & true
otherwise returns FALSE => false
^ Logical XOR - Returns FALSE if all conditions are same true ^ true =>
otherwise returns TRUE false
! Logical NOT - Returns TRUE if condition is FLASE and !false => true
returns FALSE if it is TRUE
&& short-circuit AND - Similar to Logical AND (&), but false & true
once a decision is finalized it does not evaluate => false
remianing.
Example
+= Add both left and right-hand side values and store the result A += 10
into left-hand side variable
|= Logical OR assignment -
a += b;
System.out.println("a = " + a);
a -= b;
System.out.println("a = " + a);
a *= b;
System.out.println("a = " + a);
a /= b;
System.out.println("a = " + a);
a %= b;
System.out.println("a = " + a);
x |= (a>b);
System.out.println("x = " + x);
x &= (a>b);
System.out.println("x = " + x);
}
}
Bitwise Operators
The bitwise operators are used to perform bit-level operations in the java
programming language. When we use the bitwise operators, the operations
are performed based on binary values. The following table describes all the
bitwise operators in the java programming language.
Let us consider two variables A and B as A = 25 (11001) and B = 20 (10100).
Operator Meaning Example
& the result of Bitwise AND is 1 if all the bits are 1 A&B
otherwise it is 0 ⇒ 16 (10000)
^ the result of Bitwise XOR is 0 if all the bits are same A^B
otherwise it is 1 ⇒ 13 (01101)
<< the Bitwise left shift operator shifts all the bits to the left A << 2
by the specified number of positions ⇒ 100
(1100100)
>> the Bitwise right shift operator shifts all the bits to the A >> 2
right by the specified number of positions ⇒ 6 (00110)
Example
Conditional Operators
The conditional operator is also called a ternary operator because it
requires three operands. This operator is used for decision making. In this
operator, first, we verify a condition, then we perform one operation out of
the two operations based on the condition result. If the condition is TRUE
the first option is performed, if the condition is FALSE the second option is
performed. The conditional operator is used with the following syntax.
Syntax
Example
c = (a>b)? a : b;
}
Control Statements in Java
Conditional control statements in Java. Control statements are also called control
structures or control constructs.
A block is a specific kind of statement that encloses a group of statements between braces.
It is represented by an opening brace and closing brace.
The opening brace represents the beginning of block and closing brace specifies the end of
a block. It is used to define the scope of variables and support nesting.
A program that breaks the sequential flow and jumps to another part of the code is called
branching in java. When branching is based on a specific condition, then it is called
conditional branching or conditional statements in Java.
Since the flow of execution is transferred on a particular condition from one part of code to
another part, it is also called conditional execution.
if else statement
do while statement
while loop
for loop
for-each loop
switch statement
The conditional control flow statement uses the boolean expression for conditional tests. If
there is only a single statement in the conditional control flow statement, braces are
optional.
Braces are mandatory when there is more than one statement within conditional control
flow statement. All conditional control flow statements will be explained in more detail in
the further tutorials.
When the flow of execution jumps to another part of code without carrying out any
conditional test, it is called unconditional statements or unconditional execution in Java.
Here,
a. Condition is a boolean expression that returns a boolean value either true or false.
b. Condition can also include any relational operators to form Boolean expressions that
must be enclosed within parentheses.
c. If the condition is true, then the statement is executed. If the condition is false, then the
statement is bypassed or skipped.
d. If the block of if statement contains more than one statement, must enclose these
statements within a pair of braces ({ }).
Example:
import java.util.Scanner;
class IfStatementTest
{
if((num % 5) == 0)
{
System.out.println("We are inside the if-block!");
System.out.println("Given number is divisible by 5!!");
}
If else in Java
An if else in Java is a two-way conditional statement that decides the execution path
based on whether the condition is true or false.
In other words, if-else statement is used to perform a specific action (task) depending on
whether a specified condition is true or false.
A one-way if statement executes a statement if and only if the specified condition is true. If
the condition is false, nothing will be done.
But, suppose we want to take alternative actions when the specified condition is false. In
this case, we will use a two-way if-else statement.
Here, each statement represents a single statement or a block of statements enclosed in
curly braces ( { }). The condition is any boolean expression that returns a boolean value.
The else clause is an optional part. It means that we can omit else clause part if not
required. You can follow this convention in all control statements in Java.
Example
import java.util.Scanner;
class IfElseStatementTest
{
if((num % 2) == 0)
{
System.out.println("We are inside the true-block!");
System.out.println("Given number is EVEN number!!");
}
else
{
System.out.println("We are inside the false-block!");
System.out.println("Given number is ODD number!!");
}
If an “if statement” is declared inside another if, or if-else statement, it is called nested if
statement in Java. The inner if statement can also have another if statement.
In fact, there is no limit to the depth of the nesting. Nested if statements are very common
in java programming.
The general syntax:
Syntax
if(condition_1)
{
if(condition_2)
{
inner if-block of statements;
}
}
Example:
import java.util.Scanner;
class NestedIfStatementTest
{
}
}
if-else if ladder in Java is a multi-way decision structure that is used to decide among three
or more actions.
The general syntax:
if(condition)
statement1;
else if(condition)
statement2;
else if(condition)
statement3;
...
else
statement4;
In the above syntax, there can be multiple else if clauses and the last else clause is
optional.
1. The first specified condition evaluates to true. If the condition is true, statement1 will
execute and the rest part of else if ladder will bypass.
2. If the specified condition is false, the second if condition evaluates to true. If the second
condition is true, statement2 will execute, and the rest part of the ladder will bypass.
3. If the second condition is false, the third condition and the rest of the conditions (if
required) are evaluated (or tested) until a condition is met or all of the conditions prove to
be false.
4. If all of the conditions are false, the final else statement (i.e. statement4) associated with
the top if statement will be executed.
5. The statement associated with final else acts as a default condition. That is, if all of the
above conditional tests fail, the statement associated with the last else will be executed.
If there is no final else statement and none of the conditions is true, no action will take
place.
import java.util.Scanner;
public class Test {
public static void main(String[] args)
{
// Create an object of Scanner class to take the input.
Scanner sc = new Scanner(System.in);
In other words, a switch statement executes statements based on the value of a variable or
an expression, against a list of case values.
Example:
import java.util.Scanner;
class SwitchStatementTest
{
switch( value )
{
case 0: System.out.println("ZERO") ; break ;
case 1: System.out.println("ONE") ; break ;
case 2: System.out.println("TWO") ; break ;
case 3: System.out.println("THREE") ; break ;
case 4: System.out.println("FOUR") ; break ;
case 5: System.out.println("FIVE") ; break ;
case 6: System.out.println("SIX") ; break ;
case 7: System.out.println("SEVEN") ; break ;
case 8: System.out.println("EIGHT") ; break ;
case 9: System.out.println("NINE") ; break ;
default: System.out.println("Not a Digit") ;
}
Loops in Java are the processes that execute a block of statements repeatedly until a
termination condition is met.
In simple words, a loop in java is used to execute the same block of statements repeatedly.
Each execution of the loop is called iteration in java.
The block of statements can be executed any number of times, from zero to infinite number
depending on the requirement.
1. while loop
2. do-while loop
3. for loop
4. foreach loop
While Loop in Java
The while loop in Java is the most fundamental loop statement that repeats a statement
or series of statements as long as the specified conditional expression evaluates to true.
Java while loop is the simplest of all the looping structures. It is an entry-controlled loop
statement.
In the entry-controlled loop, the test condition evaluates first. If the specified condition is
true, then the body of loop executes.
If the conditional expression does not satisfy, then the body of loop will not execute.
Example:
class WhileTest
{
A do-while loop in Java is a variant form of while loop. It is the same as a while loop,
except that it executes the body of the loop first and then evaluates the loop continuation
condition.
In the while loop statement, the test condition evaluates first before the loop body executes.
If the condition is initially false, the body of loop will not execute at all.
However, sometimes, it might need to execute the body of a loop at least once before the
test performs. We can handle such situations with the help of do-while loop in Java.
The do-while loop always executes its body at least once before the test evaluates because
its test conditional expression is at the bottom of the loop.
Example:
class DoWhileTest
{
public static void main(String[] args)
{
int num = 1;
do
{
System.out.println(num);
num++;
}while(num <= 10);
The for loop in Java is an entry-controlled loop structure that executes a set of statements
a fixed number of times.
The for statement provides a more concise syntax for creating loops. It executes a block of
statements as long as the condition is true.
In for-statement, the execution begins with the initialization statement. After the
initialization statement, it executes Condition. If the condition is evaluated to true, then
the block of statements executed otherwise it terminates the for-statement. After the block
of statements execution, the modification statement gets executed, followed by condition
again.
Example:
class ForTest
{
public static void main(String[] args)
{
for(int i = 0; i < 10; i++) {
System.out.println("i = " + i);
}
System.out.println("Statement after for!");
}
}
The for each loop in Java (also referred to as enhanced for loop) is an extended feature of
Java language that was introduced with the J2SE 5.0 release.
This feature is specially designed to retrieve elements of the array efficiently rather than
using array indexes.
Java for-each loop can also be used to retrieve elements of a collection. A collection
represents a group of elements as integer values, strings, or objects.
Enhanced for loop repeatedly executes a group of statements for each element of the
collection. It can execute as many times as a number of elements in the collection.
class ForEachTest {
for(int i : arrayList) {
System.out.println("i = " + i);
}
}
Nested For Loop in Java
Nested for loop in Java means one for statement inside another for statement. In other
words, a for loop nested inside another for loop is called nested for loops.
A nested for loops consists of an outer for loop and one or more inner for loops. Each time
the outer for loop repeats, the inner for loop re-enters and starts a new execution.
That is, each time the control will enter inside the inner for loop when the outer for loop
repeats.
Flowchart
Example:
class Tables
{
public static void main(String[] args)
{
System.out.println("Displaying Tables: ");
// Outer for loop.
for(int i = 1; i <= 3; i++)
{
// Inner for loop.
for(int j = 1; j <= 10; j++)
{
System.out.println(i+ " * " +j+" = "+ (i*j));
}
System.out.println(" ");
}
}
}
break statement
continue statement
labelled break and continue statements
return statement
The floowing picture depictes the execution flow of the break statement.
Example:
for(int i : list) {
if(i == 30)
break;
System.out.println(i);
}
for(int i : list) {
if(i == 30)
continue;
System.out.println(i);
}
import java.util.Scanner;
public class JavaLabelledStatement {
public static void main(String args[]) {
In java, the return statement used with both methods with and without return type. In the
case of a method with the return type, the return statement is mandatory, and it is
optional for a method without return type.
When a return statement used with a return type, it carries a value of return type. But,
when it is used without a return type, it does not carry any value. Instead, simply transfers
the execution control.
Eaxmple:
import java.util.Scanner;
public class JavaReturnStatementExample {
int value;
int readValue() {
Scanner read = new Scanner(System.in);
System.out.print("Enter any number: ");
return this.value=read.nextInt();
}
obj.showValue(obj.readValue());
}
}
Scanner Class in Java
In Java, Scanner is a class in java.util package used for obtaining the input
of the primitive types like int, double, etc. and strings. Using the
Scanner class in Java is the easiest way to read input in a Java program,
though not very efficient if you want an input method for scenarios where
time is a constraint like in competitive programming.
Java Scanner Input Types
Scanner class helps to take the standard input stream in Java. So, we need
some methods to extract data from the stream. Methods used for extracting
data are mentioned below:
Method Description
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.
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.
arrayRefVar=new datatype[size];
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]);
}
}
We can declare, instantiate and initialize the java array together by:
We can also print the Java array using for-each loop. The Java for-each
loop prints the array elements one by one. It holds an array element in a
variable, then executes the body of the loop.
for(data_type variable:array)
{
//body of the loop
}
Example:
//Java Program to print the array elements using for-each loop
class Testarray1
{
public static void main(String args[])
{
int arr[]={33,3,4,5};
//printing array using for-each loop
for(int i:arr)
System.out.println(i);
}
}
Example:
public class TestAnonymousArray
{
//creating a method which receives an array as a parameter
static void printArray(int arr[])
{
for(int i=0;i<arr.length;i++)
System.out.println(arr[i]);
}
In such case, data is stored in row and column based index (also known as
matrix form).
o Fields
o Methods
o Constructors
o Blocks
o Nested class and interface
class <class_name>
{
field;
method;
}
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
Advantage of Method
o Code Reusability
o Code Optimization
new keyword in Java
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.
class Student
{
int id;//field or data member or instance variable
String name;
public static void main(String args[])
{
//Creating an object or instance
Student s1=new Student();//creating an object of Student
System.out.println(s1.id);
System.out.println(s1.name);
}
}
Output:
0
null
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.
class Student
{
int id;
String name;
}
class TestStudent1
{
public static void main(String args[])
{
Student s1=new Student();
System.out.println(s1.id);
System.out.println(s1.name);
}
}
Output:
0
null
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.
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
class Student
{
int id;
String name;
}
class TestStudent3{
public static void main(String args[]){
//Creating objects
Student s1=new Student();
Student s2=new Student();
//Initializing objects
s1.id=101;
s1.name="Sonoo";
s2.id=102;
s2.name="Amit";
//Printing data
System.out.println(s1.id+" "+s1.name);
System.out.println(s2.id+" "+s2.name);
}
}
Output:
101 Sonoo
102 Amit
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.
class Student
{
int rollno;
String name;
void displayInformation()
{
System.out.println(rollno+" "+name);}
}
class TestStudent4
{
public static void main(String args[])
{
Student s1=new Student();
Student s2=new Student();
s1.insertRecord(111,"Karan");
s2.insertRecord(222,"Aryan");
s1.displayInformation();
s2.displayInformation();
}
}
Output:
111 Karan
222 Aryan
As you can see in the above figure, object gets the memory in heap memory
area. The reference variable refers to the object allocated in the heap memory
area. Here, s1 and s2 both are reference variables that refer to the objects
allocated in memory.
3) Object and Class Example: Initialization through a constructor
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);
e1.display();
e2.display();
e3.display();
}
}
Output:
There is given another example that maintains the records of Rectangle class.
class Rectangle{
int length;
int width;
void insert(int l, int w){
length=l;
width=w;
}
void calculateArea(){System.out.println(length*width);}
}
class TestRectangle1{
public static void main(String args[]){
Rectangle r1=new Rectangle();
Rectangle r2=new Rectangle();
r1.insert(11,5);
r2.insert(3,15);
r1.calculateArea();
r2.calculateArea();
}
}
Output:
55
45
o By new keyword
o By newInstance() method
o By clone() method
o By deserialization
o By factory method etc.
Anonymous object
class Calculation{
void fact(int n){
int fact=1;
for(int i=1;i<=n;i++){
fact=fact*i;
}
System.out.println("factorial is "+fact);
}
public static void main(String args[]){
new Calculation().fact(5);//calling method with anonymous object
}
}
Output:
Factorial is 120
Output:
55
45
Constructors in Java
Example:
Types of Constructors
Default constructor
If you do not implement any constructor in your class, Java compiler inserts
a default constructor into your code on your behalf. This constructor is
known as default constructor.
no-arg constructor:
class Demo
{
public Demo()
{
System.out.println("This is a no argument constructor");
}
public static void main(String args[]) {
new Demo();
}
}
Output:
This is a no argument constructor
Parameterized constructor
int empId;
String empName;
Website: BeginnersBook
Website: BeginnersBook
Constructor Chaining
Method Overloading allows different methods to have the same name, but
different signatures where the signature can differ by the number of input
parameters or type of input parameters, or a mixture of both.
Method overloading is also known as Compile-time Polymorphism, Static
Polymorphism, or Early binding in Java. In Method overloading compared
to parent argument, child argument will get the highest priority.
Example:
Output :
30
60
31.0
Different Ways of Method Overloading in Java
Changing the Number of Parameters.
Changing Data Types of the Arguments.
Changing the Order of the Parameters of Methods
In Java, static is a keyword that is used for memory management mainly. Static means
single copy storage for variables or methods. The members that are declared with the
static keyword inside a class are called static members in java.
These members can be accessed even if no instance of the class exists because static
members are not tied to a particular instance. They are shared across all instances of
the class.
Static keyword in Java can be applied with variables, methods, inner classes, and
blocks.
We cannot declare a class with static keyword but the inner class can be declared as
static.
It belongs to the class than an instance of the class.
One basic rule of working with static keyword is that we cannot directly call instance
members within the static area because the static members are linked with the class.
Static members get memory once when the class is loaded into the memory. But
instance members get the memory after the object creation of the class.
There are mainly two uses of java static keyword that are as follows:
The main purpose of using static keyword is that we can access the data, method, or
block of the class without any object creation.
It is used to make the programs more memory efficient.
If we declare any instance variable with a static modifier, it is known as static variable in
Java. A static variable is also known as class variable in Java. It stores the value for a
variable in a common memory location.
For example:
When we declare an instance variable in java, a separate copy will be created for every
object. But in the case of a static variable, a single copy is created at the class level and
shared by all objects of that class.
Key point: A local variable cannot be declared as static. JVM will display modifier error at
compile time.
There are two ways to access a static variable in Java. They are as follows:
1. A static variable can be accessed inside any other class using the class name. The
general syntax to access a static variable is as follows:
A.x; // A is the class name and "x " is a static variable declared in that class.
2. Static variables can also be accessed by the object reference but an instance variable can
only be accessed by the object reference. For example, We have a class named Student. We
can create the object of the Student class like this:
Student s = new Student();
s.x;
Example:
class Student
{
static int id = 20;
System.out.println(x);
System.out.println(Student.id);
}
}
Output:
20
20
There are the following important points to keep in mind about static variable initialization
in Java. They are:
When a class is loaded into the memory at runtime, the static variable is created and
initialized into the common memory location only once. In other words, it gets loaded
into the memory at the time of class loading.
Static variables in a class are initialized before the creation of any instance of that
class.
Static variables in a class are initialized before the execution of any static method of
the class. Therefore, we cannot change the initialized value of the static variable
inside the static method.
If any object changes the value of the static variable, it will retain its value and
increments by 1 for every object creation.
class Counter
{
static int x = 0; // It will get memory only once and retain its value.
Counter()
{
x++; // It will increment the static variable by 1 for each object creation.
}
void display()
{
System.out.println(x);
}
Output:
1
2
3
The flow of execution of the above program is shown in the below figure.
Uses of Static Variable in Java with Example
The most common use of a static variable in a class is to hold predefined constant or
unchanging values that are the same for all the instances of the class and will never
change during the execution of the program.
class Employee
{
// Declare instance variables.
String name;
int id;
// Declare a static variable companyName of data type String and assign value IBM which is
common for all the objects.
static String companyName = "IBM";
// Similarly, create the second object of the class and pass the two arguments.
Employee e1 = new Employee("Deep", 321);
e1.display();
}
}
Output:
Name: Shubh
Id = 123
Company Name: IBM
Name: Deep
Id = 321
Company Name: IBM
Instance members (non-static members) can be accessed only from instance area directly.
But we cannot access it from the static area directly.
Yes, static members (static variables) can be accessed from both instance and static area
(i.e. instance and static methods) directly using the class name or without the class name.
But outside the class, we can call only using class name.
We can access a static variable in Java by using class name from another class.
We can change the value of the static variable in Java by using a constructor and static
block but not inside a static method.
class Demo
{
static int a = 20;
static int b = 50;
static int c = 100;
Demo()
{
a = 3; // Changed value of variable.
}
static
{
b = 10;
}
void m1()
{
System.out.println(a);
System.out.println(b);
System.out.println(c); // It will print 100.
}
Output:
3
10
100
Class variable makes program memory efficient. That is, it saves memory. All static
variables are stored in PermGen space of the heap memory.
Static Method in Java | Example Program
When a method is declared with the keyword ‘static’, it is called static method in java.
Like a static variable, static method is also tied to the class, not to an object of class.
Therefore, it can be called and executed without creating objects of the class.
Static method can be called or accessed directly using class name. The syntax to call a
static method in Java is as follows:
For example:
A static method is also known as class method in java because it belongs to a class rather
than an individual instance of a class.
The general syntax to declare the static method ( or class method) in java is as follows:
Access_modifier static void methodName()
{ // block start
. . . . . . . . . .
// Method body.
. . . . . . . . . .
} // block end.
The different forms of declaration of a static method with or without return type are shown
in the below figure.
Features of Static method (Class method)
There are several important features of a static method in java that must keep in mind.
They are as follows:
1. A static method in a class can directly access other static members of the class. We do
not need to create an object of class for accessing other static members. It can be called
directly within the same class and outside the class using the class name.
2. It cannot access instance (i.e. non-static) members of a class. The relationship between
instance and static members are summarized in the below figure:
An instance method can call an instance or static method. It can also access
instance or static data variable.
A static method can call a static method only. It can only access a static data
variable inside the static method.
3. We cannot declare a static method and instance method with the same signature in the
same class hierarchy.
4. When we create a static method in the class, only one copy of the method is created in
the memory and shared by all objects of the class. Whether you create 100 objects or 1
object.
5. A static method in java is also loaded into the memory before the object creation.
8. Static methods can be overloaded in Java but cannot be overridden because they are
bound with class, not instance.
9. Static (variable, method, and inner class) are stored in Permanent generation memory
(class memory).
When we declare a static method in Java, JVM first executes the static method, and then it
creates objects of the class. Since objects are not available at the time of calling the static
method.
Therefore, instance variables are also not available to a static method. Due to which a
static method cannot access an instance variable in the class.
class StaticTest
{
// Instance Area.
static int x = 20; // static variable
int y = 30; // instance variable
// Declare an instance method.
void display()
{
// Instance area. So we can directly call instance variable without using object
reference variable.
System.out.println(x); // Since we can access static member within instance
area. Therefore, we can call the static variable directly.
System.out.println(y);
}
// Declare a static method.
static void show()
{
// Static Area. So we can call S.V. directly inside th e S.M.
System.out.println(x);
// System.out.println(y); // compile time error because instance variable cannot
access inside S.M.
}
public static void main(String[] args)
{
// Create the object of the class.
StaticTest st = new StaticTest();
// Call instance method using reference variable st.
st.display();
Output:
20
30
20
The static method can be accessed by nullable reference as:
StaticMethod s1 = null;
s1.show();
class StaticMethod
{
static int a = 10;
void display()
{
System.out.println("This is an instance method");
}
static void show()
{
System.out.println("This is a Static method");
}
public static void main(String[] args)
{
StaticMethod sm = new StaticMethod();
sm.display();
StaticMethod s = null;
s.show();
int c = s.a;
System.out.println(c);
}
}
Output:
This is an Instance method
This is a Static method
Static method can access a static variable and can also change its value.
Let’s write a program where we will change the value of static variable inside static method.
Look at the following source code.
Program source code 3:
class ValueChange
{
static int a = 10;
static int change()
{
int a = 20;
return a;
}
public static void main(String[] args)
{
// Call static method using the class name. Since it will return an integer value.
So we will store it by using a changeValue variable.
int changeValue = ValueChange.change();
System.out.println(changeValue);
}
}
Output:
20
Let’s take another program where we will calculate the square and cube of a given number
by using static method.
Program source code 4:
class SquareAndCube
{
static int x = 15;
static int y = 20;
static int square(int x)
{ // Here, x is a local variable.
int a = x * x;
return a;
}
static int cube(int y){ // Here, y is a local variable.
int b = y*y*y;
return b;
}
public static void main(String[] args)
{
int sq = square(5);
int CB = cube(10);
System.out.println(sq);
System.out.println(cb);
}
}
Output:
25
1000
In entire core java, this and super keywords are not allowed inside the static method or
static area.
Super Keyword in Java
The super keyword in Java is a reference variable that is used to refer to parent
class objects. An understanding of Inheritance and Polymorphism is needed in
order to understand the Java super keyword. The keyword “super” came into the
picture with the concept of Inheritance.
Characteristics of super Keyword in Java
In Java, the super keyword is used to refer to the parent class of a subclass. Here
are some of its characteristics:
super is used to call a superclass constructor: When a subclass is created, its
constructor must call the constructor of its parent class. This is done using the
super() keyword, which calls the constructor of the parent class.
super is used to call a superclass method: A subclass can call a method defined
in its parent class using the super keyword. This is useful when the subclass
wants to invoke the parent class’s implementation of the method in addition to
its own.
super is used to access a superclass field: A subclass can access a field defined
in its parent class using the super keyword. This is useful when the subclass
wants to reference the parent class’s version of a field.
super must be the first statement in a constructor: When calling a superclass
constructor, the super() statement must be the first statement in the
constructor of the subclass.
super cannot be used in a static context: The super keyword cannot be used in
a static context, such as in a static method or a static variable initializer.
super is not required to call a superclass method: While it is possible to use the
super keyword to call a method in the parent class, it is not required. If a
method is not overridden in the subclass, then calling it without the super
keyword will invoke the parent class’s implementation.
Overall, the super keyword is a powerful tool for subclassing in Java, allowing
subclasses to inherit and build upon the functionality of their parent classes.
Use of super Keyword in Java
It is majorly used in the following contexts as mentioned below:
Use of super with variables
Use of super with methods
Use of super with constructors
1. Use of super with Variables
This scenario occurs when a derived class and base class has the same data
members. In that case, there is a possibility of ambiguity for the JVM.
We can understand it more clearly using the following example:
Example
Output
Maximum Speed: 120
In the above example, both the base class and subclass have a member maxSpeed.
We could access maxSpeed of base class in subclass using super keyword.
2. Use of super with Methods
This is used when we want to call the parent class method. So whenever a parent
and child class have the same-named methods then to resolve ambiguity we use the
super keyword.
This code snippet helps to understand the said usage of the super keyword.
Example
Output
This is student class
This is person class
In the above example, we have seen that if we only call method message() then, the
current class message() is invoked but with the use of the super keyword, message()
of the superclass could also be invoked.
3. Use of super with constructors
The super keyword can also be used to access the parent class constructor. One
more important thing is that ‘super’ can call both parametric as well as non-
parametric constructors depending on the situation.
Following is the code snippet to explain the above concept:
Example 1
Output
Person class Constructor
Student class Constructor
In the above example, we have called the superclass constructor using the keyword
‘super’ via subclass constructor.
Example 2
Output
false
Advantages of Using Java super keyword
The super keyword in Java provides several advantages in object-oriented
programming:
Enables reuse of code: Using the super keyword allows subclasses to inherit
functionality from their parent classes, which promotes the reuse of code and
reduces duplication.
Supports polymorphism: Because subclasses can override methods and
access fields from their parent classes using super, polymorphism is possible.
This allows for more flexible and extensible code.
Provides access to parent class behavior: Subclasses can access and use
methods and fields defined in their parent classes through the super keyword,
which allows them to take advantage of existing behavior without having to
reimplement it.
Allows for customization of behavior: By overriding methods and using
super to call the parent implementation, subclasses can customize and
extend the behavior of their parent classes.
Facilitates abstraction and encapsulation: The use of super promotes
encapsulation and abstraction by allowing subclasses to focus on their own
behavior while relying on the parent class to handle lower-level details.
Overall, the super keyword is a key feature of inheritance and polymorphism in
Java, and it provides several benefits for developers seeking to write reusable,
extensible, and well-organized code.
Important Points to Remember while using Super Keyword
Call to super() must be the first statement in the Derived(Student) Class
constructor because if you think about it, it makes sense that the superclass
has no knowledge of any subclass, so any initialization it needs to perform is
separate from and possibly prerequisite to any initialization performed by the
subclass. Therefore, it needs to complete its execution first.
If a constructor does not explicitly invoke a superclass constructor, the Java
compiler automatically inserts a call to the no-argument constructor of the
superclass. If the superclass does not have a no-argument constructor, you
will get a compile-time error. The object does have such a constructor, so if
the Object is the only superclass, there is no problem.
Inheritance is a process where child class acquired all the properties and
behaviors of the parent class. Inheritance is used when one object is based
on another object. Here parent class also called a superclass and child class
called a subclass.
Advantage of inheritance
Code Reusability
Runtime Polymorphism/ Method Overriding
In java, extends keyword is used to inherit a class where a new class derived
properties and methods of an existing class. The class that inherited is
called a Parent/Superclass, and a new derived class is called a
child/subclass.
Constructors are not members of the class, so they are not inherited by
child class, but the constructor of the parent class can be invoked from the
child class by using super.
These inherited members can use as-is, replace them, hide them, or
supplement them with new members:
Parent class inherited fields can be used directly, just like any other
class field.
You can declare a field in the child class with the same name as the one
in the parent class, thus hiding it (not recommended).
You can declare new fields in the child class that are not in the parent
class.
The inherited parent class methods can be used directly as they are.
You can write a methods in child class that has the same signature as
the one in the parent class. i.e Method Overriding.
You can write a new static method in the child class with the same
signature as on the parent class, thus hiding it.
You can declare new methods in the child class that are not in the
parent class.
You can write a child class constructor that invokes the constructor of
the parent class, either implicitly or by using the keyword super.
Types of inheritance :
Single Inheritance
Multiple Inheritance
Hierarchical Inheritance
Multilevel Inheritance
Hybrid Inheritance
Single Inheritance
class TestInheritance
{
public static void main(String args[])
{
Dog d=new Dog();
d.bark();
d.eat();
}
}
Multiple Inheritance
“Multiple Inheritance” refers to the concept of one class
extending (Or inherits) more than one base class. The
inheritance we learnt earlier had the concept of one base
class or parent. The problem with “multiple inheritance”
is that the derived class will have to manage the
dependency on two base classes.
Note 1: Multiple Inheritance is very rarely used in
software projects. Using Multiple inheritance often leads
to problems in the hierarchy. This results in unwanted complexity
when further extending the class.
Multilevel Inheritance
class Car{
public Car()
{
System.out.println("Class Car");
}
public void vehicleType()
{
System.out.println("Vehicle Type: Car");
}
}
class Maruti extends Car{
public Maruti()
{
System.out.println("Class Maruti");
}
public void brand()
{
System.out.println("Brand: Maruti");
}
public void speed()
{
System.out.println("Max: 90Kmph");
}
}
public class Maruti800 extends Maruti{
public Maruti800()
{
System.out.println("Maruti Model: 800");
}
public void speed()
{
System.out.println("Max: 80Kmph");
}
public static void main(String args[])
{
Maruti800 obj=new Maruti800();
obj.vehicleType();
obj.brand();
obj.speed();
}
}
Output:
Class Car
Class Maruti
Maruti Model: 800
Vehicle Type: Car
Brand: Maruti
Max: 80Kmph
Hierarchical Inheritance
class A
{
public void methodA()
{
System.out.println("method of Class A");
}
}
class B extends A
{
public void methodB()
{
System.out.println("method of Class B");
}
}
class C extends A
{
public void methodC()
{
System.out.println("method of Class C");
}
}
class D extends A
{
public void methodD()
{
System.out.println("method of Class D");
}
}
class JavaExample
{
public static void main(String args[])
{
B obj1 = new B();
C obj2 = new C();
D obj3 = new D();
//All classes can access the method of class A
obj1.methodA();
obj2.methodA();
obj3.methodA();
}
}
Output:
method of Class A
method of Class A
method of Class A
5) Hybrid Inheritance
class C
{
public void disp()
{
System.out.println("C");
}
}
class A extends C
{
public void disp()
{
System.out.println("A");
}
}
class B extends C
{
public void disp()
{
System.out.println("B");
}
class D extends A
{
public void disp()
{
System.out.println("D");
}
public static void main(String args[]){
D
Abstract Class in Java
Output
avinash
21
222.2
Observation 1
Example
Output
Observation 2
Example:
}
Output
Observation 3
Output
Observation 4
Abstract classes can also have final methods (methods that cannot be
overridden)
Example:
Output
Observation 5
For any abstract java class we are not allowed to create an object i.e., for an
abstract class instantiation is not possible.
Observation 6
Output
We can use the abstract keyword for declaring top-level classes (Outer
class) as well as inner classes as abstract
Output
Observation 8
Output
Hello
Observation 9
Inside m1
Inside m2
Inside m3
In C++, if a class has at least one pure virtual function, then the class
becomes abstract. Unlike C++, in Java, a separate keyword abstract is used
to make a class abstract.
Packages in Java
A package is a collection of similar types of Java entities such as classes,
interfaces, subclasses, exceptions, errors, and enums. A package can also
contain sub-packages.
Advantages:
There are several advantages of using Java Packages, some of them, are as
follows
1. Java.lang: lang stands for language. The Java language package consists
of java classes and interfaces that form the core of the Java language and
the JVM. It is a fundamental package that is useful for writing and
executing all Java programs.
Examples are classes, objects, String, Thread, predefined data types, etc. It
is imported automatically into the Java programs.
2. Java.io: io stands for input and output. It provides a set of I/O streams
that are used to read and write data to files. A stream represents a flow of
data from one place to another place.
3. Java util: util stands for utility. It contains a collection of useful utility
classes and related interfaces that implement data structures like
LinkedList, Dictionary, HashTable, stack, vector, Calender, data utility, etc.
1. Java.awt: awt stands for abstract window toolkit. The Abstract window
toolkit packages contain the GUI(Graphical User Interface) elements such as
buttons, lists, menus, and text areas. Programmers can develop programs
with colorful screens, paintings, and images, etc using this package.
3. Java.applet: It is used for creating applets. Applets are programs that are
executed from the server into the client machine on a network.
5. Java.sql: SQL stands for the structured query language. This package is
used in a Java program to connect databases like Oracle or Sybase and
retrieve the data from them.
There are three approaches to import one package into another package in
Java.
1. import package.*;
2. import package.classname;
1. Using package.*
Example:
import java.util.*;
Example:
import java.util.vector;
3. Using a Fully qualified name means we can access the declared class of
different packages without using the import statement.
Example:
Example:
import java.util.*;
public class Add
{
int s;
public void sum()
{
System.out.print("Enter the first number: ");
Scanner scan=new Scanner(System.in);
int x=scan.nextInt();
System.out.print("Enter the second number: ");
Scanner scan1=new Scanner(System.in);
int y=scan1.nextInt();
s=x+y;
System.out.println("sum="+s);
}
}
User-defined Packages
Syntax:
package package-name;
Step 1: Creating a package in java class. The format is very simple and
easy. Just write a package by following its name.
package example1;
Step 2: Include class in java package, But remember that class only has one
package declaration.
package example1;
class gfg {
-------function--------
Example:
Output:
Example 2:
Output:
Output:
a = 10 b = 20
Output:
Inside parameterized constructor
Inside default constructor
3. Using ‘this’ keyword to return the current class instance
Output :
Inside show funcion
Inside display function
Output : Value of x in Class B : 5
What is ‘this’ Keyword in Java?
● Java this keyword returns a reference to the current Object.
● We can access object variable, call the method or constructor of the current
object using this keyword.
● Java ‘this’ keyword can be used to refer to any member of the current object
from within an instance method or a constructor.
● this keyword is mostly used to avoid the confusion between a class attribute
and a parameter. For example, if a parameter of a member function has the
same name as that of an object variable, then the functionality may not
work properly.
1. Using ‘this’ keyword to refer current class instance variables
Output:
a = 10 b = 20
Output:
Inside parameterized constructor
Inside default constructor
3. Using ‘this’ keyword to return the current class instance
Output :
Inside show funcion
Inside display function
Output : Value of x in Class B : 5
What is Method Overriding
When the child class(subclass) has the method which has the same name, same
parameters and same return type (or covariant return type) as a method in its
parent class(or super-class), then the child method has overridden the parent class
method.
class Parent {
public void display() {
System.out.println("parent method is executed");
}
}
//Driver class
public class MethodOverriding1 {
public static void main(String args[])
{
// If a Parent type reference refers to a Parent object, then Parent's
// display() is called
Parent parentObject = new Parent();
parentObject.display();
Output :
parent method is executed
child method is executed
Rules for Method Overriding in Java
1. Access Modifiers and Overriding
The access level can't be more restrictive than the overridden method. The access
level can be less restrictive than that of the overridden method.
Example:
//Base class
class Parent {
//Access modifier of parent's display() method is protected
protected void display() {
System.out.println("parent method is executed");
}
}
//Derived class
class Child extends Parent {
Output :
parent method is executed
child method is executed
Another rule regarding access modifiers is you can not override private methods
in the parent class. If subclass tries to override the private method of a parent
class then the program will throw a compile-time error as shown below.
//Base class or Superclass
class Parent {
//Access modifier of parent method is private
// This method can not override the child class method
private void display() {
System.out.println("parent method is executed");
}
}
Output :
/Main.java:13: error: display() in Child cannot override display() in Parent
void display() { }
^
overridden method is final
1 error
4. Static methods can not be overridden
You can not override a method mark static. If you define a static method in the
subclass (child class) with the same method signature as the superclass(parent
class) then it is called method hiding.
void show() {
System.out.println("parent non-static (instance) method is executed");
}
}
//Driver Class
public class MethodOverriding4 {
public static void main(String args[])
{
Parent childObject = new Child();
// static method can not be overridden,
// so below line calls parent display() method
childObject.display();
// Expected child method will run
childObject.show();
}
}
Output:
parent static method is executed
child non-static (instance) method is executed
void display() {
System.out.println("parent method is executed");
}
}
Output :
parent method is executed
child method is executed
.
As you can see in the above figure, the thread is executed inside a process and
one process can have also multiple threads. There can be multiple processes
inside the operating system.
Multiple Threads are independent of each other. At a time, only one thread is
executed. If an exception occurs in one thread, it doesn’t affect other threads.
Why Java threads are lightweight process?
Java Threads are also known as lightweight threads or light-weight processes.
It means that they can be executed in the same memory space because all the
threads in the main application program share the same address space in the
memory so that they can easily communicate among themselves. Thus, they
also take less space in memory and less processor time.
Every Java program has always at least one thread, even if you do not create any
thread. This thread is called main thread.
The main thread is also called parent thread and the rest of threads that are
generated from it are called child threads of the program.
Main thread is the last thread to be executed in a program. When main thread
finishes the execution, the program terminates immediately. Whenever Java
program starts, main thread is created automatically.
This main thread is available in all programs. We can control the execution of the
main thread by creating a Thread object and then using methods of Thread class.
To do so, we will have to create a Thread object by calling currentThread() method
of class Thread. A Thread object can be created as follows:
Thread obj = Thread.currentThread();
Output:
Current thread is Thread[main,5,main]
Name of current thread is main
Name of current thread after changing name is Thread[New
Thread,5,main]
Main thread existing
Java Threads | How to create a thread in Java
Thread class:
Thread class provide constructors and methods to create and perform operations on a
thread.Thread class extends Object class and implements Runnable interface.
o Thread()
o Thread(String name)
o Thread(Runnable r)
o Thread(Runnable r,String name)
Runnable interface:
The Runnable interface should be implemented by any class whose instances are intended
to be 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 the
following tasks:
Output:
thread is running...
Java Thread Example by implementing Runnable interface
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.
We can directly use the Thread class to spawn new threads using the constructors defined
above.
Output:
My first thread
// main method
public static void main(String argvs[])
{
// creating an object of the class MyThread2
Runnable r1 = new MyThread2();
Output:
My new thread
Now the thread is running ...
Thread States in Java
A thread is a program in execution created to perform a specific task. Life cycle of a Java
thread starts with its birth and ends on its death.
The start() method of the Thread class is used to initiate the execution of a thread and it
goes into runnable state and the sleep() and wait() methods of the Thread class sends the
thread into non runnable state.
After non runnable state, thread again comes into runnable state and starts its execution.
The run() method of thread is very much important. After executing the run() method, the
lifecycle of thread is completed.
To work with threads in a program, it is important to identify thread state. The following
figure shows thread states in Java thread life cycle.
A thread is a path of execution in a program that goes through the following states of a
thread. The five states are as follows:
1. New
2. Runnable
3. Running
4. Blocked (Non-runnable state)
5. Dead
New (Newborn State)
When an instance of the Thread class is created a new thread is born and is known to be in
New-born state. That is, when a thread is born, it enters into new state but its execution
phase has not been started yet on the instance.
In simpler terms, Thread object is created but it cannot execute any program statement
because it is not in an execution state of the thread. Only start() method can be called on a
new thread; otherwise, an IllegalThreadStateException will be thrown.
Runnable State
The second phase of a new-born thread is the execution phase. When the start() method is
called on a the new instance of a thread, it enters into a runnable state.
In the runnable state, thread is ready for execution and is waiting for availability of the
processor (CPU time). There are many threads that are ready for execution, they all are
waiting in a queue (line).
If all threads have equal priority, a time slot is assigned for each thread execution on the
basis of first-come, first-serve manner by CPU. 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.
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. It is the state where thread performs its actual functions. A thread can come into
running state only from runnable state.
A running thread may give up its control in any one of the following situations and can
enter into the blocked state.
1. When sleep() method is invoked on a thread to sleep for specified time period, the
thread is out of queue during this time period. The thread again reenters into the
runnable state as soon as this time period is elapsed.
2. 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.
3. When wait() method is called on a thread to wait for some time. The thread in wait
state can be run again using notify() or notifyAll() method.
Blocked 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 thread comes 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 are
executing, 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
for satisfying some conditions. Therefore, a thread is always in any of the five states.
Example:
/* Thread 1 */
class Thread1 extends Thread
{
public void run()
{
System.out.println("Thread 1");
System.out.println("i in Thread 1 ");
for (int i = 1; i <= 5; i++)
{
System.out.println("i = " + i);
try
{
Thread.sleep(1000);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
System.out.println("Thread 1 Completed.");
}
}
/* Thread 2 */
class Thread2 extends Thread
{
public void run()
{
System.out.println("Thread 2");
System.out.println("i in Thread 2 ");
for (int i = 1; i <= 5; i++)
{
System.out.println("i = " + i);
}
System.out.println("Thread 2 Completed.");
}
}
/* Driver code */
public class ThreadDemo
{
public static void main(String[] args) {
// life cycle of Thread
// Thread's New State
Thread1 t1 = new Thread1();
Thread2 t2 = new Thread2();
// Both the above threads are in runnable state
// Running state of Thread1 and Thread2
t1.start();
// Move control to another thread
t2.yield();
// Blocked State Thread1
try
{
t1.sleep(1000);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
t2.start();
System.out.println("Main Thread End");
}
}
Output:
Thread 1
i in Thread 1
i=1
Main Thread End
Thread 2
i in Thread 2
i=1
i=2
i=3
i=4
i=5
Thread 2 Completed.
i=2
i=3
i=4
i=5
Thread 1 Completed.
Java - Multithreading
Java is a multi-threaded programming language which means we can develop multi-
threaded program using Java. A multi-threaded program contains two or more parts that
can run concurrently and each part can handle a different task at the same time making
optimal use of the available resources specially when your computer has multiple CPUs.
By definition, multitasking is when multiple processes share common processing resources
such as a CPU. Multi-threading extends the idea of multitasking into applications where
you can subdivide specific operations within a single application into individual threads.
Each of the threads can run in parallel. The OS divides processing time not only among
different applications, but also among each thread within an application.
Multi-threading enables you to write in a way where multiple activities can proceed
concurrently in the same program.
We create a class that extends the java.lang.Thread class. This class overrides the run()
method available in the Thread class. A thread begins its life inside run() method. We
create an object of our new class and call start() method to start the execution of a thread.
Start() invokes the run() method on the Thread object.
Output
Thread 15 is running
Thread 14 is running
Thread 16 is running
Thread 12 is running
Thread 11 is running
Thread 13 is running
Thread 18 is running
Thread 17 is running
Output
Thread 13 is running
Thread 11 is running
Thread 12 is running
Thread 15 is running
Thread 14 is running
Thread 18 is running
Thread 17 is running
Thread 16 is running
Priority of a Thread (Thread Priority)
Each thread has a priority. Priorities are represented by a number between 1 and 10. In
most cases, the thread scheduler schedules the threads according to their priority (known
as preemptive scheduling). But it is not guaranteed because it depends on JVM
specification that which scheduling it chooses. Note that not only JVM a Java programmer
can also assign the priorities of a thread explicitly in a Java program.
public final int getPriority(): The java.lang.Thread.getPriority() method returns the priority
of the given thread.
import java.lang.*;
th1.setPriority(6);
th2.setPriority(3);
th3.setPriority(9);
Thread.currentThread().setPriority(10);
Output:
Synchronization in Java is the capability to control the access of multiple threads to any
shared resource.
Java Synchronization is better option where we want to allow only one thread to access the
shared resource.
Types of Synchronization
1. Process Synchronization
2. Thread Synchronization
Thread Synchronization
There are two types of thread synchronization mutual exclusive and inter-thread
communication.
1. Mutual Exclusive
1. Synchronized method.
2. Synchronized block.
3. Static synchronization.
2. Cooperation (Inter-thread communication in java)
Mutual Exclusive
Mutual Exclusive helps keep threads from interfering with one another while sharing data.
It can be achieved by using the following three ways:
Synchronization is built around an internal entity known as the lock or monitor. Every
object has a lock associated with it. By convention, a thread that needs consistent access to
an object's fields has to acquire the object's lock before accessing them, and then release
the lock when it's done with them.
From Java 5 the package java.util.concurrent.locks contains several lock implementations.
class Table
{
void printTable(int n)
{//method not synchronized
for(int i=1;i<=5;i++)
{
System.out.println(n*i);
try
{
Thread.sleep(400);
}
catch(Exception e)
{
System.out.println(e);
}
}
}
}
}
class MyThread2 extends Thread{
Table t;
MyThread2(Table t){
this.t=t;
}
public void run(){
t.printTable(100);
}
}
class TestSynchronization1
{
public static void main(String args[])
{
Table obj = new Table();//only one object
MyThread1 t1=new MyThread1(obj);
MyThread2 t2=new MyThread2(obj);
t1.start();
t2.start();
}
}
Output:
When a thread invokes a synchronized method, it automatically acquires the lock for that
object and releases it when the thread completes its task.
class Table
{
synchronized void printTable(int n)
{//synchronized method
for(int i=1;i<=5;i++)
{
System.out.println(n*i);
try
{
Thread.sleep(400);
}
catch(Exception e)
{ System.out.println(e); }
}
}
}
Output:
Synchronized block can be used to perform synchronization on any specific resource of the
method.
Suppose we have 50 lines of code in our method, but we want to synchronize only 5 lines,
in such cases, we can use synchronized block.
If we put all the codes of the method in the synchronized block, it will work same as the
synchronized method.
Points to Remember
Syntax
class Table
{
void printTable(int n)
{
synchronized(this)
{//synchronized block
for(int i=1;i<=5;i++)
{
System.out.println(n*i);
try
{
Thread.sleep(400);
}catch(Exception e){System.out.println(e);}
}
}
}
}
Output:
If you make any static method as synchronized, the lock will be on the class not on object.
Suppose there are two objects of a shared class (e.g. Table) named object1 and object2. In
case of synchronized method and synchronized block there cannot be interference between
t1 and t2 or t3 and t4 because t1 and t2 both refers to a common object that have a single
lock. But there can be interference between t1 and t3 or t2 and t4 because t1 acquires
another lock and t3 acquires another lock. We don't want interference between t1 and t3 or
t2 and t4. Static synchronization solves this problem.
In this example we have used synchronized keyword on the static method to perform static
synchronization.
class Table
{
synchronized static void printTable(int n){
for(int i=1;i<=10;i++){
System.out.println(n*i);
try{
Thread.sleep(400);
}catch(Exception e){}
}
}
}
Output:
1 2 3 4 5 6 7 8 9 10 10 20 30
40 50 60 70 80 90 100 100 200 300 400 500
600 700 800 900 1000 1000 2000 3000 4000
5000 6000 7000 8000 9000 10000
Inter-thread Communication in Java
wait()
notify()
notifyAll()
1) wait() method
The wait() method causes current thread to release the lock and wait until either another
thread invokes the notify() method or the notifyAll() method for this object, or a specified
amount of time has elapsed.
The current thread must own this object's monitor, so it must be called from the
synchronized method only otherwise it will throw exception.
Method Description
public final void wait(long timeout)throws It waits for the specified amount of
InterruptedException time.
2) notify() method
The notify() method wakes up a single thread that is waiting on this object's monitor. If any
threads are waiting on this object, one of them is chosen to be awakened. The choice is
arbitrary and occurs at the discretion of the implementation.
Syntax:
3) notifyAll() method
Syntax:
Why wait(), notify() and notifyAll() methods are defined in Object class not Thread
class?
wait() sleep()
The wait() method releases the lock. The sleep() method doesn't release the lock.
It should be notified by notify() or notifyAll() After the specified amount of time, sleep is
methods completed.
class Customer
{
int amount=10000;
synchronized void withdraw(int amount)
{
System.out.println("going to withdraw...");
if(this.amount<amount)
{
System.out.println("Less balance; waiting for deposit...");
try{wait();}catch(Exception e){}
}
this.amount-=amount;
System.out.println("withdraw completed...");
}
class Test
{
public static void main(String args[])
{
final Customer c=new Customer();
new Thread(){
public void run()
{
c.withdraw(15000);
}
}.start();
new Thread()
{
public void run()
{
c.deposit(10000);
}
}.start();
}
}
Output:
going to withdraw...
Less balance; waiting for deposit...
going to deposit...
deposit completed...
withdraw completed
Java AWT calls the native platform calls the native platform (operating systems)
subroutine for creating API components like TextField, ChechBox, button, etc.
For example, an AWT GUI with components like TextField, label and button will
have different look and feel for the different platforms like Windows, MAC OS,
and Unix. The reason for this is the platforms have different view for their native
components and AWT directly calls the native subroutine that creates those
components.
Components
Container
Types of containers:
1. Window
2. Panel
3. Frame
4. Dialog
Window: The window is the container that have no borders and menu bars.
You must use frame, dialog or another window for creating a window. We need
to create an instance of Window class to create this container.
Panel: The Panel is the container that doesn't contain title bar, border or
menu bar. It is generic container for holding the components. It can have other
components like button, text field etc. An instance of Panel class creates a
container, in which we can add components. You can also customize its
components using the Layout Managers.
Dialog: Dialog class has border and title. An instance of the Dialog class
cannot exist without an associated instance of the Frame class.
Frame: The frame is a component that works as the main top-level window of
the GUI application. It is created using the Frame class. For any GUI application,
the first step is to create a frame. There are two methods to create a frame: by
extending the Frame class or by creating an object of Frame class.
The frame is a resizable and movable window. It has the title bar and border
and can have menu bars. The default visibility of a Frame is hidden. The
programmer has to make it visible by using the set Visible method and
providing the value “true” to it.
It can have other components like button, text field, scrollbar etc. Frame is most
widely used container while developing an AWT application.
Difference between Frame and Panel:
Method Description
public void setSize(int width,int Sets the size (width and height) of the
height) component.
import java.awt.*;
import java.awt.*;
public class Example2 {
Example2()
{
//Creating Frame
Frame fr=new Frame();
//Creating a label
Label lb = new Label("UserId: ");
fr.setVisible(true);
}
public static void main(String args[])
{
Example2 ex = new Example2();
}
}
Output:
import java.awt.*;
class AWTExample2
{
AWTExample2()
{
// creating a Frame
Frame f = new Frame();
// creating a Label
Label l = new Label("Employee id:");
// creating a Button
Button b = new Button("Submit");
// creating a TextField
TextField t = new TextField();
f.setTitle("Employee info");
f.setLayout(null);
f.setVisible(true);
}
// main method
public static void main(String args[])
{
}
}
Java GUI Event Handling: Any program that uses GUI (graphical user interface)
such as Java application written for windows, is event driven. Event describes
the change in state of any object. For Example : Pressing a button, Entering a
character in Textbox, Clicking or Dragging a mouse, etc.
init() { }
3. Add or Register the listener to source for receiving notification. Each type of
event has its own listener.
1. add TypeListener(TypeListener);
2. addMouseListener(this);
We can put the event handling code into one of the following places:
1. Within class
2. Other class
3. Anonymous class
//Java event handling by implementing ActionListener
import java.awt.*;
import java.awt.event.*;
class AEvent extends Frame implements ActionListener
{
TextField tf;
AEvent()
{
//create components
tf=new TextField();
tf.setBounds(60,50,170,20);
Button b=new Button("click me");
b.setBounds(100,120,80,30);
//register listener
b.addActionListener(this);//passing current instance
AEvent2()
{
//create components
tf=new TextField();
tf.setBounds(60,50,170,20);
Button b=new Button("click me");
b.setBounds(100,120,80,30);
//register listener
Outer o=new Outer(this);
b.addActionListener(o);//passing outer class instance
//add components and set size, layout and visibility
add(b);add(tf);
setSize(300,300);
setLayout(null);
setVisible(true);
}
import java.awt.event.*;
class Outer implements ActionListener
{
AEvent2 obj;
Outer(AEvent2 obj)
{
this.obj=obj;
}
public void actionPerformed(ActionEvent e)
{
obj.tf.setText("welcome");
}
}
//Java event handling by anonymous class
import java.awt.*;
import java.awt.event.*;
class AEvent3 extends Frame
{
TextField tf;
AEvent3()
{
tf=new TextField();
tf.setBounds(60,50,170,20);
Button b=new Button("click me");
b.setBounds(50,120,80,30);
b.addActionListener(new ActionListener()
add(b);add(tf);
setSize(300,300);
setLayout(null);
setVisible(true);
Class constructors
Class methods
void setLabel(String label) :Sets the button's label to be the specified string.
import java.awt.*;
public class CreateButton
{
CreateButton()
{
Frame f = new Frame();
Button b1 = new Button("Button 1");
Button b2 = new Button("B2");
Button b3 = new Button();
b1.setBounds(50,50,100,50);
b2.setBounds(50,100,100,50);
b3.setBounds(150,50,100,100);
f.setLayout(null);
f.setSize(300,300);
f.setVisible(true);
f.add(b1);
f.add(b2);
f.add(b3);
The object of the Label class is a component for placing text in a container. It is
used to display a single line of read only text. The text can be changed by a
programmer but a user cannot edit it directly.
It is called a passive control as it does not create any event when it is accessed.
To create a label, we need to create the object of Label class.
1. static int LEFT: It specifies that the label should be left justified.
2. static int RIGHT: It specifies that the label should be right justified.
3. static int CENTER: It specifies that the label should be placed in center.
3. Label(String text, int It constructs a label with the specified string and the
alignement) specified alignment.
1. void setText(String text) It sets the texts for label with the specified text.
2. void setAlignment(int It sets the alignment for label with the specified
alignment) alignment.
import java.awt.*;
public class LabelExample
{
public static void main(String args[])
{
f.add(l1);
f.add(l2);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
}
Java AWT TextField
The object of a TextField class is a text component that allows a user to enter a single
line text and edit it. It inherits TextComponent class, which further
inherits Component class.
When we enter a key in the text field (like key pressed, key released or key typed), the
event is sent to TextField. Then the KeyEvent is passed to the registered KeyListener. It
can also be done using ActionEvent; if the ActionEvent is enabled on the text field, then
the ActionEvent may be fired by pressing return key. The event is handled by
the ActionListener interface.
4. TextField(String text, int It constructs a new text field with the given text and
columns) given number of columns (width).
void setColumns(int
4. It sets the number of columns in text field.
columns)
void setEchoChar(char
5. It sets the echo character for text field.
c)
The object of the Label class is a component for placing text in a container. It
is used to display a single line of read only text. The text can be changed by a
programmer but a user cannot edit it directly.
Constructors of Label
Constructor Description
Methods Description
public void
Sets a String message on the Label.
setText(String text)
void setAlignment(int
Sets an alignment on this label.
alignment)
The object of a TextField class is a text component that allows a user to enter a
single line text and edit it. It inherits TextComponent class, which further
inherits Component class.
When we enter a key in the text field (like key pressed, key released or key typed),
the event is sent to TextField. Then the KeyEvent is passed to the
registered KeyListener. It can also be done using ActionEvent; if the
ActionEvent is enabled on the text field, then the ActionEvent may be fired by
pressing return key. The event is handled by the ActionListener interface.
Constructors of TextField
Constructor Description
public TextField) Creates a TextField..
public TextField(String text) Creates a TextField with a specified default text.
public TextField(int width) Creates a TextField with a specified width.
public TextField(String text, int Creates a TextField with a specified default text and
width) width.
Methods Description
public void setText(String text) Sets a String message on the TextField.
public String getText() Gets a String message of TextField.
The object of a TextArea class is a multiline region that displays text. It allows the
editing of multiple line text. It inherits TextComponent class.
The text area allows us to type as much text as we want. When the text in the text area
becomes larger than the viewable area, the scroll bar appears automatically which helps
us to scroll the text up and down, or right and left.
Constructors of TextArea
Constructor Description
public TextArea() Creates a new TextArea..
public TextArea(String text) Creates a new TextArea with specified text.
public TextArea(int rows, int Creates a new TextArea with specified number of rows and
columns) columns.
public TextArea(String text, int Creates a new TextArea with a text and a number of rows and
rows, int columns) columns.
Constructors of Button
Constructor Description
public Button() Creates a button with no text on it.
public Button(String text) Creates a button with a text on it.
Methods Description
public void setText(String
Sets a String message on the Button.
text)
public String getText() Gets a String message of Button.
public void setLabel() Sets a String text on button.
public String getLabel() Gets the String text of this button.
Scrollbar class
Scrollbar class is used to create a horizontal and vertical Scrollbar. A
Scrollbar can be added to a top-level container like Frame or a component like
Panel. Scrollbar class is another component in the AWT package which extends
the Component class.
Constructors of Scrollbar
Constructor Description
public Scrollbar(int orientation, Creates a Scrollbar with the
int value int extent, int min, specified orientation, value, extent,
int max) minimum, and maximum, where -
Methods Description
public
addAdjustmentListener(AdjustmentListener Adds an AdjustmentListener.
al)
Gets the Scrollbar's current
public int getValue()
position value.
Sets the Scrollbar's current
public int setValue(int value)
position value.
Checkbox class: Checkbox class is used to create a checkbox control, which
contains a box that can be checked or unchecked by clicking on it.
Checkbox is a component which extends Component class and it can be added
to the container like Frame or a component like Panel.
Constructors of Checkbox
Constructor Description
Creates a checkbox with no text, this checkbox is
public Checkbox()
unchecked by default.
Creates a checkbox with a text, this checkbox is
public Checkbox(String text)
unchecked by default.
Checkbox(String label,
Constructs a Checkbox with the specified label, set to
boolean state,
the specified state, and in the specified check box
CheckboxGroup group)
group.
Checkbox(String label,
CheckboxGroup group, Creates a check box with the specified label, in the
boolean state) specified check box group, and set to the specified
state.
Methods Description
public void Sets a name on the Checkbox, this name will not
setName(String text) be displayed.
Gets a String message of Checkbox, this name will
public String getName()
not be displayed.
public void setLabel() Sets a String text on button.
public String getLabel() Gets the String text of this button.
public void
Sets a state of Checkbox.
setState(boolean b)
public boolean getState() Gets the state of Checkbox.
CheckboxGroup class: The object of CheckboxGroup class is used to group together a
set of Checkbox. At a time only one check box button is allowed to be in "on" state and
remaining check box button in "off" state. It inherits the object class.
import java.awt.*;
import java.awt.event.*;
public class CBG implements ItemListener
{ public void itemStateChanged(ItemEvent ie)
Frame jf; {
CheckboxGroup cbg; Checkbox ch =(Checkbox)ie.getItemSelectable();
Checkbox winXP, winVista,solaris,mac; if(ch.getState()==true)
Label label1; {
CBG() label1.setText(ch.getLabel()+ " is checked");
{ jf.add(label1);
jf= new Frame("Checkbox"); jf.setVisible(true);
cbg = new CheckboxGroup(); }
label1 = new Label(); }
public static void main(String... ar)
winXP = new Checkbox("Windows XP", cbg, true); {
winVista = new Checkbox("Windows Vista", cbg, false); new CBG();
solaris = new Checkbox("Solaris", cbg, false); }
mac = new Checkbox("Mac OS", cbg, false);
}
jf.add(winXP);
jf.add(winVista);
jf.add(solaris);
jf.add(mac);
winXP.addItemListener(this);
winVista.addItemListener(this);
solaris.addItemListener(this);
mac.addItemListener(this);
jf.setLayout(new FlowLayout());
jf.setSize(232,150);
jf.setVisible(true);
}
List Class:
List class is used to create a list with multiple values, allowing a user to
select any of the values. When a value is selected from List, an ItemEvent is
generated, which is handled by implementing ItemListener interface. List is
another component in AWT which extends Component class.
Constructors of List
Constructor Description
public List() Creates a scrolling list.
public List(int rows) Creates a List with a number of rows.
Methods Description
public void add(String item) Adds the item to the end of List.
public void add(String item, int index) Adds the item at a specific index in the list.
Adds a specific ActionListener to listen an Action
public void
event generated when item is selected from this
addActionListener(ActionListener al)
list.
Adds a specific ItemListener to listen an Item
public void
event generated when item is selected from this
addItemListener(ItemListener al)
list.
public String getItem( int index) Gets an item from a specific index in the list.
public String getSelectedItem() Gets the selected item in the list.
public String[] getSelectedItems() Gets the selected item in the list.
public int getRows() Gets the total number of rows in the list.
Choice Class
Choice class is part of Java Abstract Window Toolkit (AWT). The Choice class
presents a pop- up menu for the user, the user may select an item from the
popup menu. The selected item appears on the top. The Choice class inherits
the Component.
Note that you cannot select multiple items from the list. This component is
the best component to use than the check box groups or list because it
consumes less space than these components. It can be created by
instantiating the Choice class.
Choice has only one default constructor, namely the following.
Choice choice = new Choice()
Method Notes
void select(String str) Highlight the first cell with text equal to str
import java.awt.*;
import java.awt.event.*; f.add(c);
public class CE implements f.add(label);
ActionListener
f.add(b);
{
Frame f;
f.setSize(400, 400);
Label label;
f.setLayout(null);
Button b;
f.setVisible(true);
Choice c;
CE()
b.addActionListener(this);
{
}
f = new Frame();
Label = new Label();
public void
label.setAlignment(Label.CEN actionPerformed(ActionEvent e)
TER);
{
label.setSize(400, 100);
String data = "Programming
language Selected: "+
c.getItem(c.getSelectedIndex());
b = new Button("Show");
label.setText(data);
b.setBounds(200, 100, 50, 20);
}
c = new Choice();
public static void main(String args[])
c.setBounds(100, 100, 75, 75);
{
new ChoiceExample2();
c.add("C");
}
c.add("C++");
}
c.add("Java");
c.add("PHP");
c.add("Android");
Event Handling in Java:
Event handling is prime to Java programming because it’s integral to the
creation of applets and other sorts of GUI-based programs. Events are
supported by a variety of packages, including java.util, java.awt, and
java.awt.event. The program response is generated when the user interacts with
a GUI-based program.
User interaction with the elements of Graphical User Interface (GUI) of a Java
program leads to events. These elements could be a button, checkbox, radio
button, menu, list, table, scrollbar, mouse, window etc. Such elements are
also known as source of an event and there is a specific class corresponding to
each source and each event.
Source
Listener
Source
Interaction with a source generates
an event, which is an object of event class
describing the current state of source. A
source must register the listener class that wishes to listen and respond to its
event, by calling a method, which has a general form of
Each of the key event handling methods takes a keyEvent object is its
arguments.
A class to listen and respond to a KeyEvent, must perform the next two
steps -
Method Description
Method Description
public int getX() Returns the x-coordinate of the MouseEvent.
public int getY() Returns the y-coordinate of the MouseEvent.
A class to listen & respond to a MouseEvent, must perform the next two
steps -
It should implement an interface, MouseListener, by providing an
implementation of its methods -
Method Description
public void
This method is called when a mouse button is
mouseReleased(MouseEvent
released.
me)
public void This method is called when a mouse cursor exists the
mouseExited(MouseEvent me) window.
Method Description
Method Description
Method Description
java.awt.BorderLayout
java.awt.FlowLayout
java.awt.GridLayout
java.awt.CardLayout
java.awt.GridBagLayout
javax.swing.BoxLayout
javax.swing.GroupLayout
javax.swing.ScrollPaneLayout
javax.swing.SpringLayout etc.
Java BorderLayout
// creating buttons
Button b1 = new Button("NORTH");; // the button will be labeled as NORTH
Button b2 = new Button("SOUTH");; // the button will be labeled as SOUTH
Button b3 = new Button("EAST");; // the button will be labeled as EAST
Button b4 = new Button("WEST");; // the button will be labeled as WEST
Button b5 = new Button("CENTER");; // the button will be labeled as CENTER
f.setSize(300, 300);
f.setVisible(true);
}
public static void main(String[] args)
{
new BLManager();
}
}
Grid Layout Manager
The grid layout manager divides the container into a grid, so that components
can be placed in rows and columns. Each component will have the same width
and height. The components are added to the grid starting at the top-left cell
and proceeding left-to-right, until the row is full. Then go to the next row. This
type of layout is known as, the Grid Layout Manager.
There are 3 types of constructor in Grid Layout. They are as following:
GridLayout()
GridLayout(int rows, int columns)
GridLayout(int rows, int columns, inthgap, int vgap)
import java.awt.*;
GridDemo()
{
frame1=new Frame();
frame1.add(box1);
frame1.add(box2);
frame1.add(box3);
frame1.add(box4);
frame1.add(box5);
frame1.add(box6);
frame1.add(box7);
frame1.add(box8);
frame1.add(box9);
frame1.setLayout(new GridLayout(3,3));
frame1.setSize(500,500);
frame1.setVisible(true);
}
public static void main(String[] args)
{
new GridDemo();
}
}
Flow Layout manager
The flow layout, is the most basic layout manager in which components are
placed from left to right, as they were added. When the horizontal row is too
small, to put all the components in one row, then it uses multiple rows. You can
align the components left, right, or center (default).
Notice that FlowLayout is the default layout of Panel container.
There are 3 types of constructor in the Flow Layout. They are as following:
FlowLayout()
FlowLayout(int align)
FlowLayout(int align, inthgap, intvgap)
import java.awt.*;
frame1=new Frame();
frame1.add(box1);
frame1.add(box2);
frame1.add(box3);
frame1.add(box4);
frame1.add(box5);
frame1.setLayout(new FlowLayout());
frame1.setSize(300,300);
frame1.setVisible(true);
}
public static void main(String[] args)
{
new FlowDemo();
}
}
CardLayout Manager
CardLayout manager is used to position the components in a manner of deck
of cards, with only the card at the top of deck is visible at a time. All the
components of CardLayout Manager are of the type - JPanel and they are
contained in a main parent JPanel container. The layout manager of this main
parent JPanel is set to CardLayout manager.
Constructors of CardLayout
Constructor Description
public
Creates a CardLayout with a specified number of
CardLayout(int hGap,
gap between the components.
int vGap)
CardLayout methods
Methods Description
public void last(Component This method flips to the last card in the
comp) container.
public void
This method shows a specific card in the
show(Component
container with a specific name.
comp,String name)
public void setHgap(int This method sets the horizontal space between
horizontalGap) components.
public void setVgap(int This method sets the vertical space between
verticalGap) components.
CardLayout crd;
CardLayoutExample1()
{
cPane = getContentPane();
//default constructor used therefore, components will cover the whole area
crd = new CardLayout();
cPane.setLayout(crd);
// adding listeners to it
btn1.addActionListener(this);
btn2.addActionListener(this);
btn3.addActionListener(this);
crd.next(cPane);
}
crdl.setSize(300, 300);
crdl.setVisible(true);
crdl.setDefaultCloseOperation(EXIT_ON_CLOSE);
}
}
GridBagLayout Manager
Constructors of GridBagLayout
Constructor Description
int ipadx Specifies the extra horizontal space around the component.
int ipady Specifies the extra vertical space around the component.
int gridheight Specifies the height of the component.
Methods Description
setSize(300, 300);
setPreferredSize(getSize());
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
}
Menu, MenuItems and MenuBar class
A menu bar can be created
using MenuBar class.
Constructor Description
An interface in Java is syntactically similar to a class but can have only abstract
methods declaration and constants as members.
In other words, an interface is a collection of abstract methods and constants (i.e.
static and final fields). It is used to achieve complete abstraction.
Every interface in java is abstract by default. So, it is not compulsory to write
abstract keyword with an interface.
Once an interface is defined, we can create any number of separate classes and can
provide their own implementation for all the abstract methods defined by an interface.
A class that implements an interface is called implementation class. A class can
implement any number of interfaces in Java.
Every implementation class can have its own implementation for abstract methods
specified in the interface as shown in the below figure.
Since the implementation classes will have all the methods with a body, it is possible to
create an instance of implementation classes.
Therefore, all the variables declared in an interface are considered as public, static, and
final by default and acts like constant. We cannot change their value once they
initialized.
Features of Interface
There are the following features of an interface in Java. They are as follows:
1. Interface provides pure abstraction in Java. It also represents the Is-A
relationship.
2. It can contain three types of methods: abstract, default, and static methods.
3. All the (non-default) methods declared in the interface are by default abstract and
public. So, there is no need to write abstract or public modifiers before them.
4. The fields (data members) declared in an interface are by default public, static,
and final. Therefore, they are just public constants. So, we cannot change their
value by implementing class once they are initialized.
5. Interface cannot have constructors.
6. The interface is the only mechanism that allows achieving multiple inheritance
in java.
7. A Java class can implement any number of interfaces by using keyword
implements.
8. Interface can extend an interface and can also extend multiple interfaces.
Here are some key points for defining an interface in Java that must be kept in mind.
The rules are as follows:
1. An interface cannot be instantiated directly. But we can create a reference to an
interface that can point to an object of any of its derived types implementing it.
2. An interface may not be declared with final keyword.
3. It cannot have instance variables. If we declare a variable in an interface, it must
be initialized at the time of declaration.
4. A class that implements an interface, must provide its own implementations of
all the methods defined in the interface.
5. We cannot reduce the visibility of an interface method while overriding. That is,
when we implement an interface method, it must be declared as public.
6. It can also be declared with an empty body (i.e. without any members). For
example, java.util package defines EventListener interface without a body.
7. An interface can be declared within another interface or class. Such interfaces
are called nested interfaces in Java.
8. A top-level interface can be public or default with the abstract modifier in its
definition. Therefore, an interface declared with private, protected, or final will
generate a compile-time error.
9. All non-default methods defined in an interface are abstract and public by
default. Therefore, a method defined with private, protected, or final in an
interface will generate compile-time error.
10. If you add any new method in interface, all concrete classes which implement
that interface must provide implementations for newly added method because all
methods in interface are by default abstract.
Like classes, an interface can also extend another interface. This means that an
interface can be sub interfaces from other interfaces.
The new sub-interface will inherit all members of the super interface similar to
subclasses. It can be done by using the keyword “extends”. It has the following general
form:
Syntax:
interface interfaceName2 extends interfaceName1
{
// body of interfaceName2.
}
Look at the below figure a, b, c, and d to understand better.
Let’s understand the extending interface better with the help of different examples.
1. We can define all the constants in one interface and methods in another interface.
We can use constants in classes where methods are not required. Look at the example
below.
interface A
{
int x = 10;
int y = 20;
}
interface B extends A
{
void show();
}
The interface B would inherit both constants x and y into it.
2. We can also extend various interfaces together by a single interface. The general
declaration is given below:
interface A
{
int x = 20;
int y = 30;
}
interface B extends A
{
void show();
}
interface C extends A, B
{
........
}
Key points:
1. An interface cannot extend classes because it would violate rules that an interface
can have only abstract methods and constants.
2. An interface can extend Interface1, Interface2.
The interface is also used to declare a set of constants that can be used in multiple
classes. The constant values will be available to any classes that implement interface
because it is by default public, static, and final.
We can use values in any method as part of the variable declaration or anywhere in the
class.
Java Interface Example Programs
Program code 1:
public interface ConstantValues
{
// Declaration of interface variables.
int x = 20;
int y = 30;
}
public class Add implements ConstantValues
{
int a = x;
int b = y;
void m1()
{
System.out.println("Value of a: " +a);
System.out.println("Value of b: " +b);
}
void sum()
{
int s = x + y;
System.out.println("Sum: " +s);
}
}
public class Sub implements ConstantValues
{
void sub()
{
int p = y - x;
System.out.println("Sub: " +p);
}
}
public class Test
{
public static void main(String[] args)
{
Add a = new Add();
a.m1();
a.sum();
Sub s = new Sub();
s.sub();
}
}
Output:
Value of a: 20
Value of b: 30
Sum: 50
Sub: 10
Program code 2:
public interface A
{
void msg(); // No body.
}
public class B implements A
{
public void msg()
{
System.out.println("Hello Java");
}
void show()
{
System.out.println("Welcome you");
}
public static void main(String[] args)
{
B b = new B();
b.msg();
b.show(); // A reference of interface is pointing to objects of class B.
A a = new B();
a.msg();
When two or more classes implement the same interface with different implementations,
then through the object of each class, we can achieve polymorphic behavior for a given
interface. This is called polymorphism in interface.
In the above figure, (d) shows polymorphism in interfaces where class B and class C
implement the same interface A.
Program code 3:
public interface Rectangle
{
void calc(int l, int b); // no body.
}
public class RecArea implements Rectangle
{
public void calc(int l, int b)
{
int area = l * b; // Implementation.
System.out.println("Area of rectangle = "+area);
}
}
public class RecPer implements Rectangle
{
public void calc(int l, int b)
{
int perimeter = 2 * (l + b); // Implementation.
System.out.println("Perimeter of rectangle = "+perimeter);
}
}
public class Execution {
public static void main(String[] args)
{
Rectangle rc; // Creating an interface reference.
rc = new RecArea(); // Creating object of RecArea.
rc.calc(20, 30); // calling method.
When a class implements more than one interface, or an interface extends more than
one interface, it is called multiple inheritance. Various forms of multiple inheritance
are shown in the following figure.
Program code 5:
public interface Home
{
void homeLoan();
}
public interface Car
{
void carLoan();
}
public interface Education
{
void educationLoan();
}
public class Loan implements Home, Car, Education
{
// Multiple inheritance using multiple interfaces.
public void homeLoan()
{
System.out.println("Rate of interest on home loan is 8.5%");
}
public void carLoan()
{
System.out.println("Rate of interest on car loan is 9.25%");
}
public void educationLoan()
{
System.out.println("Rate of interest on education loan is 10.45%");
}
public static void main(String[] args)
{
Loan l = new Loan();
l.homeLoan();
l.carLoan();
l.educationLoan();
}
}
Output:
Rate of interest on home loan is 8.5%
Rate of interest on car loan is 9.25%
Rate of interest on education loan is 10.45%
What is a Java String?
In Java, string is basically an object that represents sequence of char values.
An array of characters works same as Java string. The java.lang.String class
is used to create a Java string object.
For example:
char[] ch={'j','a','v','a','t','p','o','i','n','t'};
String s=new String(ch);
is same as:
String s="javatpoint";
String exampleString=”java”
Each time when we will create string literal, new String object created in String
pool .string value stored in string pool. String pool space is located inside
heap, because of lot use of strings when new string create as string literal.
Java firstly check string pool for string value, if string value exist in string pool
then return reference for that string value, if value not exist then new string
will create inside string pool and return reference for new string value.
If you are creating a new String object by using new operator, then string pool
check will not perform and string object will create in heap memory.
String Methods
Constructor Description
package com.journaldev.java;
Output:
sb.append("World ");
sb.append(2017);
System.out.println(sb);
4. insert(): insert() method takes two parameters – the index integer value to insert
a value and the value to be inserted. The index tells StringBuffer where to insert
the passed character sequence. Again this method is overloaded to work with
primitive data types and Objects.
sb.insert(sb.length(), 2017);
System.out.println(sb);
5. reverse(): Reverses the existing String or character sequence content in the buffer
and returns it. The object must have an existing content or else
a NullPointerException is thrown.
System.out.println(sb.reverse());
8. replace(int startIndex, int endIndex, String str): Accepts three arguments: first
two being the starting and ending index of the existing String Buffer. Therefore
the character sequence between startIndex and endIndex–1 are removed. Then
the String passed as third argument is inserted at startIndex.
Constructors:
If the flag is false, delimiter characters serve to separate tokens. For example,
if string is "hello geeks" and delimiter is " ", then tokens are "hello" and "geeks".
If the flag is true, delimiter characters are considered to be tokens. For example,
if string is "hello geeks" and delimiter is " ", then tokens are "hello", " " and
"geeks".
Introduction to Java I/O:
Java I/O (Input and Output) is used to process the input and produce
the output.
Java brings various Streams with its I/O package that helps the
user to perform all the input-output operations. These streams
support all the types of objects, data-types, characters, files etc.,
to fully execute the I/O operations.
Stream:
A stream is a sequence of data. In Java a stream is composed of bytes. A stream
is a way of sequentially accessing a file. It's called a stream because it is like a
stream of water that continues to flow.
Programs read inputs from data sources (e.g., keyboard, file, network,
memory buffer, or another program) and write outputs to data sinks (e.g.,
display console, file, network, memory buffer, or another program). In Java
standard I/O, inputs and outputs are handled by the so-called streams.
A stream is a sequential and contiguous one-way flow of data (just like
water or oil flows through the pipe). It is important to mention that Java does
not differentiate between the various types of data sources or sinks (e.g.,
file or network) in stream I/O. They are all treated as a sequential flow of
data. Input and output streams can be established from/to any data
source/sink, such as files, network, keyboard/console or another program. The
Java program receives data from a source by opening an input stream, and
sends data to a sink by opening an output stream. All Java I/O streams are
one-way (except the RandomAccessFile). If your program needs to perform both
input and output, you have to open two streams - an input stream and an
output stream.
Stream I/O operations involve three steps:
1. Open an input/output stream associated with a physical device (e.g., file,
network, console/keyboard), by constructing an appropriate I/O stream
instance.
2. Read from the opened input stream until "end-of-stream" encountered,
or write to the opened output stream (and optionally flush the buffered
output).
3. Close the input/output stream.
System.out: standard
output stream
System.err: standard
error stream
System.in: This is the standard input stream that is used to read characters
from the keyboard or any other standard input device.
System.out: This is the standard output stream that is used to produce the
result of a program on an output device like the computer screen.
Here is a list of the various print functions that we use to output statements:
print(): This method in Java is used to display a text on the console. This text is
passed as the parameter to this method in the form of String. This method prints
the text on the console and the cursor remains at the end of the text at the
console. The next printing takes place from just here.
Syntax:
System.out.print(parameter);
Example:
println(): This method in Java is also used to display a text on the console. It
prints the text on the console and the cursor moves to the start of the next line
at the console. The next printing takes place from the next line.
Syntax:
System.out.println(parameter);
Example:
printf(): This is the easiest of all methods as this is similar to printf in C. Note
that System.out.print() and System.out.println() take a single argument, but
printf() may take multiple arguments. This is used to format the output in Java.
Example:
System.err: This is the standard error stream that is used to output all the error
data that a program might throw, on a computer screen or any standard output
device.
This stream also uses all the 3 above-mentioned functions to output the error
data:
print()
println()
printf()
Example:
Types of Streams:
Depending on the type of operations, streams can be divided into two primary
classes:
InputStream
Java application uses an input stream to read data from a source, it may be
a file, an array, peripheral device or socket.
OutputStrem
Java application uses an output stream to write data to a destination, it
may be a file, an array, peripheral device or socket.
InputStream class
InputStream class is an abstract class. It is the super class of all classes
representing an input stream of bytes.
Methods of InputStream
Method Description
public abstract int reads the next byte of data from the input
read()throws IOException stream. It returns -1 at the end of file.
InputStream Hierarchy
OutputStream class
OutputStream class is an abstract class. It is the super class of all classes
representing an output stream of bytes. An output stream accepts output
bytes and sends them to some sink.
Methods of OutputStream:
Method Description
OutputStream Hierarchy
Byte Streams and Character Streams:
Java provides I/O Streams to read and write data where, a Stream represents
an input source or an output destination which could be a file, i/o devise, other
program etc.
Based on the data they handle there are two types of streams −
Byte Streams − These handle data in bytes (8 bits) i.e., the byte stream
classes read/write data of 8 bits. Using these you can store characters,
videos, audios, images etc.
Character Streams − These handle data in 16 bit Unicode. Using these
you can read and write text data only.
The Reader and Writer classes (abstract) are the super classes of all the character
stream classes: classes that are used to read/write character streams.
Whereas the InputStream and OutputStream classes (abstract) are the super
classes of all the input/output stream classes: classes that are used to
read/write a stream of bytes.
Following diagram illustrates all the input and output Streams (classes) in Java.
Difference between input/output Streams and Readers/Writers
The major difference between these is that the input/output stream classes
read/write byte stream data. Whereas the Reader/Writer classes handle
characters.
The methods of input/output stream classes accept byte array as parameter
whereas the Reader/Writer classes accept character array as parameter.
The Reader/Writer classes handles all the Unicode characters, comes handy for
internalization, comparatively efficient that input/output streams.
public int read(byte[] bytes, int offset, int length) throws IOException
// Read "length" number of bytes, store in bytes array starting from offset of
index.
Writing to an OutputStream
Similar to the input counterpart,
the abstract superclass OutputStream declares an abstract method write() to
write a data-byte to the output sink. write() takes an int. The least-significant
byte of the int argument is written out; the upper 3 bytes are discarded. It throws
an IOException if I/O error occurs (e.g., output stream has been closed).
public void write(byte[] bytes, int offset, int length) throws IOException
// Write "length" number of bytes, from the bytes array starting from offset of
index.
public void write(byte[] bytes) throws IOException
// Same as write(bytes, 0, bytes.length)
You open an I/O stream by constructing an instance of the stream. Both the InputStream and
the OutputStream provides a close() method to close the stream, which performs the necessary
clean-up operations to free up the system resources.
public void close() throws IOException // close this Stream
Flushing the OutputStream
In addition, the OutputStream provides a flush() method to flush the remaining bytes from the
output buffer.
public void flush() throws IOException // Flush the output
InputStream and OutputStream are abstract classes that cannot be instantiated. You need to choose
an appropriate concrete subclass to establish a connection to a physical device. For example, you can
instantiate a FileInputStream or FileOutputStream to establish a stream to a physical disk file.
Constructors:
• Vector(int size, int incr): Creates a vector whose initial capacity is specified by size
and increment is specified by incr. It specifies the number of elements to allocate
each time that a vector is resized upward.
boolean equals(Object o): Compares the specified Object with this vector for equality.
Object firstElement(): Returns the first component (the item at index 0) of this vector.
Object get(int index): Returns the element at the specified position in this vector.
int indexOf(Object elem): Searches for the first occurence of the given argument, testing for equality using the equals
method.
int indexOf(Object elem, int index): Searches for the first occurence of the given argument, beginning the search at
index, and testing for equality using the equals method.
void insertElementAt(Object obj, int index): Inserts the specified object as a component in this vector at the specified
index.
Method & Description
boolean isEmpty(): Tests if this vector has no components.
Object lastElement(): Returns the last component of the vector.
int lastIndexOf(Object elem): Returns the index of the last occurrence of the specified object in this
vector.
int lastIndexOf(Object elem, int index): Searches backwards for the specified object, starting from the
specified index, and returns an index to it.
Object remove(int index): Removes the element at the specified position in this vector.
boolean remove(Object o): Removes the first occurrence of the specified element in this vector, If the
vector does not contain the element, it is unchanged.
boolean removeAll(Collection c): Removes from this vector all of its elements that are contained in the
specified Collection.
void removeAllElements(): Removes all components from this vector and sets its size to zero.
boolean removeElement(Object obj): Removes the first (lowest-indexed) occurrence of the argument from
this vector.
int size(): Returns the number of components in this vector.
Example
Java Stack
The stack is a linear data structure that is used to store the collection of objects.
It is based on Last-In-First-Out (LIFO). Java collection framework provides
many interfaces and classes to store the collection of objects. One of them is
the Stack class that provides different operations such as push, pop, search,
etc.
Creating a Stack
To create a stack, first, import the java.util package and create an object of the
Stack class.
Java Stack extends Vector class with the following five operations only.
import java.util.*;
public class st
{
public static void main(String[] args)
{
Stack<String> stk= new Stack<>();
//pushing elements into Stack
stk.push("Mac Book");
stk.push("HP");
stk.push("DELL");
stk.push("Asus");
Output
Constructor Description
Method Description
void forEach(BiConsumer<? super It performs the given action for each entry
K,? super V> action) in the map until all entries have been
processed or the action throws an
exception.
V getOrDefault(Object key, V It returns the value to which the specified
defaultValue) key is mapped, or defaultValue if the map
contains no mapping for the key.
int hashCode() It returns the hash code value for the Map
void putAll(Map<? extends K,? It is used to copy all the key-value pair
extends V> t)) from map to hashtable.
boolean remove(Object key, Object It removes the specified values with the
value) associated specified keys from the
hashtable.
boolean replace(K key, V oldValue, It replaces the old value with the new
V newValue) value for a specified key.
void replaceAll(BiFunction<? super It replaces each entry's value with the
K,? super V,? extends V> function) result of invoking the given function on
that entry until all entries have been
processed or the function throws an
exception.
boolean containsKey(Object key) This method return true if some key equal
to the key exists within the hash table,
else return false.
Constructors
Built-in Methods
The most frequently used built-in methods for generating random
numbers, are the following:
System.out.printf("]\n");
System.out.println(random.nextLong());
System.out.println(random.nextInt());
}
}
Output
5
true
0.09507979119059662
0.8763395
-2.1809846422230037
[-126 -31 18 -10 -99 34 -39 84 68 -115 ]
-2755864444256421329
-1335486132
Calendar Class in Java with examples
Calendar class in Java is an abstract class that provides methods for converting
date between a specific instant in time and a set of calendar fields such as
MONTH, YEAR, HOUR, etc. It inherits Object class and implements the
Comparable, Serializable, Cloneable interfaces.
Class declaration
Following is the declaration for java.util.Calendar class:
public abstract class Calendar
extends Object
implements Serializable, Cloneable, Comparable<Calendar>
DESCRIPTION
METHOD
Class methods
String getSymbol(): This method gets the symbol of this currency for the
default locale.
remove(K key): removes the key-value pair that was mapped with the
specified key.
get(K key): returns the value that was mapped to the specified key.
The proxy server is a computer on the internet that accepts the incoming requests from the
client and forwards those requests to the destination server. It works as a gateway between the
end-user and the internet. It has its own IP address. It separates the client system and web
server from the global network.
Mechanism of Proxy Server
The following figure depicts the mechanism of the proxy server.
Therefore, it can be said that the proxy server acts as a client as well as the server.
Java Networking
Java Networking is a concept of connecting two or more computing devices together so that we
can share resources.
Java socket programming provides facility to share data between different computing devices.
● IP Address
● Protocol
● Port Number
● MAC Address
● Connection-oriented and connection-less protocol
● Socket
IP Address
Protocol
A protocol is a set of rules basically that is followed for communication. For example:
TCP
FTP
Telnet
SMTP
POP etc.
Port Number
The port number is used to uniquely identify different applications. It acts as a communication
endpoint between applications.
The port number is associated with the IP address for communication between two applications.
MAC Address
MAC (Media Access Control) address is a unique identifier of NIC (Network Interface
Controller). A network node can have multiple NIC but each with unique MAC address.
Socket
A socket is an endpoint between two way communications.
What is JavaScript?
JavaScript is a light-weight object-oriented programming language which is
used by several websites for scripting the webpages. It is an interpreted, full-
fledged programming language that enables dynamic interactivity on
websites when applied to an HTML document.
JavaScript was developed by Brendan Eich in 1995. It was introduced to adding
programs to the webpages in the Netscape Navigator browser. Since sthen, it
has been adopted by all other graphical web browsers. With JavaScript,
users can build modern web applications to interact directly without
reloading the page every time. The traditional website uses to provide several
forms of interactivity and simplicity.
Being a scripting language, JavaScript cannot run on its own. In fact, the
browser is responsible for running JavaScript code. When a user requests an
HTML page with JavaScript in it, the script is sent to the browser and it is up to
the browser to execute it. The main advantage of JavaScript is that all modern
web browsers support (Internet Explorer, Google Chrome, Firefox or any other
browser). Also, JavaScript runs on any operating system including
Windows, Linux or Mac. Thus, JavaScript overcomes the main disadvantages
of VBScript (Now deprecated) which is limited to just IE and Windows.
Although, JavaScript has no connectivity with Java programming language.
The name was suggested and provided in the times when Java was gaining
popularity in the market. In addition to web browsers, databases such as
CouchDB and MongoDB uses JavaScript as their scripting and query
language.
Advantages of JavaScript
Speed - JavaScript tends to be very fast because it is often run
immediately within the client's browser. So long as it doesn't require
outside resources, JavaScript isn't slowed down by calls to a backend
server. Also, major browsers all support JIT (just in time) compilation for
JavaScript, meaning that there's no need to compile the code before
running it.
Simplicity - JavaScript's syntax was inspired by Java's and is relatively
easy to learn compared to other popular languages like C++.
Popularity - JavaScript is everywhere on the web, and with the advent of
Node.js, is increasingly used on the backend. There are countless
resources to learn JavaScript. Both StackOverflow and GitHub show an
increasing amount of projects that use JavaScript, and the traction it's
gained in recent years is only expected to increase.
Interoperability - Unlike PHP or other scripting languages, JavaScript
can be inserted into any web page. JavaScript can be used in many
different kinds of applications because of support in other languages like
Pearl and PHP.
Server Load - JavaScript is client-side, so it reduces the demand on
servers overall, and simple applications may not need a server at all.
Rich interfaces - JavaScript can be used to create features like drag and
drop and components such as sliders, all of which greatly enhance the
user interface and experience of a site.
Extended Functionality - Developers can extend the functionality of web
pages by writing snippets of JavaScript for third party add-ons like
Greasemonkey.
Versatility - There are many ways to use JavaScript through Node.js
servers. If you were to bootstrap Node.js with Express, use a document
database like MongoDB, and use JavaScript on the frontend for clients, it
is possible to develop an entire JavaScript app from front to back using
only JavaScript.
Updates - Since the advent of ECMAScript 5 (the scripting specification
that JavaScript relies on), ECMA International has been dedicated to
updating JavaScript annually. So far, we have received browser support
for ES6 in 2017 and look forward to ES7 being supported in the future.
Disadvantages of JavaScript
Client-Side Security - Since JavaScript code is executed on the client-
side, bugs and oversights can sometimes be exploited for malicious
purposes. Because of this, some people choose to disable JavaScript
entirely.
Browser Support - While server-side scripts always produce the same
output, different browsers sometimes interpret JavaScript code differently.
These days the differences are minimal, and you shouldn't have to worry
about it as long as you test your script in all major browsers.
JavaScript Example:
Javascript example is easy to code. JavaScript provides 3 places to put the
JavaScript code: within body tag, within head tag and external JavaScript file.
Let’s create the first JavaScript example.
<script type="text/javascript">
document.write("JavaScript is a simple language for javatpoint learners");
</script>
In the above example, we have displayed the dynamic content using JavaScript.
Let’s see the simple example of JavaScript that displays alert dialog box.
<body>
<p>Welcome to JavaScript</p>
<script type="text/javascript">
alert("Hello Javatpoint");
</script>
</body>
Code between the head tag
Let’s see the same example of displaying alert dialog box of JavaScript that is
contained inside the head tag.
To call function, you need to work on event. Here we are using onclick event to
call msg() function.
<html>
<head>
<script type="text/javascript">
function msg()
{
alert("Hello Javatpoint");
}
</script>
</head>
<body>
<p>Welcome to JavaScript</p>
<form>
<input type="button" value="click" onclick="msg()"/>
</form>
</body>
</html>
We can create external JavaScript file and embed it in many html page.
Let's create an external JavaScript file that prints Hello Javatpoint in a alert
dialog box.
message.js
function msg()
{
alert("Hello Javatpoint");
}
Let's include the JavaScript file into html page. It calls the JavaScript
function on button click.
index.html
<html>
<head>
<script type="text/javascript" src="message.js"></script>
</head>
<body>
<p>Welcome to JavaScript</p>
<form>
<input type="button" value="click" onclick="msg()"/>
</form>
</body>
</html>
The stealer may download the coder's code using the url of the js file.
If two js files are dependent on one another, then a failure in one file
may affect the execution of the other dependent file.
The web browser needs to make an additional http request to get the js
code.
A tiny to a large change in the js code may cause unexpected results in
all its dependent files.
We need to check each file that depends on the commonly created
external javascript file.
If it is a few lines of code, then better to implement the internal
javascript code.
JavaScript Comment
1. Single-line Comment
2. Multi-line Comment
It is represented by double forward slashes (//). It can be used before and after
the statement.
Let’s see the example of single-line comment i.e. added before the statement.
<script>
// It is single line comment
document.write("hello javascript");
</script>
Let’s see the example of single-line comment i.e. added after the statement.
<script>
var a=10;
var b=20;
var c=a+b;//It adds values of a and b variable
document.write(c);//prints sum of 10 and 20
</script>
It can be used to add single as well as multi line comments. So, it is more
convenient.
It is represented by forward slash with asterisk then asterisk with forward slash.
For example:
JavaScript Variable
A JavaScript variable is simply a name of storage location. There are two types
of variables in JavaScript: local variable and global variable.
There are some rules while declaring a JavaScript variable (also known as
identifiers).
In JavaScript, we use the following keywords to declare variables: var and let. For
example,
var x;
let y;
Both var and let are used to declare variables. However, there are some
differences between them.
Var let
Note: It is recommended to use let instead of var. However, there are a few
browsers that do not support let. Visit JavaScript let browser support to learn
more
let x;
x = 5;
let x = 5;
let y = 6;
In JavaScript, it's possible to declare variables in a single statement.
let x = 5, y = 6, z = 7;
If you use a variable without initializing it, it will have an undefined value.
Here x is the variable name and since it does not contain any value, it will be
undefined.
It's possible to change the value stored in the variable. For example,
// 5 is assigned to variable x
let x = 5;
document.write(x); // 5
// variable x is changed 3
x = 3;
document.write(x); // 3
Variable names must start with either a letter, an underscore _, or the dollar
sign $. For example,
//valid
let a = 'hello';
let _a = 'hello;
let $a = 'hello';
//invalid
Let 1a = 'hello'; // this gives an error
let y = "hi";
let Y = 5;
document.write(y); // hi
document.write(Y); // 5
//invalid
let new = 5; // Error! new is a keyword.
Notes:
Though you can name variables in any way you want, it's a good practice to
give a descriptive variable name. If you are using a variable to store the number
of apples, it better to use apples or numberOfApples rather than x or n.
In JavaScript, the variable names are generally written in camelCase if it has
multiple words. For example, firstName, annualSalary, etc.
JavaScript Constants
The const keyword was also introduced in the ES6(ES2015) version to create
constants. For example,
const x = 5;
const x = 5;
x = 10; // Error! constant cannot be changed.
document.write(x)
Also, you cannot declare a constant without initiating it. For example,
Note: If you are sure that the value of a variable won't change throughout the
program, it's recommended to use const. However, there are a few browsers
that do not support const. Visit JavaScript const browser support to learn
more.
Example of JavaScript variable
<script>
var x = 10;
var y = 20;
var z=x+y;
document.write(z);
</script>
<script>
function abc()
{
var x=10;//local variable
}
</script>
Or,
<script>
if(10<13)
{
var y=20;//JavaScript local variable
}
</script>
<script>
var data=200;//gloabal variable
function a()
{
document.writeln(data);
}
function b()
{
document.writeln(data);
}
<script>
var value=50;//global variable
function a()
{
alert(value);
}
function b()
{
alert(value);
}
</script>
To declare JavaScript global variables inside function, you need to use window
object. For example:
window.value=90;
Now it can be declared inside any function and can be accessed from any
function. For example:
function m()
{
window.value=100;//declaring global variable by window object
}
function n()
{
alert(window.value);//accessing global variable from other function
}
When you declare a variable outside the function, it is added in the window object
internally. You can access it through window object also. For example:
var value=50;
function a()
{
alert(window.value);//accessing global variable
}
Javascript Data Types
JavaScript provides different data types to hold different types of values. There
are two types of data types in JavaScript.
JavaScript is a dynamic type language, means you don't need to specify type
of the variable because it is dynamically used by JavaScript engine. You need to
use var here to specify the data type. It can hold any type of values such as
numbers, strings etc.
There are five types of primitive data types in JavaScript. They are as follows:
Data Description
Type
JavaScript String
For example,
//strings example
let name = 'ram';
let name1 = "hari";
let result = `The names are ${name} and ${name1}`;
Single quotes and double quotes are practically the same and you can use either
of them.
Backticks are generally used when you need to include variables or expressions
into a string. This is done by wrapping variables or expressions with ${variable
or expression} as shown above.
JavaScript Number
let number1 = 3;
let number2 = 3.433;
let number3 = 3e5 // 3 * 10^5
A number type can also be +Infinity, -Infinity, and NaN (not a number). For
example,
let number1 = 3/0;
document.write(number1); // returns Infinity
JavaScript BigInt
In JavaScript, Number type can only represent numbers less than (253 - 1) and
more than -(253 - 1). However, if you need to use a larger number than that, you
can use the BigInt data type.
// BigInt value
let value = 900719925124740998n;
Output
900719925124740999n
Uncaught TypeError: Cannot mix BigInt and other types
Note: BigInt was introduced in the newer version of JavaScript and is not
supported by many browsers including Safari. Visit JavaScript BigInt support to
learn more.
JavaScript Boolean
This data type represents the logical entity. Boolean represents one of two
values: true or false. It is easier to think of it as a yes/no switch. For example,
JavaScript undefined
let name;
document.write(name); // returns undefined
JavaScript null
This data type was introduced in a newer version of JavaScript (from ES2015).
Though value1 and value2 both contain 'hello', they are different as they are of
the Symbol type.
Visit JavaScript Symbol to learn more.
JavaScript Object
An object is a complex data type that allows us to store collections of data. For
example,
let student = {
firstName: 'ram',
lastName: null,
class: 10
};
JavaScript Type
It also means that a variable can be of one data type and later it can be changed
to another data type. For example,
// data is of undefined type
let data;
JavaScript typeof
To find the type of a variable, you can use the typeof operator. For example,
let number = 4;
typeof(number); //returns "number"
let a = null;
typeof(a); // returns "object"
Notice that typeof returned "object" for the null type. This is a known issue in
JavaScript since its first release.
JavaScript Operators
In this tutorial, you will learn about different operators available in JavaScript
and how to use them with the help of examples.
What is an Operator?
2 + 3; // 5
Assignment Operators
Arithmetic Operators
Comparison Operators
Logical Operators
Bitwise Operators
String Operators
Other Operators
JavaScript Assignment Operators
let x = 5;
= Assignment operator a = 7; // 7
+= Addition assignment a += 5; // a = a + 5
-= Subtraction Assignment a -= 2; // a = a - 2
*= Multiplication Assignment a *= 3; // a = a * 3
/= Division Assignment a /= 2; // a = a / 5
%= Remainder Assignment a %= 2; // a = a % 2
Note: The commonly used assignment operator is =. You will understand other
assignment operators such as +=, -=, *= etc. once we learn arithmetic operators.
JavaScript Arithmetic Operators
let number = 3 + 5; // 8
+ Addition x+y
- Subtraction x-y
* Multiplication x*y
/ Division x/y
% Remainder x%y
** Exponentiation (Power) x ** y
let x = 5;
let y = 3;
// addition
document.write('x + y = ', x + y);
// subtraction
document.write('x - y = ', x - y);
// multiplication
document.write('x * y = ', x * y);
// division
document.write('x / y = ', x / y);
// remainder
document.write('x % y = ', x % y);
// increment
document.write('++x = ', ++x); // x is now 6
document.write('x++ = ', x++); // x returns 6 and then increases by 1
document.write('x = ', x);
// decrement
document.write('--x = ', --x); // x is now 6
document.write('x-- = ', x--); // x returns 6 and then increases by 1
document.write('x = ', x);
//exponentiation
document.write('x ** y =', x ** y);
Output
x+y= 8
x-y= 2
x * y = 15
x / y = 1.6666666666666667
x%y=2
++x = 6
x++ = 6
x=7
--x = 6
x-- = 6
x=5
x ** y = 125
Note: The ** operator was introduced in EcmaScript 2016. And, some browsers
may not support the exponentiation operator. To learn more, visit JavaScript
exponentiation browser support.
let a = 3, b = 2;
document.write(a > b); // true
Here, the comparison operator > is used to compare whether a is greater than b.
// equal operator
document.write(2 == 2); // true
document.write(2 == '2'); // true
Output
true
true
true
true
true
false
false
true
Comparison operators are used in decision making and loops. You will learn
about the use of comparison operators in detail in the later tutorials.
let x = 5, y = 3;
(x < 6) && (y < 5); // true
Here, && is a logical operator AND. Since both x < 6 and y < 5 are true, the
result is true.
Operator Description Example
// logical AND
document.write(true && true); // true
document.write(true && false); // false
// logical OR
document.write(true || false); // true
// logical NOT
document.write(!true); // false
Output
true
false
true
false
Logical operators are used in decision making and loops. You will learn about
the use of logical operators in detail in the later tutorials.
| Bitwise OR
^ Bitwise XOR
~ Bitwise NOT
Bitwise operators are rarely used in everyday programming. If you are interested,
visit JavaScript Bitwise Operators to learn more.
In JavaScript, you can also use the + operator to concatenate (join) two or more
strings.
Example 4: String operators in JavaScript
// concatenation operator
document.write('hello' + 'world');
let a = 'JavaScript';
Output
helloworld
JavaScript tutorial
JavaScript if Statement
if (condition)
{
// the body of if
}
Example 1: if Statement
Output 1
Enter a number: 2
The number is positive
The if statement is easy
Suppose the user entered 2. In this case, the condition number > 0 evaluates
to true. And, the body of the if statement is executed.
Output 2
Enter a number: -1
The if statement is easy
Suppose the user entered -1. In this case, the condition number > 0 evaluates
to false. Hence, the body of the if statement is skipped.
Since document.write("The if statement is easy"); is outside the body of
the if statement, it is always executed.
Comparison and logical operators are used in conditions. So to learn more about
comparison and logical operators, you can visit JavaScript Comparison and
Logical Operators.
if (condition)
{
// block of code if condition is true
}
else
{
// block of code if condition is false
}
The if..else statement evaluates the condition inside the parenthesis.
If the condition is evaluated to true,
the code inside the body of if is executed
the code inside the body of else is skipped from execution
Output 1
Enter a number: 2
The number is positive
The if...else statement is easy
Suppose the user entered 2. In this case, the condition number > 0 evaluates
to true. Hence, the body of the if statement is executed and the body of
the else statement is skipped.
Output 2
Enter a number: -1
The number is either a negative number or 0
The if...else statement is easy
Suppose the user entered -1. In this case, the condition number > 0 evaluates
to false. Hence, the body of the else statement is executed and the body of
the if statement is skipped.
if (condition1)
{
// code block 1
}
else if (condition2)
{
// code block 2
}
else
{
// code block 3
}
Output
Enter a number: 0
The number is 0
The if...else if...else statement is easy
Suppose the user entered 0, then the first test condition number > 0 evaluates
to false. Then, the second test condition number == 0 evaluates to true and its
corresponding block is executed.
Nested if...else Statement
You can also use an if...else statement inside of an if...else statement. This is
also known as nested if...else statement.
Example 4: Nested if...else Statement
if (number >= 0)
{
if (number == 0)
{
document.write("You entered number 0");
}
else
{
document.write("You entered a positive number");
}
}
else
{
document.write("You entered a negative number");
}
Output
Enter a number: 0
You entered number 0
Suppose the user entered 0. In this case, the condition number > -1 evaluates
to true. Then the second condition number == 0 is checked which evaluates
to true and its corresponding body is executed.
Note: As you can see, nested if...else makes your logic complicated. If possible,
you should always try to avoid nested if...else.
Body of if...else With Only One Statement
If the body of if...else has only one statement, you can omit { } in the program.
For example, you can replace
let number = 2;
if (number > 0)
{
document.write("The number is positive.");
}
else
{
document.write("The number is negative or zero.");
}
with
let number = 2;
if (number > 0)
document.write("The number is positive.");
else
document.write("The number is negative or zero.");
Output
Note: Although it's not necessary to use { } if the body of if...else has only one
statement, using { } makes your code more readable.
JavaScript Switch
The JavaScript switch statement is used to execute one code from multiple
expressions. It is just like else if statement that we have learned in previous
page. But it is convenient than if..else..if because it can be used with numbers,
characters etc.
switch(expression)
{
case value1:
code to be executed;
break;
case value2:
code to be executed;
break;
......
default:
code to be executed if above values are not matched;
}
<script>
var grade='B';
var result;
switch(grade)
{
case 'A':
result="A Grade";
break;
case 'B':
result="B Grade";
break;
case 'C':
result="C Grade";
break;
default:
result="No Grade";
}
document.write(result);
</script>
B Grade
The switch statement is fall-through i.e. all the cases will be evaluated if you
don't use break statement.
<script>
var grade='B';
var result;
switch(grade)
{
case 'A':
result+=" A Grade";
case 'B':
result+=" B Grade";
case 'C':
result+=" C Grade";
default:
result+=" No Grade";
}
document.write(result);
</script>
JavaScript Loops
The JavaScript loops are used to iterate the piece of code using for, while, do
while or for-in loops. It makes the code compact. It is mostly used in array.
1. for loop
2. while loop
3. do-while loop
4. for-in loop
Here,
// looping from i = 1 to 5
for (let i = 1; i <= n; i++)
{
document.write(`I love JavaScript.`);
}
Output
I love JavaScript.
I love JavaScript.
I love JavaScript.
I love JavaScript.
I love JavaScript.
Condition: i <=
Iteration Variable Action
n
I love JavaScript. is
i=1
1st true printed.
n=5
i is increased to 2.
I love JavaScript. is
i=2
2nd true printed.
n=5
i is increased to 3.
I love JavaScript. is
i=3
3rd true printed.
n=5
i is increased to 4.
I love JavaScript. is
i=4
4th true printed.
n=5
i is increased to 5.
I love JavaScript. is
i=5
5th true printed.
n=5
i is increased to 6.
i=6
6th false The loop is terminated.
n=5
// looping from i = 1 to 5
// in each iteration, i is increased by 1
for (let i = 1; i <= n; i++)
{
document.write(i); // printing the value of i
}
Output
1
2
3
4
5
i=2 2 is printed.
2nd true
n=5 i is increased to 3.
i=3 3 is printed.
3rd true
n=5 i is increased to 4.
i=4 4 is printed.
4th true
n=5 i is increased to 5.
i=5 5 is printed.
5th true
n=5 i is increased to 6.
i=6
6th false The loop is terminated.
n=5
// looping from i = 1 to n
// in each iteration, i is increased by 1
for (let i = 1; i <= n; i++)
{
sum += i; // sum = sum + i
}
document.write('sum:', sum);
Output
sum: 5050
Here, the value of sum is 0 initially. Then, a for loop is iterated from i = 1 to
100. In each iteration, i is added to sum and its value is increased by 1.
When i becomes 101, the test condition is false and sum will be equal to 0 + 1
+ 2 + ... + 100.
The above program to add sum of natural numbers can also be written as
// looping from i = n to 1
// in each iteration, i is decreased by 1
for(let i = n; i >= 1; i-- )
{
// adding i to sum in each iteration
sum += i; // sum = sum + i
}
document.write('sum:',sum);
This program also gives the same output as the Example 3. You can
accomplish the same task in many different ways in programming;
programming is all about logic.
Although both ways are correct, you should try to make your code more
readable.
JavaScript Infinite for loop
If the test condition in a for loop is always true, it runs forever (until memory is
full). For example,
In the above programs, the condition is always true which will then run the
code for infinite times.
while (condition)
{
// body of loop
}
Here,
1
2
3
4
5
Condition: i <=
Iteration Variable Action
n
i = 1 1 is printed. i is
1st true
n=5 increased to 2.
i = 2 2 is printed. i is
2nd true
n=5 increased to 3.
i = 3 3 is printed. i is
3rd true
n=5 increased to 4.
i = 4 4 is printed. i is
4th true
n=5 increased to 5.
i = 5 5 is printed. i is
5th true
n=5 increased to 6.
i = 6
6th false The loop is terminated
n=5
Example 2: Sum of Positive Numbers Only
let sum = 0;
while(number >= 0)
{
Output
Enter a number: 2
Enter a number: 5
Enter a number: 7
Enter a number: 0
Enter a number: -3
The sum is 14.
Here, parseInt() is used because prompt() takes input from the user as a string.
And when numeric strings are added, it behaves as a string. For example, '2' +
'3' = '23'. So parseInt() converts a numeric string to number.
The while loop continues until the user enters a negative number. During each
iteration, the number entered by the user is added to the sum variable.
When the user enters a negative number, the loop terminates. Finally, the total
sum is displayed.
do
{
// body of loop
} while(condition)
Here,
1. The body of the loop is executed at first. Then the condition is evaluated.
2. If the condition evaluates to true, the body of the loop inside the do statement
is executed again.
3. The condition is evaluated once again.
4. If the condition evaluates to true, the body of the loop inside the do statement
is executed again.
5. This process continues until the condition evaluates to false. Then the loop
stops.
Note: do...while loop is similar to the while loop. The only difference is that
in do…while loop, the body of loop is executed at least once.
Flowchart of do...while loop
1
2
3
4
5
Condition: i <=
Iteration Variable Action
n
i = 1 1 is printed. i is increased to
not checked
n=5 2.
i = 2 2 is printed. i is increased to
1st true
n=5 3.
i = 3 3 is printed. i is increased to
2nd true
n=5 4.
i = 4 4 is printed. i is increased to
3rd true
n=5 5.
i = 5 6 is printed. i is increased to
4th true
n=5 6.
i = 6
5th false The loop is terminated
n=5
Example 4: Sum of Positive Numbers
let sum = 0;
let number = 0;
do
{
sum += number;
number = parseInt(prompt('Enter a number: '));
} while(number >= 0)
Output 1
Enter a number: 2
Enter a number: 4
Enter a number: -500
The sum is 6.
Here, the do...while loop continues until the user enters a negative number.
When the number is negative, the loop terminates; the negative number is not
added to the sum variable.
Output 2
The body of the do...while loop runs only once if the user enters a negative
number.
Infinite while loop
If the condition of a loop is always true, the loop runs for infinite times (until
the memory is full). For example,
In the above programs, the condition is always true. Hence, the loop body will
run for infinite times.
JavaScript break Statement
break [label];
Output
1
2
In the above program, the for loop is used to print the value of i in each
iteration. The break statement is used as:
if(i == 3)
{
break;
}
This means, when i is equal to 3, the break statement terminates the loop.
Hence, the output doesn't include values greater than or equal to 3.
Note: The break statement is almost always used with decision-making
statements. To learn more, visit JavaScript if...else Statement.
To learn more about for loop, visit JavaScript for loop.
Example 2: break with while loop
let sum = 0;
while(true)
{
// break condition
if(number < 0)
{
break;
}
// add all positive numbers
sum += number;
Output
Enter a number: 1
Enter a number: 2
Enter a number: 3
Enter a number: -5
The sum is 6.
In the above program, the user enters a number. The while loop is used to
print the total sum of numbers entered by the user.
Here the break statement is used as:
if(number < 0)
{
break;
}
When the user enters a negative number, here -5, the break statement
terminates the loop and the control flow of the program goes outside the loop.
The while loop continues until the user enters a negative number.
To learn more about while loop, visit JavaScript while loop.
When break is used inside of two nested loops, break terminates the inner
loop. For example,
// first loop
for (let i = 1; i <= 3; i++)
{
// second loop
for (let j = 1; j <= 3; j++)
{
if (i == 2)
{
break;
}
document.write(`i = ${i}, j = ${j}`);
}
}
Output
i = 1, j = 1
i = 1, j = 2
i = 1, j = 3
i = 3, j = 1
i = 3, j = 2
i = 3, j = 3
The continue statement is used to skip the current iteration of the loop and the
control flow of the program goes to the next iteration.
The syntax of the continue statement is:
continue [label];
In a for loop, continue skips the current iteration and control flow jumps to
the updateExpression.
// condition to continue
if (i == 3)
{
continue;
}
document.write(i);
}
Output
1
2
4
5
In the above program, for loop is used to print the value of i in each iteration.
Notice the continue statement inside the loop.
if(i == 3)
{
continue;
}
This means
In a while loop, continue skips the current iteration and control flow of the
program jumps back to the while condition.
The continue statement works in the same way for while and do...while loops.
Example 2: Calculate Positive Number
let sum = 0;
let number = 0;
// continue condition
if (isNaN(number))
{
document.write('You entered a string.');
number = 0; // the value of number is made 0 again
continue;
}
}
Output
Enter a number: 1
Enter a number: 2
Enter a number: hello
You entered a string.
Enter a number: 5
Enter a number: -2
The sum is 8.
In the above program, the user enters a number. The while loop is used to
print the total sum of positive numbers entered by the user.
Notice the use of the continue statement.
if (isNaN(number))
{
continue;
}
When continue is used inside of two nested loops, continue skips the current
iteration of the inner loop. For example,
i = 1, j = 1
i = 1, j = 3
i = 2, j = 1
i = 2, j = 3
i = 3, j = 1
i = 3, j = 3
In the above program, when the continue statement executes, it skips the
current iteration in the inner loop and control flow of the program moves to
the updateExpression of the inner loop.
Hence, the value of j = 2 is never displayed in the output.
JavaScript array:
JavaScript array is an object, which can store multiple values using special
syntax. Every value is associated with numeric index starting with 0. The
following figure illustrates how an array stores values.
JavaScript Array
Array Initialization
An array in JavaScript can be defined and initialized in two ways, array literal
and Array constructor syntax.
Array Literal
The following example shows how to define and initialize an array using array
literal syntax.
JavaScript array can store multiple element of different data types. It is not
required to store value of same data type in an array.
Simple example of creating and using array in JavaScript.
<script type="text/javascript">
var emp=["Sonoo","Vimal","Ratan"];
for (i=0;i<emp.length;i++)
{
document.write(emp[i] + "<br/>");
}
</script>
<script type="text/javascript">
var i;
emp[0] = "Arun";
emp[1] = "Varun";
emp[2] = "John";
for (i=0;i<emp.length;i++)
{
document.write(emp[i] + "<br>");
}
</script>
JavaScript array constructor (new keyword)
<script type="text/javascript">
for (i=0;i<emp.length;i++)
{
document.write(emp[i] + "<br>");
}
</script>
An array elements (values) can be accessed using index (key). Specify an index
in square bracket with array name to access the element at particular index.
Please note that index of an array starts from zero in JavaScript.
Use for loop to access all the elements of an array using length property.
Popping
Example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.pop(); // Removes the last element ("Mango") from fruits
Pushing
The push() method adds a new element to an array (at the end):
Example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.push("Kiwi"); // Adds a new element ("Kiwi") to fruits
Shifting Elements
Example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.shift(); // Removes the first element "Banana" from fruits
Deleting Elements
Since JavaScript arrays are objects, elements can be deleted by using the
JavaScript operator delete:
Example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
delete fruits[0]; // Changes the first element in fruits to undefined
Slicing an Array
The slice() method slices out a piece of an array into a new array.
This example slices out a part of an array starting from array element 1
("Orange"):
Example
var fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"];
var citrus = fruits.slice(1);
The slice() method creates a new array. It does not remove any elements from
the source array.
Sorting an Array
Example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.sort();
Reversing an Array
Example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.sort(); // First sort the elements of fruits
fruits.reverse(); // Then reverse the order of the elements
JavaScript Functions
Let’s see the simple example of function in JavaScript that does not has
arguments.
<script>
function msg()
{
alert("hello! this is message");
}
</script>
<input type="button" onclick="msg()" value="call function"/>
JavaScript Function Arguments
We can call function by passing arguments. Let’s see the example of function
that has one argument.
<script>
function getcube(number)
{
alert(number*number*number);
}
</script>
<form>
<input type="button" value="click" onclick="getcube(4)"/>
</form>
We can call function that returns a value and use it in our program. Let’s see
the example of function that returns value.
<script>
function getInfo()
{
return "hello javatpoint! How r u?";
}
</script>
<script>
document.write(getInfo());
</script>
There are mostly three types of dialog boxes in JavaScript. They are used to
either show confirmation messages, raise an error, or show a warning
message. You can get input also from these dialog boxes. The following are the
dialog boxes in JavaScript:
This dialog box is mostly used for validation. It displays a message in the dialog
box. This dialog box will block the browser. You cannot do anything in the
browser page without pressing the “OK” button of this dialog box, then it is
closed. It is used for displaying error messages.
Structure
Window: It is a global object for the javascript code. And it also represents the
browser window.
Document: The document object is the main “entry point” to the page. We can
change or create anything on the page using it and represents all page content
as objects that can be modified.
According to the Document Object Model (DOM), every HTML tag is an object.
Nested tags are “children” of the enclosing one. The text inside a tag is an object
as well.
DOM Object
DOM Properties
Properties Description
Cookie It returns all name or value pairs of cookies in the document.
documentMode It returns the mode used by the browser to render the
document.
Domain It returns the domain name of the server that loaded the
document.
lastModified It returns the date and time of last modified document.
readyState It returns the status of the document.
Referrer It returns the URL of the document that loaded the current
document.
Title It sets or returns the title of the document.
URL It returns the full URL of the document.
DOM Methods
Methods Description
close() It closes the output stream previously opened with document.open().
clear() It clears the document in a window.
open() It opens an output stream to collect the output from
document.write().
write() It writes output (JavaScript code) to a document.
writeln() Same as write(), but adds a newline character after each statement.
Method Description
Property Description
Action It sets and returns the value of the action attribute in a form.
enctype It sets and returns the value of the enctype attribute in a form.
Method It sets and returns the value of the method attribute in a form that is GET or POST.
Name It sets and returns the value of the name attribute in a form.
Target It sets and returns the value of the target attribute in a form.
Method Description
2. Hidden Object
Hidden object represents a hidden input field in an HTML form and it is invisible
to the user.
This object can be placed anywhere on the web page.
It is used to send hidden form of data to a server.
Syntax:
<input type= “hidden”>
Name It sets and returns the value of the name attribute of the hidden input field.
Value It sets or returns the value of the value attribute of the hidden input field.
3. Password Object
Property Description
maxLength It sets or returns the maximum number of characters allowed in a password filed.
Name It sets or returns the value of the name attribute of a password field.
Value It sets or returns the value of the attribute of the password field.
Method Description
4. Checkbox Object
Property Description
Method Description
5. Select Object
Collection Description
Property Description
selectedIndex It sets or returns the index of the selected option in a dropdown list.
Method Description
6. Option Object
Property Description
Value It sets or returns the value to the server if the option was selected.
Methods Description
<html>
<head>
<script type="text/javascript">
function optionfruit(select)
{
var a = select.selectedIndex;
var fav = select.options[a].value;
if(a==0)
{
alert("Please select a fruit");
}
else
{
document.write("Your Favorite Fruit is <b>"+fav+".</b>");
}
}
</script>
</head>
<body>
<form>
List of Fruits:
<select name="fruit">
<option value="0">Select a Fruit</option>
<option value="Mango">Mango</option>
<option value="Apple">Apple</option>
<option value="Banana">Banana</option>
<option value="Strawberry">Strawberry</option>
<option value="Orange">Orange</option>
</select>
<input type="button" value="Select"
onClick="optionfruit(this.form.fruit);">
</form>
</body>
</html>
Output:
Your Favorite Fruit is Mango.
7. Radio Object
Radio object represents a radio button in an HTML form.
Syntax:
<input type= “radio”>
Property Description
Name It sets or returns the value of the name attribute of a radio button.
Method Description
8. Text Object
Text object represents a single-line text input field in an HTML form.
Syntax:
<input type= “text”>
Property Description
Name It sets or returns the value of the name attribute of a text field.
maxLength It sets or returns the maximum number of characters allowed in a text field.
9. Textarea Object
Textarea object represents a text-area in an HTML form.
Syntax:
<textarea> . . . </textarea>
Property Description
Name It sets or returns the value of the name attribute of a text field.
Even the document object (of the HTML DOM) is a property of the
window object:
window.document.getElementById("header");
document.getElementById("header");
Window Size
Two properties can be used to determine the size of the browser window.
Window Methods
Method Description
clearInterval() clears the timer, which is set by using the setInterval() method
clearTimeout() clears the timer, which is set by using the setTimeout() method
confirm() displays a dialog box with a message and two buttons, OK and Cancel
print() sends a print command to print the content of the current window
prompt() prompts for input
It displays the confirm dialog box. It has message with ok and cancel buttons.
Example of Settimeout() function
JavaScript History Object
window.history
Or,
history
window.navigator
Or,
navigator
The navigator object in JavaScript is used to retrieve properties of client browser. The
following table describes properties of the navigator object in JavaScript.
Property Description
cookieenabled specifies whether the cookies are enabled or not in the browser
contains a string indicating the machine type for which the browser
platform
was compiled
<!DOCTYPE HTML>
<html>
<head>
<title>JavaScript Navigator Object Properties</title>
<script type="text/javascript">
function dispNavigatorProperties()
{
with(document)
{
write("<b>appName = </b>")
writeln(navigator.appName + "<br/><br/>")
write("<b>appVersion = </b>")
writeln(navigator.appVersion + "<br/><br/>")
write("<b>appCodeName = </b>")
writeln(navigator.appCodeName + "<br/><br/>")
write("<b>platform = </b>")
writeln(navigator.platform + " <br/><br/>")
write("<b>userAgent = </b>")
writeln(navigator.userAgent + "<br/><br/>")
}
}
function dispExplorerProperties()
{
with(document)
{
write("<b>appName = </b>")
writeln(navigator.appName + "<br/><br/>")
write("<b>appVersion = </b>")
writeln(navigator.appVersion + "<br/><br/>")
write("<b>appCodeName = </b>")
writeln(navigator.appCodeName + "<br/><br/>")
write("<b>platform = </b>")
writeln(navigator.platform + " <br/><br/>")
write("<b>userAgent = </b>")
writeln(navigator.userAgent + "<br/><br/>")
write("<b>cookieEnabled = </b>")
writeln(navigator.cookieEnabled + "<br/><br/>")
}
}
function dispBrowserProperties()
{
if(navigator.appName == "Netscape")
dispNavigatorProperties()
else if(navigator.appName == "Microsoft Internet
Explorer")
dispExplorerProperties()
}
dispBrowserProperties()
</script>
</head>
<body>
</body>
</html>
Here are some outputs of the above JavaScript navigator object properties example
code. This is the snapshot of output produced in Google Chrome browser:
Or,
screen
There are many properties of screen object that returns information of the
browser.
Functions Description
parseFloat If the string begins with a number, the function reads through the
(string) string until it finds the end of the number; cuts off the remainder of
the string and returns the result.
If the string does not begin with a number, the function returns NaN.
parseInt If the string begins with an integer, the function reads through the
(string) string until it finds the end of the integer, cuts off the remainder of
the string and returns the result.
If the string does not begin with an integer, the function returns NaN
(Not a Number).
isNaN(NaN); // true
isNaN(1); // false: 1 is a number
isNaN(-2e-4); // false: -2e-4 is a number (-0.0002) in scientific notation
isNaN(Infinity); // false: Infinity is a number
isNaN(true); // false: converted to 1, which is a number
isNaN(false); // false: converted to 0, which is a number
isNaN(null); // false: converted to 0, which is a number
isNaN(""); // false: converted to 0, which is a number
isNaN(" "); // false: converted to 0, which is a number
isNaN("45.3"); // false: string representing a number, converted to 45.3
isNaN("1.2e3"); // false: string representing a number, converted to 1.2e3
isNaN("Infinity"); // false: string representing a number, converted to Infinity
isNaN(new Date); // false: Date object, converted to milliseconds since epoch
isNaN("10$"); // true : conversion fails, the dollar sign is not a digit
isNaN("hello"); // true : conversion fails, no digits at all
isNaN(undefined); // true : converted to NaN
isNaN(); // true : converted to NaN (implicitly undefined)
parseFloat (string):
If the string begins with a number, the function reads through the string
until it finds the end of the number; cuts off the remainder of the string
and returns the result.
If the string does not begin with a number, the function returns NaN.
var a = parseFloat("10") // 10
var b = parseFloat("10.00") // 10
var c = parseFloat("10.33") // 10.33
var d = parseFloat("34 45 66") // 34
var e = parseFloat(" 60 ") // 60
var f = parseFloat("40 years") // 40
var g = parseFloat("He was 40") // NaN
parseInt (string):
If the string begins with an integer, the function reads through the string
until it finds the end of the integer, cuts off the remainder of the string and
returns the result.
If the string does not begin with an integer, the function returns NaN (Not
a Number).
var a = parseInt("10") // 10
var b = parseInt("10.00") // 10
var c = parseInt("10.33") // 10
var d = parseInt("34 45 66") // 34
var e = parseInt(" 60 ") // 60
var f = parseInt("40 years") // 40
var g = parseInt("He was 40") // NaN
var x = 10;
var y = 20;
var a = eval("x * y") + "<br>"; // 200
var b = eval("2 + 2") + "<br>"; // 4
var c = eval("x + 17") + "<br>"; // 27
Inside the function, the arguments (the parameters) behave as local variables.
Function Invocation
The code inside the function will execute when "something" invokes (calls) the
function:
Function Return
Example
function myFunction(a, b)
{
return a * b; // Function returns the product of a and b
}
The result in x will be: 12
Functions Used as Variable Values
Functions can be used the same way as you use variables, in all types of
formulas, assignments, and calculations.
Example
var x = toCelsius(77);
var text = "The temperature is " + x + " Celsius";
Local Variables
Example
// code here can NOT use carName
function myFunction() {
var carName = "Volvo";
// code here CAN use carName
}
Since local variables are only recognized inside their functions, variables with
the same name can be used in different functions.
Local variables are created when a function starts, and deleted when the
function is completed.
Date Object
At times when user need to access the current date and time and also past
and future date and times. JavaScript provides support for working with
dates and time through the Date object.
The Date object provides a system-independent abstraction of dates and
times.
Date object can be created as : var today = new Date( );
Dates may be constructed from a year, month, day of the month, hour,
minute, and second, and those six components, as well as the day of the
week, may be extracted from a date.
Dates may also be compared and converted to a readable string form. A
Date is represented to a precision of one millisecond.
Properties of Date object
Date Methods
Methods Description
getTime() Returns the number of milliseconds since January 1, 1970 at 12:00 AM.
getTimezoneOffset() Returns the timezone offset in minutes for the current locale.
setTime() Sets the number of milliseconds since January 1, 1970 at 12:00 AM.
Math Object
Math Properties
PI Returns Π value.
Math Methods
Methods Description
String Properties
Properties Description
constructor It returns the reference to the String function that created the object.
String Methods
Methods Description
charCodeAt() It returns the ASCII code of the character at the specified position.
concat() It combines the text of two strings and returns a new string.
split() It splits a string object into an array of strings by separating the string into
the substrings.