Java
Java
Java
JAVA was developed by James Gosling at Sun Microsystems Inc in the year
1995, later acquired by Oracle Corporation. It is a simple programming language.
Java makes writing, compiling, and debugging programming easy. It helps to
create reusable code and modular programs. Java is a class-based, object-oriented
programming language.
Features of Java:
1. Simple
2. Object-Oriented
3. Portable
4. Platform independent
5. Secured
6. Robust
7. Architecture neutral
8. Interpreted
9. High Performance
10. Multithreaded
11. Distributed
12. Dynamic
Simple:
Java is very easy to learn, and its syntax is simple, clean and easy to understand.
According to Sun Microsystem, Java language is a simple programming language
because:
Java syntax is based on C++ (so easier for programmers to learn it after
C++).
Java has removed many complicated and rarely-used features, for example,
explicit pointers, operator overloading, etc.
There is no need to remove unreferenced objects because there is an
Automatic Garbage Collection in Java.
Object-oriented
1. Object
2. Class
3. Inheritance
4. Polymorphism
5. Abstraction
6. Encapsulation
Platform Independent:
Example:
Secured:
Java is best known for its security. With Java, we can develop virus-free systems.
Java is secured because:
No explicit pointer
Java Programs run inside a virtual machine sandbox
Classloader: Classloader in Java is a part of the Java Runtime
Environment (JRE) which is used to load Java classes into the Java
Virtual Machine dynamically. It adds security by separating the package
for the classes of the local file system from those that are imported from
network sources.
Bytecode Verifier: It checks the code fragments for illegal code that can
violate access rights to objects.
Security Manager: It determines what resources a class can access such
as reading and writing to the local disk.
Robust:
Java is portable because it facilitates you to carry the Java bytecode to any
platform.
It doesn't require any implementation. Java programs can be easily moved
from one system to another system, anywhere and anytime.
We can change and upgrade system processor and system resources
without any changes in java.
High-performance:
Distributed:
Dynamic:
Introduction:
The Java Development Kit (JDK) is software used for Java programming, along
with the Java Virtual Machine (JVM) and the Java Runtime Environment
(JRE). The JDK includes the compiler and class libraries, allowing developers
to create Java programs executable by the JVM and JRE.
Before installing the Java Development Kit, check if a Java version is already
installed on Windows. Follow the steps below:
Download the latest Java Development Kit installation file for Windows 10 to
have the latest features and bug fixes.
After downloading the installation file, proceed with installing Java on your
Windows system.
After running the installation file, the installation wizard welcome screen
appears.
To set the temporary path of JDK, you need to follow the following steps:
For Example:
set path=C:\Program Files\Java\jdk1.6.0_23\bin
Compile: javac filename.java
ClassLoader:
The heap area is a part of the JVM memory and is created when the
JVM starts up. Its size cannot be static because it increases or decrease
during the application runs.
Stack:
Native Stack:
Execution Engine:
It is the central part of the JVM. Its main task is to execute the byte
code and execute the Java classes. The execution engine has three main
components used for executing Java classes.
Interpreter:
JIT Compiler:
3.Interpreter:
Once the classes get loaded and the code gets verified, then interpreter reads the
assembly code line by line and does the following two functions:
JDK contains:
When object is unreferenced then the JVM send into garbage collector to
destroy the object.
we were using free() function in C language and delete() in C++. But, in java it
is performed automatically. So, java provides better memory management.
Advantage of Garbage Collection:
o It makes java memory efficient because garbage collector removes the
unreferenced objects from heap memory.
o It is automatically done by the garbage collector(a part of JVM) so we
don't need to make extra efforts.
finalize() method:
The finalize() method is invoked each time before the object is garbage collected.
This method can be used to perform cleanup processing.
Syntax:
……………….
……………….
gc() method:
The gc() method is used to invoke the garbage collector to perform cleanup
processing. The gc() is found in System and Runtime classes.
Syntax:
………………
………………
}
Example:
class TestGarbage1
{
public void finalize()
{
System.out.println("object is garbage collected");
}
public static void main(String args[])
{
TestGarbage1 s1=new TestGarbage1();
TestGarbage1 s2=new TestGarbage1();
s1=null;
s2=null;
System.gc();
}
}
Output:
object is garbage collected
object is garbage collected
Lexical Tokens/ Lexical Issues in java
A lexical token may consist of one or more characters, and every single character
is in exactly one token.
The tokens can be keywords, comments, numbers, white space, or strings. All
lines should be terminated by a semi-colon (;).
White Space
White space can contain the characters for tabs, blanks, newlines, and form feeds.
These characters are ignored except when they serve to separate other tokens.
However, blanks and tabs are significant in strings.
Comments
1. Single line comments begin with the token // and end with a carriage return.
For example, //this is the single-line syntax.
2. Multi-Line comments begin with the token /* and end with the token */
For example, /* this is multiline syntax*/
Numbers:
Integer Number
Real Numbers
Signed and Unsigned Numbers
Negative Numbers
Identifiers:
The identifier is the name used to define the object, such as a function, module,
or register. Identifiers should begin with alphabetical characters or underscore
characters.
Escaped Identifiers:
Verilog HDL allows any character to be used in an identifier by escaping the
identifier.
Escaped identifiers begin with the backslash (\). The backslash escapes the
entire identifier.
Operators are special characters used to put conditions or to operate the variables.
There are one, two, and sometimes three characters used to perform operations
on variables.
1. Arithmetic Operators:
These operators perform arithmetic operations. The + and -are used as either
unary (x) or binary (z-y) operators.
2. Relational Operators:
These operators compare two operands and return the result in a single bit, 1 or
0. The Operators included in relational operation are:
== (equal to)
!= (not equal to)
(greater than)
>= (greater than or equal to)
< (less than)
<= (less than or equal to)
3. Bit-wise Operators:
Logical operators are bit-wise operators and are used only for single-bit operands.
They return a single bit value, 0 or 1. They can work on integers or groups of bits,
expressions and treat all non-zero values as 1.
Logical operators are generally used in conditional statements since they work
with expressions. The operators included in Logical operation are:
! (logical NOT)
&& (logical AND)
|| (logical OR)
5. Reduction Operators:
Reduction operators are the unary form of the bitwise operators and operate on
all the bits of an operand vector. These also return a single-bit value. The
operators included in Reduction operation are:
6. Shift Operators:
Shift operators are shifting the first operand by the number of bits specified by
the second operand in the syntax.
Vacant positions are filled with zeros for both directions, left and right shifts
(There is no use sign extension). The Operators included in Shift operation are:
{ }(concatenation)
8. Replication Operator:
The replication operator is making multiple copies of an item. The operator used
in Replication operation is:
9. Conditional Operator:
(Condition) ?
Operands:
1. Literals
Literals are constant-valued operands that are used in Verilog expressions. The
two commonly used Verilog literals are:
Wires, regs, and parameters are the data types used as operands in Verilog
expressions. Bit-Selection "x[2]" and Part-Selection "x[4:2]"
Bit-selects and part-selects are used to select one bit and multiple bits,
respectively, from a wire, regs or parameter vector using square brackets "[ ]".
3. Function Calls:
It just places the function call as one of the types of operands. It is useful to know
the bit width of the return value of the function call.
Keywords
Qns:
What is a keyword and explain different types of keywords in
java
Keywords or Reserved words are the words in a language that are used for
some internal process or represent some predefined actions. These words are
therefore not allowed to use as variable names or objects.
1. abstract:
2. boolean:
Java break keyword is used to break the loop or switch statement. It breaks
the current flow of the program at specified conditions.
4. byte:
Java byte keyword is used to declare a variable that can hold 8-bit data
values.
5. case:
Java case keyword is used with the switch statements to mark blocks of
text.
6. catch:
7. char:
Java char keyword is used to declare a variable that can hold unsigned 16-
bit Unicode characters
8. class:
9. continue:
Java continue keyword is used to continue the loop. It continues the current
flow of the program and skips the remaining code at the specified
condition.
10. default:
Java default keyword is used to specify the default block of code in a switch
statement.
11. do:
12. double:
Java double keyword is used to declare a variable that can hold 64-bit
floating-point number.
13. else:
14. enum:
15. extends:
16. final:
Java final keyword is used to indicate that a variable holds a constant value.
It is used with a variable. It is used to restrict the user from updating the
value of the variable.
17. finally:
18. float:
Java float keyword is used to declare a variable that can hold a 32-bit
floating-point number.
19. for:
Java for keyword is used to start a for loop. It is used to execute a set of
instructions/functions repeatedly when some condition becomes true. If the
number of iteration is fixed, it is recommended to use for loop.
20. if:
Java if keyword tests the condition. It executes the if block if the condition
is true.
21. implements:
22. import:
Java import keyword makes classes and interfaces available and accessible
to the current source code.
23. instanceof:
24. int:
Java int keyword is used to declare a variable that can hold a 32-bit signed
integer.
25. interface:
26. long:
Java long keyword is used to declare a variable that can hold a 64-bit
integer.
27. native:
28. new:
29. null:
Java null keyword is used to indicate that a reference does not refer to
anything. It removes the garbage value.
30. package:
Java package keyword is used to declare a Java package that includes the
classes.
31. private:
32. protected:
33. public:
34. return:
Java return keyword is used to return from a method when its execution is
complete.
35. short:
Java short keyword is used to declare a variable that can hold a 16-bit
integer.
36. static:
37. strictfp:
38. super:
39. switch:
The Java switch keyword contains a switch statement that executes code
based on test value. The switch statement tests the equality of a variable
against multiple values.
40. synchronized:
41. this:
Java this keyword can be used to refer the current object in a method or
constructor.
42. throw:
43. throws:
44. transient:
45. try:
Java try keyword is used to start a block of code that will be tested for
exceptions. The try block must be followed by either catch or finally block.
46. void:
Java void keyword is used to specify that a method does not have a return
value.
47. volatile:
48. while:
Java while keyword is used to start a while loop. This loop iterates a part
of the program several times. If the number of iterations is not fixed, it is
recommended to use the while loop.
Sample program in Java:
In this section, we will learn how to write the simple program of Java. We can
write a simple hello Java program easily.
class Simple
{
public static void main(String args[])
{
System.out.println("Hello Java");
}
}
Output:
Hello Java
1. Primitive data types: The primitive data types include Boolean, char,
byte, short, int, long, float and double.
2. Non-primitive data types: The non-primitive data types
include Classes, Interfaces, and Arrays.
1
7. float data type
8. double data type
byte 0 1 byte
short 0 2 byte
Int 0 4 byte
The Boolean data type specifies one bit of information, but its "size" can't be
defined precisely.
Example:
2
The byte data type is used to save memory in large arrays where the memory
savings is most required. It saves space because a byte is 4 times smaller than an
integer. It can also be used in place of "int" data type.
Example:
The short data type can also be used to save memory just like byte data type. A
short data type is 2 times smaller than an integer.
Example:
The int data type is a 32-bit signed two's complement integer. Its
value-range lies between - 2,147,483,648 (-2^31) to 2,147,483,647 (2^31 -1)
(inclusive). Its minimum value is - 2,147,483,648and maximum value is
2,147,483,647. Its default value is 0.
The int data type is generally used as a default data type for integral values
unless if there is no problem about memory.
Example:
Its default value is 0. The long data type is used when you need a range of
values more than those provided by int.
3
Example:
The float data type should never be used for precise values, such as currency. Its
default value is 0.0F.
Example:
float f1 = 234.5f
Example:
double d1 = 12.3
Example:
4
Variables:
A variable is a container which holds the value while the Java program
Variable is a name of memory location. There are three types of variables in java:
local, instance and static.
Variables
1) Local Variable:
A variable declared inside the body of the method is called local variable. You
can use this variable only within that method and the other methods in the class
aren't even aware that the variable exists.
5
public class LocalVariable
{
public static void main(String[] args)
{
int x=100;
int y=200;
int z=x+y;
System.out.println(z);
}
}
Output:
z=300
Note:
2) Instance Variable:
Instance variables are non-static variables. A variable declared inside the class
but outside the body of the method, is called an instance variable. It is not declared
as static It is called an instance variable because its value is instance-specific and
is not shared among instances.
Unlike local variables, we may use access specifiers for instance variables. If
we do not specify any access specifier, then the default access specifier will be
used.
Initialization of an instance variable is not mandatory. Its default
value is 0.
Instance variables can be accessed only by creating objects.
6
class InstanceVariable
{
int count=0; //will get memory each time when the instance is created
InstanceVariable()
{
count++; //incrementing value
System.out.println(count);
}
public static void main(String args[])
{
InstanceVariable c1=new InstanceVariable(); //Creating objects1
InstanceVariable c2=new InstanceVariable(); //Creating objects2
InstanceVariable c3=new InstanceVariable(); //Creating objects3
}
}
Output:
1
1
1
7
3) Static variable:
class StaticVariable
{
static int count=10; //will get memory only once and retain its value
StaticVariable()
{
count++; //incrementing the value of static variable
System.out.println(count);
}
public static void main(String args[])
{
StaticVariable c1=new StaticVariable (); //creating objects1
StaticVariable c2=new StaticVariable (); //creating objects2
StaticVariable c3=new StaticVariable (); //creating objects3
}
}
Output:
11
12
13
8
variable naming conventions
Variables are tokens within the command statements that are to be replaced with
actual values immediately before the statement is run.
The standard naming conventions used in modern software development are as
follows:
Pascal case
camel case
snake case
kebab case
Pascal case:
Popularized by the Turbo Pascal programming language, Pascal case requires
the first letter of a variable be uppercase, along with the first letter of every new
word compounded together to create the variable.
ThisIsPascalCase
AnotherPascalCaseExample
Camel case:
Camel case follows the same rules as Pascal case but drops the requirement to
capitalize the first letter. To differentiate between cases where the first letter is
or is not capitalized, software developers often use the terms "upper camel case"
and "lower camel case."
Upper camel case looks the same as Pascal case. Lower camel case is also
known as "dromedary case," as a dromedary camel has one less hump than the
two-humped Bactrian camel.
9
The following are examples of camel case:
thisIsDromedaryCamelCase
ThisIsUpperCamelCase
Snake and kebab case:
For those who appreciate more whitespace between concatenated words, there
is snake case and kebab case. Snake case separates words with underscores; it's
also called pothole case. When every letter is capitalized, it is known as
screaming snake case:
this_is_snake_case
THIS_IS_SCREAMING_SNAKE_CASE
Kebab case:
Kebab case follows the same rules as snake case, just with a dash instead of an
underscore. When all capital letters are used, it's known as a scream kebab.
this-is-kebab-case
THIS-IS-A-SCREAM-KEBAB
One of the problems with kebab case is that the dash can be confused with a
minus sign, which can create difficult-to-troubleshoot bugs in code.
10
Scope of Variables in Java:
In programming, scope of variable defines how a specific variable is accessible
within the program or across classes.
Scope of a Variable:
These are the variables that are declared inside the class but outside any function
have class-level scope. We can access these variables anywhere inside the class.
Note that the access specifier of a member variable does not affect the scope
within the class.
11
Access Modifier Package Subclass Word
private No No No
default Yes No No
Syntax:
12
Example: 1
Output:
y=100;
^
symbol: variable y
location: class VariableScopeExample1
1 error
Note:
We see that y=100 is unknown. If you want to compile and run the above
program remove or comment the statement y=100. After removing the
statement, the above program runs successfully and shows the following
output.
13
Example Program:2 Instance Variable
Output:
Product Name: Java Book
Product Price: 6000.0
14
Method Level Scope: (Local Variables)
These are the variables that are declared inside a method, constructor,
or block have a method-level or block-level scope and cannot be accessed
outside in which it is defined. Variables declared inside a pair of curly
braces {} have block-level scope.
Example:
public class DemoClass1
{
void show()
{
//variable declared inside a method has method level scope
int x=100;
System.out.println("The value of x is: "+x);
}
public static void main(String args[])
{
DemoClass1 dc = new DemoClass1();
dc.show();
}
}
Output:
Value of x is: 100
15
Variable Inside Constructor:
Output:
Salary is: 25000
16
Example:3
int y=200;
1 error
Note:
We see that y=100 is unknown. If you want to compile and run the above
program remove or comment the statement y=100. After removing the
statement, the above program runs successfully and shows the following output.
17
Final Keyword In Java:
The final keyword in java is used to restrict the
user. The final keyword can be applied with the variables, a final variable that
have no value it is called blank final variable or uninitialized final variable.
The final keyword is used to denote the constants. The final keyword is usually
used with methods, classes, and variables. Whenever we define any variable or
class or method as final then the particular entity cannot be changed after has
been assigned.
1. Final Variable
2. Final Method
3. Final Class
Usage 1:
One is definitely to prevent inheritance, as final classes cannot be
extended. For example, all Wrapper Classes like Integer, Float, etc. are final
classes. We can not extend them.
Usage 2:
The other use of final with classes is to create an immutable class like
the predefined String class. One cannot make a class immutable without making
it final.
18
Final variable:
If you make any variable as final, you cannot change the value of final variable
(It will be constant).
When a variable is declared with the final keyword, its value can’t be
modified, essentially, a constant.
This also means that you must initialize a final variable.
If the final variable is a reference, this means that the variable cannot be
re-bound to reference another object,
but the internal state of the object pointed by that reference variable can
be changed i.e. you can add or remove elements from the final array or
final collection.
Example:
class Bike9
{
final int speedlimit=90;//final variable
pvoid run()
{
speedlimit=400;
}
public static void main(String args[])
{
Bike9 obj=new Bike9();
obj.run();
}
}
Output:
Here is a final variable speedlimit, we are going to change the value of this
variable, but It can't be changed because final variable once assigned a value
can never be changed.
19
final method:
The final method in java is the method that cannot be changed
or overridden once defined. Hence, we cannot modify a final method from
the subclass.
class Bike
{
final void run()
{
System.out.println("running");
}
}
class Honda extends Bike
{
void run()
{
System.out.println("Running Safely Below 90kmph");
}
public static void main(String args[])
{
Honda Enfield= new Honda();
Enfield.run();
20
}
}
Output:
Compile time error
final class
If you make any class as final, you cannot extend it. A class declared with
the final keyword is known as the final class.
A final class can’t be inherited by subclasses.
By use of the final class, we can restrict the inheritance of the class.
We can create a class as a final class only if it is complete in nature,
which means it must not be an abstract class.
In java, all the wrapper classes are final classes like String, Integer, etc.
If we try to inherit a final class, then the compiler throws an error at
compilation time.
We can’t create a class as immutable without the final class.
Example Program:
final class Bike{}
class Honda1 extends Bike
{
void run()
{
System.out.println("Running Safely With @ 90kmph");
}
public static void main(String args[])
{
Honda1 honda= new Honda1();
honda.run();
}
}
Output:
Compile time error
21
Note:
Delete the final key word for getting output.
Output:
Running Safely With @ 90kmph
Output:
A = 10, B = 20, C = 30
22
Operators in Java:
Java support the set operators, operator is an symbol that tells the computer
to perform certain mathematical and logical manipulations is used to perform
operations. For example: +, -, *, / etc.
There are many types of operators in Java which are given below:
Unary Operator:
The Java unary operators require only one operand. Unary operators are used to
perform various operations
class OperatorExample
{
public static void main(String args[])
{
int x=10;
System.out.println(x++);//10 (11)
System.out.println(++x);//12
System.out.println(x--);//12 (11)
System.out.println(--x);//10
}
}
23
Output:
10
12
12
10
Example: 2
class OperatorExample
{
public static void main(String args[])
{
int a=10;
int b=-10;
boolean c=true;
boolean d=false;
System.out.println(~a);
//11 (minus of total positive value which starts from 0)
System.out.println(~b);//9 (positive of total minus, positive starts from 0)
System.out.println(!c);//false (opposite of boolean value)
System.out.println(!d);//true
}
}
Output:
-11
9
false
true
24
Arithmetic Operators
class OperatorExample
{
public static void main(String args[])
{
int a=10;
int b=5;
System.out.println(a+b);//15
System.out.println(a-b);//5
System.out.println(a*b);//50
System.out.println(a/b);//2
System.out.println(a%b);//0
}
}
Output:
15
5
50
2
0
import java.io.*;
class Addition
{
public static void main(String[] args)
{
int num1 = 10, num2 = 20, sum = 0;
System.out.println("num1 = " + num1);
System.out.println("num2 = " + num2);
sum = num1 + num2;
System.out.println("The sum = " + sum);
}
}
Output:
num1 = 10 num2 = 20
The sum = 30
25
Left Shift Operator:
The Java left shift operator << is used to shift all of the bits in a value to the left
side of a specified number of times.
class OperatorExample
{
public static void main(String args[])
{
System.out.println(10<<2);//10*2^2=10*4=40
System.out.println(10<<3);//10*2^3=10*8=80
System.out.println(20<<2);//20*2^2=20*4=80
System.out.println(15<<4);//15*2^4=15*16=240
}
}
Output:
40
80
80
240
Right Shift Operator:
The Java right shift operator >> is used to move the value of the left operand to
right by the number of bits specified by the right operand.
public OperatorExample
{
public static void main(String args[])
{
System.out.println(10>>2);//10/2^2=10/4=2
System.out.println(20>>2);//20/2^2=20/4=5
System.out.println(20>>3);//20/2^3=20/8=2
}
}
Output:
2
5
2
26
Logical Operators:
These operators are used to perform “logical AND” and
“logical OR” operations, i.e., a function similar to AND gate and OR gate in
digital electronics. One thing to keep in mind is the second condition is not
evaluated if the first one is false, i.e., it has a short-circuiting effect. Used
extensively to test for several conditions for making a decision. Java also has
“Logical NOT”, which returns true when the condition is false and vice-versa
Conditional operators are:
&&, Logical AND: returns true when both conditions are true.
||, Logical OR: returns true if at least one condition is true.
!, Logical NOT: returns true when a condition is false and vice-versa
class OperatorExample
{
public static void main(String args[])
{
int a=10;
int b=5;
int c=20;
System.out.println(a<b&&a++<c);//false && true = false
System.out.println(a);//10 because second condition is not checked
System.out.println(a<b&a++<c);//false && true = false
System.out.println(a);//11 because second condition is checked
}
}
Output:
false10
false
11
27
OR Operator Example: Logical || and Bitwise:
The logical || operator doesn't check the second condition if the first condition is
true. It checks the second condition only if the first one is false.
class OperatorExample
{
public static void main(String args[])
{
int a=10;
int b=5;
int c=20;
System.out.println(a>b||a<c);//true || true = true
System.out.println(a>b|a<c);//true | true = true
//|| vs |
System.out.println(a>b||a++<c);//true || true = true
System.out.println(a);//10 because second condition is not checked
System.out.println(a>b|a++<c);//true | true = true
System.out.println(a);//11 because second condition is checked
}
}
Output:
truetrue
true
10
true
11
28
Ternary Operator:
Java Ternary operator is used as one line replacement for if-then-else statement
and used a lot in Java programming. It is the only conditional operator which
takes three operands.
class OperatorExample
{
public static void main(String args[])
{
int a=2;
int b=5;
int min=(a<b)?a:b;
System.out.println(min);
}
}
Output:
2
Assignment Operator:
class OperatorExample
{
public static void main(String args[])
{
int x=100;
int y=200;
x+=50;
y-=50;
System.out.println(x);
System.out.println(y);
}
29
}
Output:
14
16
Relational Operators:
These operators are used to check for relations like
equality, greater than, and less than. They return boolean results after the
comparison and are extensively used in looping statements as well as
conditional if-else statements.
==, Equal to returns true if the left-hand side is equal to the right-hand
side.
!=, Not Equal to returns true if the left-hand side is not equal to the
right-hand side.
<, less than: returns true if the left-hand side is less than the right-hand
side.
<=, less than or equal to returns true if the left-hand side is less than or
equal to the right-hand side.
>, Greater than: returns true if the left-hand side is greater than the
right-hand side.
>=, Greater than or equal to returns true if the left-hand side is greater
than or equal to the right-hand side.
30
Example Program:
class Test
{
public static void main(String args[])
{
int a = 10;
int b = 20;
System.out.println("a == b = " + (a == b) );
System.out.println("a != b = " + (a != b) );
System.out.println("a > b = " + (a > b) );
System.out.println("a < b = " + (a < b) );
System.out.println("b >= a = " + (b >= a) );
System.out.println("b <= a = " + (b <= a) );
}
}
Output:
a == b = false
a != b = true
a > b = false
a < b = true
b >= a = true
b <= a = false
31
Memory Management:
Memory management is the process of allocation
and de-allocation of objects, called Memory management. Java does memory
management automatically. Java uses an automatic memory management
system called a garbage collector. Thus, we are not required to implement
memory management logic in our application. Java memory management
divides into two major parts:
32
Heap Area:
Heap stores the actual objects. It creates when the JVM starts up.
The user can control the heap if needed. It can be of fixed or dynamic size.
When you use a new keyword, the JVM creates an instance for the object
in a heap.
While the reference of that object stores in the stack. There exists only one
heap for each running JVM process.
When heap becomes full, the garbage is collected.
The Java Virtual Machine has a heap that is shared among all Java Virtual
Machine threads.
The heap is the run-time data area from which memory for all class
instances and arrays is allocated.
The heap is created on virtual machine start-up. Heap storage for objects is
reclaimed by Garbage Collector.
Whenever we create any object in our program, the object is created in
heap and the stack (JVM/Native) stores the reference to it.
Method Area:
Method Area is a part of the heap memory which is shared among all the
threads.
It creates when the JVM starts up. It is used to store class structure,
superclass name, interface name, and constructors.
The JVM stores the following kinds of information in the method area
Stack Area:
Stack Area generates when a thread creates.
It can be of either fixed or dynamic size. The stack memory is allocated per
thread.
33
It is used to store data and partial results. It contains references to heap
objects.
It also holds the value itself rather than a reference to an object from the
heap.
The variables which are stored in the stack have certain visibility, called
scope.
Also called as C stacks, native method stacks are not written in Java
language.
This memory is allocated for each thread when its created. And it can be
of fixed or dynamic nature.
Native methods are methods written in a language other than the Java
programming language.
Native method stacks are typically allocated per thread when each thread
is created.
PC Registers:
Each thread has a Program Counter (PC) register associated with it.
PC register stores the return address or a native pointer.
It also contains the address of the JVM instructions currently being
executed.
Program Counter or PC register holds the address of JVM instruction
currently being executed for any particular thread.
34
An example of JVM instruction is d2f which converts a double value to
float value.
If the current method being executed is not one of JVM instruction set, it
has to be a native method.
35
Explain Conditional statements in Java with examples.
Conditional statements are mostly used in decision-making scenarios which means these
statements take a decision on the basis of some conditions. The conditional statements are
also referred as branching statements because the program takes a decision based on the
result of the assessed condition.
if statement
if-else statement
if-else-if ladder
nested if statement
Switch Statement
if Statement:
The Java if statement tests the condition. It executes the if block if condition is true. If the
given condition is satisfied it will execute the true block statement only
Example Program:
class IfExample
{
public static void main(String[] args)
{
//defining an 'age' variable
int age=18;
//checking the age
if(age>18)
{
System.out.print("You are eligible to vote");
}
}
}
Output:
21
You are eligible to vote
if-else Statement:
The Java if-else statement also tests the condition. It executes the if block if condition is true
otherwise else block is executed. It will execute either true block statement or false block
statements.
Example Program:1
class IfExample
{
public static void main(String[] args)
{
int age=20; //defining an 'age' variable
if(age>18) //checking the age
{
System.out.print("You are eligible to vote");
}
else
{
System.out.println(“You are not eligible to vote”);
}
}
}
Output:
25
You are not eligible to vote
if-else-if ladder Statement:
The if-else-if ladder statement executes one condition from multiple statements. If the first
condition is satisfy it will execute the statement otherwise it will execute the next condition.
if(condition1)
{
//code to be executed if condition1 is true
}
else if(condition2)
{
//code to be executed if condition2 is true
}
else if(condition3)
{
//code to be executed if condition3 is true
}
...
Else
{
//code to be executed if all the conditions are false
}
Example Program:
import java.util.Scanner;
class if-else-if ladder
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter a percentage");
float per = sc.nextFloat();
if(per>=70)
{
System.out.println("Distinction");
}
else if(per>=60)
{
System.out.println("First Class");
}
else if(per>=50)
{
System.out.println("Second Class");
}
else if(per>=40)
{
System.out.println("Pass");
}
else
{
System.out.println("Failed");
}
}
}
Output:
Enter a percentage:
62
First Class
Nested if statement:
The nested if statement represents the if block within another if block. Here, the inner if
block condition executes only when outer if block condition is true.
if(condition)
{
//code to be executed
if(condition)
{
//code to be executed
}
}
Example program:
public class NestedIfExample2
{
public static void main(String[] args)
{
int age=25; //Creating two variables for age and weight
int weight=48;
if(age>=18) //applying condition on age and weight
{
if(weight>50)
{
System.out.println("You are eligible to donate blood");
}
else
{
System.out.println("You are not eligible to donate blood");
}
}
else
{
System.out.println("Age must be greater than 18");
}
}
}
Output:
16
You are not eligible to donate blood
Switch Statement:
Syntax:
switch(expression)
{
case value1:
//code to be executed;
break; //optional
case value2:
//code to be executed;
break; //optional
………
default:
code to be executed if all cases are not matched;
}
Example program:
class WeekDays
{
public static void main(String s[])
{
int day = 2;
switch(day)
{
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
case 3:
System.out.println("Wednesday");
break;
case 4:
System.out.println("Thursday");
break;
case 5:
System.out.println("Friday");
break;
default:
System.out.println("Weekend");
break;
}
}
}
Out put:
Tuesday
Explain about Iteration/ looping statements statements
For Loop:
Iteration statements are used to execute a particular set of instructions repeatedly until a
particular condition is met or for a fixed number of iterations.
• The initialization statement is executed only once.
• Then, the test expression is evaluated. If the test expression is evaluated to false,
the for loop is terminated.
• However, if the test expression is evaluated to true, statements inside the body of
the for loop are executed,
• and the update expression is updated.
• Again the test expression is evaluated.
This process goes on until the test expression is false. When the test expression is false,
the loop terminates.
Example: Display numbers from 1 to 5
class Main
{
public static void main(String[] args)
{
int n = 5;
for (int i = 1; i <= n; ++i)
{
System.out.println(i);
}
}
}
Output:
1 2 3 4 5
Output:
Sum=500500
While Loop:
The Java while loop is used to iterate a part of the program repeatedly until the specified
Boolean condition is true. As soon as the Boolean condition becomes false, the loop
automatically stops.
The while loop is considered as a repeating if statement. If the number of iteration is not
fixed, it is recommended to use the while loop.
Syntax:
while (condition)
{
//code to be executed
Increment / decrement statement
}
Example: Sum of Positive Numbers Only
import java.util.Scanner;
class WhileLoop
{
public static void main(String[] args)
{
int sum = 0;
Scanner input = new Scanner(System.in);
System.out.println("Enter a number");
int number = input.nextInt();
while (number >= 0)
{
sum += number;
System.out.println("Enter a number");
number = input.nextInt();
}
System.out.println("Sum = " + sum);
input.close();
}
}
Output:
Enter a number
25
Enter a number
9
Enter a number
5
Enter a number
-3
Sum = 39
do-while Loop:
The Java do-while loop is used to iterate a part of the program repeatedly, until the specified
condition is true. If the number of iterations is not fixed and you must have to execute the
loop at least once, it is recommended to use a do-while loop.
Java do-while loop is called an exit control loop. Therefore, unlike while loop and for loop,
the do-while check the condition at the end of loop body. The Java do-while loop is
executed at least once because condition is checked after loop body.
Syntax:
Do
{
//code to be executed / loop body
//update statement
}
While (condition);
In the below example, we print integer values from 1 to 10. Unlike the for loop, we
separately need to initialize and increment the variable used in the condition (here, i).
Otherwise, the loop will execute infinitely.
Example Program:
public class DoWhileExample
{
public static void main(String[] args)
{
int i=1;
do
{
System.out.println(i);
i++;
}
while(i<=10);
}
}
Output:
10
For-each loop in Java:
The Java for-each loop or enhanced for loop is introduced since J2SE 5.0.
It provides an alternative approach to traverse the array or collection in Java.
It is mainly used to traverse the array or collection elements.
The advantage of the for-each loop is that it eliminates the possibility of bugs and
makes the code more readable.
It is known as the for-each loop because it traverses each element one by one.
The drawback of the enhanced for loop is that it cannot traverse the elements in
reverse order.
you do not have the option to skip any element because it does not work on an
index basis. Moreover, you cannot traverse the odd or even elements only.
For-each is another array traversing technique like for loop, while loop, do-while
loop introduced in Java5.
import java.util.*;
class ForEachExample2
{
public static void main(String args[])
{
ArrayList<String> list=new ArrayList<String>(); //Creating a list of elements
list.add("Vimal");
list.add("Sonoo");
list.add("Sameena");
for(String s:list) //traversing the list of elements using for-each loop
{
System.out.println(s);
}
}
}
Output:
Vimal n
Sonoo
Sameena
class For_Each
{
public static void main(String[] arg)
{
{
int[] marks = { 50, 80, 95, 99, 49,56,98 };
int highest_marks = maximum(marks);
System.out.println("The highest score is " + highest_marks);
}
}
public static int maximum(int[] numbers)
{
int max = numbers[0];
// for each loop
for (int num : numbers)
{
if (num > max)
{
max = num;
}
}
return max;
}
}
Output:
The highest score is 99
Explain about the jumping Statements/ control statements with example.
Jump Statements in Java
Introduction:
Jump statements are control statements that transfer execution control
from one point to another point in the program. There are two Jump statements that are
provided in the Java programming language:
1. Break statement.
2. Continue statement.
Or
The execution of a Java program is done in sequential order. Looping statements like for,
while, and do-while are used to execute a set of statements repeatedly. If such an
execution were to continue, it would go on forever. This can be prevented by adding
appropriate terminating conditions to the loop or by implementing jump statements. A
jump statement helps transfer the control of a program from one line of the code to
another and skip the ones in between.
1.Break Statement:
In java, the break statement is used to terminate the execution of the
nearest looping statement or switch statement. The break statement is widely used with
the switch statement, for loop, while loop, do-while loop.
Syntax:
break;
When a break statement is found inside a loop, the loop is terminated, and the control
reaches the statement that follows the loop. here is an example:
For( )//
{
For( ) For ( )
{ {
break;
break; }
} }
Example Program:
import java.io.*;
class Break
{
public static void main(String[] args)
{
int n = 10;
for (int i = 0; i < n; i++)
{
if (i == 6)
break;
System.out.println(i);
}
}
}
Output:
0
1
2
3
4
5
Example: 2
public class Break2
{
public static void main(String args[])
{
int i = 3;
switch(i)
{
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;
default:
System.out.println("Other");
}
}
}
Output :
Three
Goto:
The goto keyword is a commonly used jump statement in C/C++. However, Java
uses break statements to perform the same function as goto. Labels can be used to identify
blocks of code in Java. Any valid identifier followed by a semicolon represents a label.
We can break out of a labelled block by mentioning the label name after the break
keyword.
Output:
0
1
2
Example:2
class MyClass
{
public static void main( String args[] )
{
label:
for (int i=0;i<6;i++)
{
if (i==3)
{
break label; // exits the loop when it reaches 3
}
System.out.println(i);
}
}
}
Output:
0
1
2
Continue statement:
Continue is a jump statement used when a loop’s current iteration is
to be skipped. It allows the control to temporarily exit the loop and ignore the remaining
statements that follow. After this jump, the control immediately moves with the next
iteration of the same loop.
Note:
Qns.
What is the difference between the break and continue statement?
A break statement terminates its loop and resumes execution out of it. On the other hand,
a continue statement temporarily exits the loop and resumes with the next iteration.
Qns.
Is goto used in Java?
Unlike C/C++, Java does not use goto as a jump statement, but still considers it a
keyword. This means that it cannot be used as an identifier. The use of goto in Java makes
the code complex and difficult to understand. Hence, the break statement handles the
function of goto in a simpler way.
What is an Array and explain different types of arrays in java
Arrays:
type var-name[];
OR
type[] var-name;
Disadvantages:
Size Limit:
We can store only the fixed size of elements in the array. It doesn't grow its size
at runtime.
One Dimensional Array in java is always used with only one subscript
( [ ] ).
One Dimensional Array in java is always used with only one subscript (
[]).
A one-dimensional array behaves likes a list of variables.
You can access the variables of an array by using an index in square
brackets preceded by the name of that array.
Index value should be an integer. Before using the array, we must declare
it.
type var-name[];
OR
type[] var-name;
Example Program:1
class OnedimenisionaArray
{
public static void main(String[] args)
{
int[] arr; // declares an Array of integers.
arr = new int[5]; // allocating memory for 5 integers.
arr[0] = 10; // initialize the first elements of the array
arr[1] = 20; // initialize the second elements of the array
arr[2] = 30;
arr[3] = 40;
arr[4] = 50;
// accessing the elements of the specified array
for (int i = 0; i < arr.length; i++)
System.out.println("Element at index " + i + " : " + arr[i]);
}
}
Output:
Element at index 0 : 10
Element at index 1 : 20
Element at index 2 : 30
Element at index 3 : 40
Element at index 4 : 50
Multidimensional Arrays:
Multidimensional Arrays can be defined in simple
words as array of arrays. Data in multidimensional arrays are stored in tabular
form (in row major order).
data_type[1st dimension][2nd dimension][]..[Nth
dimension] array_name = new data_type[size1][size2]….[sizeN];
data_type: Type of data to be stored in the array. For example: int, char,
etc.
dimension: The dimension of the array created. For example: 1D, 2D, etc.
array_name: Name of the array
size1, size2, …, sizeN: Sizes of the dimensions respectively.
Two dimensional array:
2D array can be defined as an array of arrays. The
2D array is organized as matrices which can be represented as the collection of
rows and columns. The 2d array represents with two sub scripts.
Initializing 2D Arrays:
Output:
279
361
742
Multidimensional array:
Three – dimensional array is a complex form of a
multidimensional array. A three – dimensional array can be seen as an array of
two – dimensional array for easier understanding. Multi-dimensional array
represents with three subscripts. Elements in three-dimensional arrays are
commonly referred by x[i][j][k] where ‘i’ is the array number, ‘j’ is the row
number and ‘k’ is the column number.
Example:3
class MultiDimensional
{
public static void main(String[] args)
{
int[][][] arr = { { { 1, 2 }, { 3, 4 } },
{ { 5, 6 }, { 7, 8 } } };
Output:
12
34
56
78
Practice Programs:1
Output:
Original array: 1 2 3 4 5
Array in reverse order:
54321
Example:2
Output:
Elements of given array present on even position:
2
4
Example:3
public class OddPosition
{
public static void main(String[] args)
{
//Initialize array
int [] arr = new int [] {1, 2, 3, 4, 5};
System.out.println("Elements of given array present on odd position: ");
//Loop through the array by incrementing value of i by 2
for (int i = 0; i < arr.length; i = i+2)
{
System.out.println(arr[i]);
}
}
}
Output:
Elements of given array present on odd position:
1
3
5
Example:4
public class OddEvenInArrayExample
{
public static void main(String args[])
{
int a[]={1,2,5,6,3,2};
System.out.println("Odd Numbers:");
for(int i=0;i<a.length;i++)
{
if(a[i]%2!=0)
{
System.out.println(a[i]);
}
}
System.out.println("Even Numbers:");
for(int i=0;i<a.length;i++)
{
if(a[i]%2==0)
{
System.out.println(a[i]);
}
}
}
}
Output:
Odd Numbers:
1
5
3
Even Numbers:
2
6
2
Example: add two matrices
Output:
268
486
469
Example: multiply two matrices
Output:
6 6 6
12 12 12
18 18 18
Example: Transpose matrix
Output:
Printing Matrix without transpose:
134
243
345
Printing Matrix After Transpose:
123
344
435
Class and Objects
Or
Collection of objects is called class. It is a logical entity. Once a class has been
defined, we can create any number of objects belongs to that class.
For Example:
Fields
Methods
Constructors
Blocks
Nested class and interface
Once a class has been defined, we can create any number of objects belongs to that
class. Each object associated with data and Methods.
For Example “Fruit” is a class and Mango, Apple and Banana are objects.
class <class_name>
field; method;
1
Example:1
class Student
{
int id; //field or data member or instance variable
String name;
public static void main(String args[])
{
Student s1=new Student();//creating an object of Student
//Printing values of the object
System.out.println(s1.id); //accessing member through reference variable
System.out.println(s1.name);
}
}
Output:
O
Null
Example: 2
class Student
{
int id;
String name;
}
class TestStudent3
{
public static void main(String args[])
{
Student s1=new Student(); //Creating objects
Student s2=new Student();
s1.id=101; //Initializing objects
s1.name="Sonu";
s2.id=102;
s2.name="Monu";
System.out.println(s1.id+" "+s1.name); //Printing data
System.out.println(“ \n”);
System.out.println(s2.id+" "+s2.name);
}
}
Output:
101 Sonu
102 Monu
2
Multiple Classes:
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=1122;
String name="Amith";
}
//Creating another class TestStudent1 which contains the main method
class Student123
{
public static void main(String args[])
{
Student s1=new Student();
System.out.println(s1.id);
System.out.println(" \n");
System.out.println(s1.name);
}
}
Output:
1122
Amith
3
Object in Java:
The Object is the real-time entity having some state and behavior. In Java, Object is
an instance of the class having the instance variables as the state of the object and
the methods as the behaviour of the object. The object of a class can be created by
using the new keyword in Java Programming language.
Objects are run time entities in an object-oriented System. They may represent a
person, place, Place, Bank Account, a table of data or anu other item. that has state
and behavior is known as an object.
For example, a chair, pen, table, keyboard, bike, etc. It can be physical or logical.
class Parul
{
// Declaring and initializing string
String name = " PARUL UIVERSITY @ Vadodara";
public static void main(String[] args) // Main driver method
{
Parul obj = new Parul(); // using new keyword
// Print and display the object
System.out.println(obj.name);
}
}
Output:
PARUL UIVERSITY @ Vadodara
4
2.Using Object Cloning – clone() method:
Output:
5
3.Using newInstance() Method of Class class:
The newInstance() method of the Class class is also used to create an object. It calls
the default constructor to create the object. It returns a newly created instance of the
class represented by the object. It internally uses the newInstance() method of the
Constructor class.
Example:
public class CreateObjectExample4
{
void show()
{
System.out.println("A New Object Created.");
}
public static void main(String[] args)
{
try
{
//creating an instance of Class class
Class cls = Class.forName("CreateObjectExample4");
//creates an instance of the class using the newInstance() method
CreateObjectExample4 obj = (CreateObjectExample4) cls.newInstance();
//invoking the show() method
obj.show();
}
catch (ClassNotFoundException e)
{
e.printStackTrace();
}
catch (InstantiationException e)
{
e.printStackTrace();
}
catch (IllegalAccessException e)
{
e.printStackTrace();
}
}
}
6
Output:
import java.lang.reflect.*;
class Parul
{
// Member variables of this class
private String name;
// Constructor of this class
Parul() {}
// Method 1
// To set name of the string
public void setName(String name)
{
// This method refers to current object itself
this.name = name;
}
// Main driver method
public static void main(String[] args)
{
// Try block to check for exceptions
try
{
Constructor<Parul> constructor= Parul.class.getDeclaredConstructor();
Parul r = constructor.newInstance();
// Custom passing
r.setName("PIET @ Parul University");
System.out.println(r.name);
}
// Catch block to handle the exceptions
catch (Exception e)
{
7
// Display the exception on console
// using printStackTrace() method
e.printStackTrace();
}
}
}
Output:
5.Using deserialization
Serialization
import java.io.*;
class Persist
{
public static void main(String args[])
{
Try
{
//Creating the object
Student s1 =new Student(211,"ravi");
//Creating stream and writing the object
FileOutputStream fout=new FileOutputStream("f.txt");
ObjectOutputStream out=new ObjectOutputStream(fout);
out.writeObject(s1);
out.flush();
//closing the stream
out.close();
System.out.println("success");
}
catch(Exception e)
8
{
System.out.println(e);
}
}
}
Output:
Success
Deserialization:
import java.io.*;
class Depersist
{
public static void main(String args[])
{
Try
{
//Creating stream to read the object
ObjectInputStream in=new ObjectInputStream(new FileInputStream("f.txt"));
Student s=(Student)in.readObject();
//printing the data of the serialized object
System.out.println(s.id+" "+s.name);
//closing the stream
in.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
}
Output:
111
Ram
9
What is a method in Java?
Method Declaration:
10
Method Signature:
Access Specifier:
Access specifier or modifier is the access type of the method. It specifies the visibility
of the method. Java provides four types of access specifier:
Public: The method is accessible by all classes when we use public specifier
in our application.
Private: When we use a private access specifier, the method is accessible only
in the classes in which it is defined.
Protected: When we use protected access specifier, the method is accessible
within the same package or subclasses in a different package.
Default: When we do not use any access specifier in the method declaration,
Java uses default access specifier by default. It is visible only from the same
package only.
Return Type:
Return type is a data type that the method returns. It may have a primitive data type,
object, collection, void, etc. If the method does not return anything, we use void
keyword.
Method Name:
Parameter List:
11
Method Body:
o Predefined Method
o User-defined Method
Predefined Method:
In Java, predefined methods are the method that is already defined in the Java
class libraries is known as predefined methods.
It is also known as the standard library method or built-in method.
We can directly use these methods just by calling them in the program at any
point.
Some pre-defined methods are length(), equals(), compareTo(), sqrt(), etc.
When we call any of the predefined methods in our program, a series of
codes related to the corresponding method runs in the background that is
already stored in the library.
Each and every predefined method is defined inside a class.
Such as print() method is defined in the java.io.PrintStream class.
It prints the statement that we write inside the method.
For example, print("Java"), it prints Java on the console
12
Example:1
Example:2
13
User-defined Method:
Let's create a user defined method that checks the number is even or odd. First, we
will define the method.
14
Example:
import java.util.Scanner;
public class EvenOdd
{
public static void main (String args[])
{
//creating Scanner class object
Scanner scan=new Scanner(System.in);
System.out.print("Enter the number: ");
//reading value from the user
int num=scan.nextInt();
//method calling
findEvenOdd(num);
}
}
Output :
Enter the number: 12
12 is a even number
Types:
1.Static Methods: it is implement the behaviour of the class.
Static Method:
A static method in Java is a method that is part of a class rather than an instance
of that class.
Every instance of a class has access to the method.
Static methods have access to class variables (static variables) without using
the class's object (instance).
Only static data may be accessed by a static method
15
We can also create a static method by using the keyword static before the
method name.
The main advantage of a static method is that we can call it without creating
an object.
It can access static data members and also change the value of it. It is used to
create an instance method.
It is invoked by using the class name. The best example of a static method is
the main() method.
16
Non-Static Example:
class Student
{
int rollno;
String name;
void insertRecord(int r, String n)
{
rollno=r;
name=n;
}
void displayInformation()
{
System.out.println(rollno+" "+name);
}
}
class TestStudent4
{
public static void main(String args[])
{
Student s1=new Student();
Student s2=new Student();
s1.insertRecord(111,"William");
System.out.println(" \n");
s2.insertRecord(222,"Smith");
s1.displayInformation();
s2.displayInformation();
}
}
Output:
111 William
222 Smith
17
import java.io.*;
class Geek
{
public static String geekName = "";
public static void geek(String name)
{
geekName = name;
}
}
class GFG
{
public static void main(String[] args)
{
// Accessing the static method geek()
// and field by class name itself.
Geek.geek("Abhinav");
System.out.println(Geek.geekName);
// Accessing the static method geek()
// by using Object's reference.
Geek obj = new Geek();
obj.geek("Amith");
System.out.println(obj.geekName);
}
}
Output:
Abhinav
Amith
18
Method Overloading:
If a class has multiple methods having same name but different in parameters, it is
known as Method Overloading.
If we have to perform only one operation, having same name of the methods increases
the readability of the program.
Suppose you have to perform addition of the given numbers but there can be any
number of arguments, if you write the method such as a(int, int) for two parameters,
and b(int, int, int) for three parameters
19
1.Method Overloading: changing no. of arguments:
In this example, we have created two methods, first add() method performs addition
of two numbers and second add method performs addition of three numbers.
class Adding
{
static int add(int a,int b)
{
return a+b;
}
static int add(int a,int b,int c)
{
return a+b+c;
}
}
class TestOverloading1
{
public static void main(String[] args)
{
System.out.println(Adding.add(100,200));
System.out.println(Adding.add(100,200,300));
}
}
Output:
300
600
20
2.Method Overloading: changing data type of arguments
In this example, we have created two methods that differs in data type. The first add
method receives two integer arguments and second add method receives two double
arguments.
class Adding
{
static int add(int a, int b)
{
return a+b;
}
static double add(double a, double b, double c)
{
return a+b+c;
}
}
class TestOverloading2
{
public static void main(String[] args)
{
System.out.println(Adding.add(100,200));
System.out.println(Adding.add(100.55,200.55,300.33));
}
}
Output:
300
601.4300000000001
21
Method Overriding:
If subclass (child class) has the same method as declared in the parent class, it is
known as method overriding in Java.
In this example, we have defined the run method in the subclass as defined in the
parent class but it has some specific implementation. The name and parameter of the
method are the same, and there is IS-A relationship between the classes, so there is
method overriding.
In other words, If a subclass provides the specific implementation of the method that
has been declared by one of its parent class, it is known as method overriding.
class Vehicle
{
void run()
{
System.out.println("Vehicle is running");
}
}
class Bike extends Vehicle //Creating a child class
{
public static void main(String args[])
{
Bike obj = new Bike(); //creating an instance of child class
obj.run(); //calling the method with child class instance
}
}
22
Output:
Vehicle is running
//Java Program to illustrate the use of Java Method Overriding
//Creating a parent class.
Example:
class Vehicle
{
//defining a method
void run()
{
System.out.println("Vehicle is running");
}
}
//Creating a child class
class Bike2 extends Vehicle
{
//defining the same method as in the parent class
void run()
{
System.out.println("Bike Is Running Safely");
}
public static void main(String args[])
{
Bike2 obj = new Bike2();//creating object
obj.run();//calling method
}
}
Output:
23
Constructor:
Default Constructor:
class Bike1
{
//creating a default constructor
Bike1()
{
System.out.println("Bike is created");
}
//main method
public static void main(String args[])
{
//calling a default constructor
Bike1 b=new Bike1();
}
}
Output:
Bike is created
24
1.Parameterized Constructor:
A constructor which has a specific number of
parameters is called a parameterized constructor. The parameterized constructor is
used to provide different values to distinct objects. However, you can provide the
same values also.
Example:
class Student4
{
int id;
String name;
Student4(int i, String n) //creating a parameterized constructor
{
id = i;
name = n;
}
void display() //method to display the values
{
System.out.println(id+" "+name);}
public static void main(String args[])
{
Student4 s1 = new Student4(111,"Karan"); //creating objects and passing values
Student4 s2 = new Student4(222,"Aryan"); //calling method to display the values of
object
s1.display();
s2.display();
}
}
Output:
111 Karan
222 Aryan
25
2.Constructor overloading in java:
The constructor overloading can be defined
as the concept of having more than one constructor with different parameters list, so
that every constructor can perform a different task.
26
Difference between constructor and method in Java
There are many differences between constructors and methods. They are given
below.
A constructor must not have a return type. A method must have a return
type.
The constructor name must be same as the class The method name may or may
name. not be same as the class name.
27
Encapsulation:
Wrapping up data and methods into a single unit is known as Encapsulation. The
data not accessible from out side the world and only access those methods, which
are wrapped in the class, it can access it.
Data
Informtion in And information out
Method
Example:
class Area
{
int length;
int breadth; // fields to calculate area
// constructor to initialize values
Area(int length, int breadth)
{
this.length = length;
this.breadth = breadth;
}
// method to calculate area
public void getArea()
{
int area = length * breadth;
System.out.println("Area: " + area);
}
}
class Main
{
public static void main(String[] args)
{
// create object of Area
// pass value of length and breadth
Area rectangle = new Area(5, 6);
rectangle.getArea();
}
}
Output:
30
28
Polymorphism:
Example:
class Shape
{
void draw()
{
System.out.println("drawing...");
}
}
class Rectangle extends Shape
{
void draw()
{
System.out.println("drawing rectangle...");
}
}
class Circle extends Shape
{
void draw()
{
System.out.println("drawing circle...");
}
}
29
class Triangle extends Shape
{
void draw()
{
System.out.println("drawing triangle...");
}
}
class TestPolymorphism2
{
public static void main(String args[])
{
Shape s;
s=new Rectangle();
s.draw();
s=new Circle();
s.draw();
s=new Triangle();
s.draw();
}
}
Output
drawing rectangle...
drawing circle...
drawing triangle...
30
Abstraction:
Abstraction refers to the act of representing essential feature without
including the background details or explanation. Classes use the abstraction
concepts and defined a list of abstract attributes.
Example:
for example, sending SMS where you type the text and send the message.
You don't know the internal processing about the message delivery.
Example:
31
}
Output:
32
Inheritance:
Inheritance is an important pillar of OOP (Object-Oriented
Programming). It is the mechanism in java by which one class is allowed to inherit
the features (fields and methods) of another class. In Java, inheritance means
creating new classes based on existing ones. A class that inherits from another
class can reuse the methods and fields of that class.
On the basis of class, there can be three types of inheritance in java: single, multilevel
and hierarchical.
When a class inherits another class, it is known as a single inheritance. In the example
given below, Dog class inherits the Animal class, so there is the single inheritance.
33
Example:
class Employee
{
float salary=40000;
}
class Programmer extends Employee
{
int bonus=10000;
public static void main(String args[])
{
Programmer p=new Programmer();
System.out.println("Programmer salary is:"+p.salary);
System.out.println("Bonus of Programmer is:"+p.bonus);
}
}
Output:
Programmer salary is:40000.0
Bonus of Programmer is:10000
34
Multilevel Inheritance Example
When there is a chain of inheritance, it is known
as multilevel inheritance. Multilevel Inheritance in java involves inheriting a class,
which already inherited some other class. Multilevel Inheritance in Java is a type of
inheritance in which a class that is already inherited by another class, inherits another
class.
class Student
{
int reg_no;
void getNo(int no)
{
reg_no=no;
}
void putNo()
{
System.out.println("registration number= "+reg_no);
}
}
//intermediate sub class
class Marks extends Student
{
float marks;
35
void getMarks(float m)
{
marks=m;
}
void putMarks()
{
System.out.println("marks= "+marks);
}
}
class Sports extends Marks //derived class
{
float score;
void getScore(float scr)
{
score=scr;
}
void putScore()
{
System.out.println("score= "+score);
}
}
class MultilevelInheritanceExample
{
public static void main(String args[])
{
Sports ob=new Sports();
ob.getNo(123);
ob.putNo();
ob.getMarks(78);
ob.putMarks();
ob.getScore(68);
ob.putScore();
}
}
Output:
registration number= 123
marks= 78.0
score= 68.0
36
Hierarchical Inheritance:
Syntax:
Class Parent
{
//Data members and member functions of Parent Class
}
Class Derived-1 : access modifier Parent
{
//Data members and member functions of Derived-1 class
}
Class Derived-2 : access modifier Parent
{
//Data members and member functions of Derived-2 class
}
37
Example:
class Student
{
public void methodStudent()
{
System.out.println("The method of the class Student invoked.");
}
}
class Science extends Student
{
public void methodScience()
{
System.out.println("The method of the class Science invoked.");
}
}
class Commerce extends Student
{
public void methodCommerce()
{
System.out.println("The method of the class Commerce invoked.");
}
}
class Arts extends Student
{
public void methodArts()
{
System.out.println("The method of the class Arts invoked.");
}
}
public class HierarchicalInheritanceExample
{
public static void main(String args[])
{
Science sci = new Science();
Commerce comm = new Commerce();
Arts art = new Arts();
//all the sub classes can access the method of super class
sci.methodStudent();
38
comm.methodStudent();
art.methodStudent();
}
}
Output:
39
What is a multiple inheritance:
When a class inherits properties from many classes, this is
known as multiple inheritance. Multiple Inheritance is not supported by Java. But using Interfaces,
Multiple Inheritance is possible in Java.
Example:
interface A
{
public abstract void execute1();
}
interface B
{
public abstract void execute2();
}
class C implements A,B
{
public void execute1()
{
System.out.println("Haii.. I am from execute1");
}
public void execute2()
{
System.out.println("Haii.. I am from execute2");
}
}
class Main
{
public static void main(String[] args)
{
C obj = new C(); // creating object of class C
obj.execute1(); //calling method execute1
obj.execute2(); // calling method execute2
}
}
40
Output:
41
Hybrid inheritance:
the hybrid inheritance is the composition of two or more types of inheritance. The
main purpose of using hybrid inheritance is to modularize the code into well-
defined classes. It also provides the code reusability.
Single and Multiple Inheritance (not supported but can be achieved through
interface)
Multilevel and Hierarchical Inheritance
Hierarchical and Single Inheritance
Multiple and Multilevel Inheritance.
class GrandFather
{
public void show()
{
System.out.println("I am grandfather.");
}
}
//inherits GrandFather properties
class Father extends GrandFather
{
public void show()
{
System.out.println("I am father.");
42
}
}
//inherits Father properties
class Son extends Father
{
public void show()
{
System.out.println("I am son.");
}
}
//inherits Father properties
public class Daughter extends Father
{
public void show()
{
System.out.println("I am a daughter.");
}
public static void main(String args[])
{
Daughter obj = new Daughter();
obj.show();
}
}
Output:
I am a daughter.
43
Super keyword:
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 super keyword. The keyword “super” came into the
picture with the concept of Inheritance. It is majorly used in the following
contexts:
Example:
class Vehicle
{
int maxSpeed = 120;
}
class Car extends Vehicle // sub class Car extending vehicle
{
int maxSpeed = 180;
void display()
{
// print maxSpeed of base class (vehicle)
System.out.println("Maximum Speed: " + super.maxSpeed);
}
}
class Test // Driver Program
{
public static void main(String[] args)
{
Car small = new Car();
small.display();
}
}
Output:
Maximum Speed: 120
44
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:
class Person
{
void message()
{
System.out.println("This is person class\n");
}
}
// Subclass Student
class Student extends Person
{
void message()
{
System.out.println("This is student class");
}
// Note that display() is
// only in Student class
void display()
{
// will invoke or call current
// class message() method
message();
// will invoke or call parent
// class message() method
super.message();
}
}
// Driver Program
class Test
{
public static void main(String args[])
{
Student s = new Student();
// calling display() of Student
s.display();
}
}
45
Output:
Example:
class Person
{
Person()
{
System.out.println("Person class Constructor");
}
}
// subclass Student extending the Person class
class Student extends Person
{
Student()
{
// invoke or call parent class constructor
super();
System.out.println("Student class Constructor");
}
}
class Test // Driver Program
{
public static void main(String[] args)
{
Student s = new Student();
}
}
Output:
46
Topic:1
Nested classes:
Writing a class within another is allowed in Java.
The class written within is called the nested class, and the class that holds
the inner class is called the outer class.
Nested classes are divided into two categories: static and non-static.
Nested classes that are declared static are simply called static nested
classes.
Non-static nested classes are called inner classes.
In Java, a nested class is a class that is defined inside some other class.
Nested classes are used to group certain classes to improve the readability
of the code.
The scope of a nested class is the same as its outer class.
Nested classes can access any member of the outer class, even if the outer
class is private.
Syntax:
class parent_class
{
static class static_child_class
{
// code
}
}
From the inner class, if we want to access any static method of the outer class,
we do not need any object; we can call it directly.
Syntax:
class Outer
{
//code
class Inner
{
//code
}
}
Example:
class parent_class
{
String s = "Parul University:-";
class child_class // child class
{
void print(String x)
{
System.out.println(s + " " + x);
}
}
public static void main(String args[])
{
parent_class parentObj = new parent_class();// parent class object
child_class childObj = parentObj.new child_class (); // child class object
using parent class object
String y = "Vadodara @ Gujarat";
childObj.print(y); // calling methods of child class
}
}
Output:
Parul University:- Vadodara @ Gujarat
Local Inner Classes:
A Local Inner class is a class that is defined inside any
block, i.e., for block, if block, methods, etc. Similar to local variables, the
scope of the Local Inner Class is restricted to the block where it is defined.
Syntax:
class class_name
{
void method_name()
{
// code
if(conditions)
{
// or any other block like while, for, etc.
class localInnerClass
{
void localInnerMethod()
{
// code
}
}
}
// code
}
}
Example:
class parent_class
{
public static void main(String args[])
{
String p = "Parul University";
if (p.charAt(0) = = 'P')
{
class child_class // child class
{
void print(String x)
{
System.out.println(p + " " + x);
}
}
child_class childObj = new child_class(); // child class object
String y = "Vadodara @ Gujarat";
childObj.print(y); // calling child class method
// child_class is accessible till here only
}
// child_class is not accessible here
}
}
Output:
Parul University Vadodara @ Gujarat
Anonymous Inner Classes:
Anonymous Inner class is an inner class but without a name. It has only a
single object. It is used to override a method. It is only accessible in the block
where it is defined.
Abstract is a keyword, its non-accessing modifier, its used for classes and
Methods.
Abstract Class: Abstract class is a restricted class that can’t be used to
create Object, it must be inherited from another class.
Abstract Methods: abstract method is used only in abstract class, it does
not have any body
Syntax:
abstractClass obj = new abstractClass()
{
void methods()
{
// code
}
};
Example:
abstract class Printer
{
abstract void print (String x);
}
class parent_class // Parent Class
{
public static void main(String args[])
{
Printer obj = new Printer() // Anonymous Inner Class
{
void print(String x)
{
System.out.println("Parul University, " + x);
}
};
String y = "Vadodara @ Gujarat";
obj.print(y);
}
}
Output:
Parul University, Vadodara @ Gujarat
*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
Topic:2
this keyword in Java:
The main purpose of using this keyword is to solve the confusion when we have
same variable name for instance and local variables.
Example:
class ThisKeyWord
{
Double width, height, depth;
ThisKeyWord (double w, double h, double d)
{
this.width = w;
this.height = h;
this.depth = d;
}
public static void main(String[] args)
{
ThisKeyWord Obj = new ThisKeyWord(100,200,300);
System.out.println("width = "+ Obj.width);
System.out.println("height = "+ Obj.height);
System.out.println("depth = "+ Obj.depth);
}
}
Output:
width = 100.0
height = 200.0
depth = 300.0
Calling Constructor using this keyword:
We can call a constructor from inside the another function by using this
keyword
Example:
In this example, we are calling a parameterized constructor from the non-
parameterized constructor using the this keyword along with argument.
Example:
class ThisKeyWordConstructor
{
ThisKeyWordConstructor ()
{
this("CSE Dept @ Parul University "); // Calling constructor
}
ThisKeyWordConstructor(String str)
{
System.out.println(str);
}
public static void main(String[] args)
{
ThisKeyWordConstructor This = new ThisKeyWordConstructor();
}
}
Output:
Example:
In this example, we are accessing getName () method using this and it works
fine as works with object reference.
Example Program:
class ThisMethod
{
public void getName()
{
System.out.println("Department of CSE @ Parul");
}
public void display()
{
this.getName();
}
public static void main(String[] args)
{
ThisMethod Obj = new ThisMethod ();
Obj.display();
}
}
Output:
*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
Topic:3
The access specifiers used with classes In Interface only one specifier is used-
are private, protected and public. Public.
Constructors can be included in a class but not an inheritance.
A method body can exist in a class. but it cannot exist in an interface.
Classes do not support multiple but it is supported by inheritance.
inheritance.
Example
interface Pet
{
public void test();
}
class Dog implements Pet
{
public void test()
{
System.out.println("Interface Method Implemented");
}
public static void main(String args[])
{
Pet p = new Dog();
p.test();
}
}
Output:
interface Bank
{
float rateOfInterest(); SBI ICICI
}
class SBI implements Bank
{
public float rateOfInterest()
{
return 7.15f;
}
}
class ICICI implements Bank
{
public float rateOfInterest()
{
return 8.7f;
}
}
class TestInterface2
{
public static void main(String[] args)
{
Bank b=new ICICI ();
System.out.println("ROI: "+b.rateOfInterest());
}
}
Output:
ROI: 8.7
Multiple inheritance in Java by interface:
If a class implements multiple interfaces, or an interface extends multiple
interfaces, it is known as multiple inheritance.
interface int1
{ int1 int2
int i=20;
void print();
}
Test
interface int2
{
void show();
}
class test implements int1, int2
{
public void print()
{
System.out.println("Hello");
}
public void show()
{
System.out.println("Welcome");
}
public static void main(String args[])
{
test obj=new test();
obj.print();
obj.show();
obj.i=30;
System.out.println(obj.i);
}
}
Output:
Hello
Welcome
20
interface A
{
void print();
}
interface B
{
void show();
}
class C implements A, B
{
A B
public void print()
Interface Interface
{
System.out.println("Hello");
}
public void show() C
Class
{
System.out.println("Welcome to CSE");
}
public static void main(String args[])
{
C obj = new C();
obj.print();
obj.show();
}
}
Output:
Hello
Welcome to CSE
Example : 2
/*
* Interface extends multiple interfaces java example
*/
interface A
{
void printa();
A B
}
interface B
{
void printb(); C
}
interface C extends A,B
{ XYZ
void printc();
}
class XYZ implements C
{
public void printa()
{
System.out.println("im from interface A");
}
public void printb()
{
System.out.println("im from interface B");
}
public void printc()
{
System.out.println("im from interface C");
}
}
class Sample
{
public static void main(String[] args)
{
XYZ obj = new XYZ();
obj. printa();
obj. printb();
obj. printc();
}
}
Output:
im from interface A
im from interface B
im from interface C
*-*-*-**-*-*-*-*-*-*-*-*-*
Topic:4
Package:
A package can be defined as a group of similar types of classes, interface,
enumeration or sub-package.
Using package, it becomes easier to locate the related classes and it also
provides a good structure for projects with hundreds of classes and other
files.
package mypackage;
public class student
{
Statement;
…………..
…………..
…………..
}
The above statement will create a package name mypackage in the
project directory.
Java uses file system directories to store packages.
For example, the .java file for any class you define to be part of
mypackage package must be stored in a directory called mypackage.
Additional points about package:
A package is always defined as a separate folder having the same
name as the package name.
Store all the classes in that package folder.
All classes of the package which we wish to access outside the
package must be declared public.
All classes within the package must have the package statement as its
first line.
All classes of the package must be compiled before use (So that they
are error free)
The packages are classified into two types.
Built-in Packages
User-defined packages
1.Built-in Packages: (Pre-defined packages)
These packages consist of a large number of classes which
are a part of Java API. Some of the commonly used built-in packages are:
1) java.lang:
Contains language support classes (e.g classed which defines
primitive data types, math operations). This package is automatically imported
by default.
2)java.io:
Contains classed for supporting input / output operations. It will
perform Read/Write operations.
3)java.util:
Contains utility classes which implement data structures like
Linked List, Dictionary and support; for Date / Time operations.
Ex: java.util.*;
ex: java.util.scanner class
4)java.applet:
Contains classes for creating Applets.
5)java.awt:
Contain classes for implementing the components for graphical
user interfaces (GUI) like button, menus etc..
6)java.net:
Contain classes for supporting networking operations. Like Client
Server programs and networking operation in java
2.User-defined packages:
These are the packages that are defined by the user.
first we create a directory myPackage (name should be same as the name of
the package). Then create the MyClass inside the directory with the first
statement being the package names.
package mypack;
public class Simple
{
public static void main(String args[])
{
System.out.println("Welcome to package");
}
}
1. import package.*;
2. import package.classname;
3. fully qualified name.
1. Using packagename.*;
All the classes and interfaces of this package can be accessed (imported)
from outside the packages.
If you use package.* then all the classes and interfaces of this package
will be accessible but not subpackages.
The import keyword is used to make the classes and interface of another
package accessible to the current package.
2) Using packagename.classname:
class B
{
public static void main(String args[])
{
A obj = new A();
obj.msg();
}
}
Output:
Hello
Note:
pack.A it access only class A, if you use java.util.* it will access all
java.util, we can access all Linkedlist, date, Calendar and Hash table.
If you use fully qualified name then only declared class of this package
will be accessible.
Now there is no need to import. But you need to use fully qualified name
every time when you are accessing the class or interface.
It is generally used when two packages have same class name e.g.
java.util and java.sql packages contain Date class.
Subpackage in java:
Package inside the package is called the subpackage. It
should be created to categorize the package further.
package com.javatpoint.core;
class Simple
{
public static void main(String args[])
{
System.out.println("Hello subpackage");
}
}
For example:
//save as Simple.java
package mypack;
public class Simple
{
public static void main(String args[])
{
System.out.println("Welcome to package");
}
}
To Compile:
e:\sources> javac -d c:\classes Simple.java
To Run:
To run this program from e:\source directory, you need to set classpath of the
directory where the class file resides.
e:\sources> set classpath=c:\classes;.;
e:\sources> java mypack.Simple.
IO Package:
The java.io package helps the user to perform all types of input-output
operations.
Java IO package is primarily focused on input-output files, network
streams, internal memory buffers, etc.
Data is read and written from Java
IO's InputStream and OutputStream classes.
In other words, IO streams in java help to read the data from an input
stream such as a file and write the data into an output stream such as the
standard display or a file again.
It represents source as input and destination as output. It can handle all
types of data, from primitive values to advanced objects.
Input Streams.
Output Streams.
Error Streams.
Java supports three streams that are automatically attached with the console.
Input Streams:
The output of the executed program has to be stored in a file for further
use.
Output streams help us to write data to a output source (may be file).
Similarly like input streams output streams are also abstract classes that
provides a programming interface for all output streams.
The output stream is opened as soon as it is created and explicitly closed
by using the close() method.
Error Streams:
The method above helps to return the data of the next byte in the input
stream.
The value returned is between 0 to 255.
If no byte is read, the code returns -1, which indicates the end of the file.
The method above returns the number of bytes that can be read from
the input stream.
The method above closes the current input stream and releases any
system resources associated with it.
The method above reads the bytes from the input stream and stores every
byte in the buffer array.
It returns the total number of bytes stored in the buffer array.
If there is no byte in the input stream, it returns -1 as the stream is at the
end of the file.
7. public int read(byte[ ] b , int off , len) throws IOException:
Output Stream:
This method closes the current output stream and releases any system
resources associated with it.
The closed stream cannot be reopened and operations cannot be
performed within it.
2. public void flush() throws IOException:
It flushes the current output stream and forces any buffered output to be
written out.
This method writes the b.length bytes from the specified byte array to the output
stream.
4. Public void write (byte[ ] b ,int off ,int len) throws IOException:
The method above writes the specific bytes to the output stream. It
does not return a value.
Topics:7
1. Boolean:
The Boolean class wraps a value of the primitive type
boolean in an object.
2. Byte:
The Byte class wraps a value of primitive type byte in an
object.
3. Character – Set 1, Set 2:
The Character class wraps a value of the
primitive type char in an object.
4. Character.Subset:
Instances of this class represent particular subsets
of the Unicode character set.
5. Character.UnicodeBlock:
A family of character subsets
representing the character blocks in the Unicode specification.
7. ClassLoader:
A class loader is an object that is responsible for
loading classes.
8. ClassValue:
Lazily associate a computed value with (potentially)
every type.
9. Compiler:
The Compiler class is provided to support Java-to-native-
code compilers and related services.
10. Double:
The Double class wraps a value of the primitive type double
in an object.
11. Enum:
This is the common base class of all Java language
enumeration types.
12. Float:
The Float class wraps a value of primitive type float in an
object.
13. InheritableThreadLocal:
This class extends ThreadLocal to provide
inheritance of values from parent thread to child thread: when a child
thread is created, the child receives initial values for all inheritable
thread-local variables for which the parent has values.
14. Integer :
The Integer class wraps a value of the primitive type int in
an object.
15. Long:
The Long class wraps a value of the primitive type long in an
object.
16. Math – Set 1, Set 2:
The class Math contains methods for performing
basic numeric operations such as the elementary exponential,
logarithm, square root, and trigonometric functions.
17. Number:
The abstract class Number is the superclass of classes
BigDecimal, BigInteger, Byte, Double, Float, Integer, Long, and
Short.
18. Object:
Class Object is the root of the class hierarchy.
19. Package:
Package objects contain version information about the
implementation and specification of a Java package.
20. Process:
The ProcessBuilder.start() and Runtime.exec methods
create a native process and return an instance of a subclass of
Process that can be used to control the process and obtain
information about it.
21. ProcessBuilder:
This class is used to create operating system
processes.
22. ProcessBuilder.Redirect:
Represents a source of subprocess input or
a destination of subprocess output.
23. Runtime:
Every Java application has a single instance of class
Runtime that allows the application to interface with the
environment in which the application is running.
24. RuntimePermission:
This class is for runtime permissions.
25. SecurityManager:
The security manager is a class that allows
applications to implement a security policy.
26. Short:
The Short class wraps a value of primitive type short in an
object.
27. StackTraceElement:
An element in a stack trace, as returned by
Throwable.getStackTrace().
33. Thread:
A thread is a thread of execution in a program.
34. ThreadGroup:
A thread group represents a set of threads.
35. ThreadLocal:
This class provides thread-local variables.
36. Throwable:
The Throwable class is the superclass of all errors and
exceptions in the Java language.
37. Void:
The Void class is an uninstantiable placeholder class to hold a
reference to the Class object representing the Java keyword void.
Example:
public class Main
{
public static void main(String[] args)
{
// Creating objects
Boolean bool = new Boolean("False");
Byte by = new Byte("0001");
Character character = new Character('a');
Double doub = new Double("1.25");
Float fl = new Float("1.1");
Integer integer = new Integer("10");
Long l = new Long("1000000");
//printing result
System.out.println("Boolean: " + bool);
System.out.println("Byte: " + by);
System.out.println("Character: " + character);
System.out.println("Double: " + doub);
System.out.println("Float: " + fl);
System.out.println("Integer: " + integer);
System.out.println("Long: " + l);
}
}
Output:
Boolean: false
Byte: 1
Character: a
Double: 1.25
Float: 1.1
Integer: 10
Long: 1000000
Topics:8
Java.util Package:
1. AbstractCollection:
This class provides a skeletal implementation
of the Collection interface, to minimize the effort required to
implement this interface.
2. AbstractList:
This class provides a skeletal implementation of the
List interface to minimize the effort required to implement this
interface backed by a “random access” data store (such as an array).
3. AbstractMap<K,V>:
This class provides a skeletal implementation
of the Map interface, to minimize the effort required to implement
this interface.
4. AbstractMap.SimpleEntry<K,V>:
An Entry maintaining a key and
a value.
5. AbstractMap.SimpleImmutableEntry<K,V>:
An Entry
maintaining an immutable key and value.
6. AbstractQueue:
This class provides skeletal implementations of
some Queue operations.
7. AbstractSequentialList:
This class provides a skeletal
implementation of the List interface to minimize the effort required
to implement this interface backed by a “sequential access” data
store (such as a linked list).
8. AbstractSet:
This class provides a skeletal implementation of the
Set interface to minimize the effort required to implement this
interface.
9. ArrayDeque:
Resizable-array implementation of the Deque
interface.
10. ArrayList:
Resizable-array implementation of the List interface.
11. Arrays:
This class contains various methods for manipulating arrays
(such as sorting and searching).
12. BitSet:
This class implements a vector of bits that grows as needed.
13. Calendar:
The Calendar class is an abstract class that provides
methods for converting between a specific instant in time and a set
of calendar fields such as YEAR, MONTH, DAY_OF_MONTH,
HOUR, and so on, and for manipulating the calendar fields, such as
getting the date of the next week.
14. Collections:
This class consists exclusively of static methods that
operate on or return collections.
15. Currency:
Represents a currency.
16. Date:
The class Date represents a specific instant in time, with
millisecond precision.
17. Dictionary<K,V>:
The Dictionary class is the abstract parent of
any class, such as Hashtable, which maps keys to values.
18. EnumMap,V>:
A specialized Map implementation for use with
enum type keys.
19. EnumSet:
A specialized Set implementation for use with enum types.
20. EventListenerProxy:
An abstract wrapper class for an
EventListener class which associates a set of additional parameters
with the listener.
21. EventObject:
The root class from which all event state objects shall
be derived.
22. FormattableFlags:
FomattableFlags are passed to the
Formattable.formatTo() method and modify the output format for
Formattables.
23. Formatter:
An interpreter for printf-style format strings.
24. GregorianCalendar:
GregorianCalendar is a concrete subclass of
Calendar and provides the standard calendar system used by most of
the world.
25. HashMap<K,V>:
Hash table based implementation of the Map
interface.
26. HashSet:
This class implements the Set interface, backed by a hash
table (actually a HashMap instance).
27. Hashtable<K,V>:
This class implements a hash table, which maps
keys to values.
28. IdentityHashMap<K,V>:
This class implements the Map interface
with a hash table, using reference-equality in place of object-equality
when comparing keys (and values).
29. LinkedHashMap<K,V>:
Hash table and linked list implementation
of the Map interface, with predictable iteration order.
30. LinkedHashSet:
Hash table and linked list implementation of the
Set interface, with predictable iteration order.
31. LinkedList:
Doubly-linked list implementation of the List and
Deque interfaces.
32. ListResourceBundle:
ListResourceBundle is an abstract subclass
of ResourceBundle that manages resources for a locale in a
convenient and easy to use list.
33. Locale – Set 1, Set 2:
A Locale object represents a specific
geographical, political, or cultural region.
34. Locale.Builder:
Builder is used to build instances of Locale from
values configured by the setters.
35. Objects:
This class consists of static utility methods for operating
on objects.
36. Observable:
This class represents an observable object, or “data” in
the model-view paradigm.
37. PriorityQueue:
An unbounded priority queue based on a priority
heap.
38. Properties:
The Properties class represents a persistent set of
properties.
39. PropertyPermission:
This class is for property permissions.
40. PropertyResourceBundle:
PropertyResourceBundle is a concrete
subclass of ResourceBundle that manages resources for a locale
using a set of static strings from a property file.
41. Random:
An instance of this class is used to generate a stream of
pseudorandom numbers.
42. ResourceBundle:
Resource bundles contain locale-specific objects.
43. ResourceBundle.Control:
ResourceBundle.Control defines a set of
callback methods that are invoked by the ResourceBundle.getBundle
factory methods during the bundle loading process.
44. Scanner:
A simple text scanner which can parse primitive types and
strings using regular expressions.
45. ServiceLoader:
A simple service-provider loading facility.
46. SimpleTimeZone:
SimpleTimeZone is a concrete subclass of
TimeZone that represents a time zone for use with a Gregorian
calendar.
47. Stack:
The Stack class represents a last-in-first-out (LIFO) stack of
objects.
48. StringTokenizer:
The string tokenizer class allows an application
to break a string into tokens.
49. Timer:
A facility for threads to schedule tasks for future execution
in a background thread.
50. TimerTask:
A task that can be scheduled for one-time or repeated
execution by a Timer.
51. TimeZone:
TimeZone represents a time zone offset, and also figures
out daylight savings.
52. TreeMap<K,V>:
A Red-Black tree based NavigableMap
implementation.
53. TreeSet:
A NavigableSet implementation based on a TreeMap.
54. UUID:
A class that represents an immutable universally unique
identifier (UUID).
55. Vector:
The Vector class implements a growable array of objects.
56. WeakHashMap<K,V>:
Hash table based implementation of the
Map interface, with weak keys.
Topics:9
The wrapper class in Java provides the mechanism to convert primitive into
object and object into primitive.
The eight classes of the java.lang package are known as wrapper classes in
Java. The list of eight wrapper classes are given below:
Use of Wrapper classes in Java:
Java supports only call by value. So, if we pass a primitive value, it will
not change the original value. But, if we convert the primitive value in an
object, it will change the original value.
Serialization:
Synchronization:
java.util package:
The java.util package provides the utility classes to deal with objects.
Collection Framework:
Java collection framework works with objects only. All classes of the
collection framework (ArrayList, LinkedList, Vector, HashSet,
LinkedHashSet, TreeSet, PriorityQueue, ArrayDeque, etc.) deal with
objects only.
Autoboxing:
Example:
byte to Byte,
char to Character,
int to Integer,
long to Long,
float to Float,
boolean to Boolean,
double to Double and
short to Short.
Example:
class WrapperClass
{
public static void main(String args[])
{
//Converting int into Integer
int a=50;
Integer i=Integer.valueOf(a); //converting int into Integer explicitly
Integer j=a;//autoboxing, now compiler will write Integer.valueOf(a) internal
ly
System.out.println(a +" "+ I +" "+ j );
}
}
Output:
50 50 50
Unboxing:
Output:
100 100 100
Example:
public class WrapperExample3
{
public static void main(String args[])
{
byte b=100;
short s=1500;
int i=200;
long l=250;
float f=350.0F;
double d=400.0D;
char c='c';
boolean b2=true;
//Autoboxing: Converting primitives into objects
Byte byteobj=b;
Short shortobj=s;
Integer intobj=i;
Long longobj=l;
Float floatobj=f;
Double doubleobj=d;
Character charobj=c;
Boolean boolobj=b2;
//Printing objects
System.out.println("***Printing object values***");
System.out.println("Byte object: "+byteobj);
System.out.println("Short object: "+shortobj);
System.out.println("Integer object: "+intobj);
System.out.println("Long object: "+longobj);
System.out.println("Float object: "+floatobj);
System.out.println("Double object: "+doubleobj);
System.out.println("Character object: "+charobj);
System.out.println("Boolean object: "+boolobj);
//Unboxing: Converting Objects to Primitives
byte bytevalue=byteobj;
short shortvalue=shortobj;
int intvalue=intobj;
long longvalue=longobj;
float floatvalue=floatobj;
double doublevalue=doubleobj;
char charvalue=charobj;
boolean boolvalue=boolobj;
//Printing primitives
System.out.println("*-*-*-*Printing primitive values-*-*-*");
System.out.println("byte value: "+bytevalue);
System.out.println("short value: "+shortvalue);
System.out.println("int value: "+intvalue);
System.out.println("long value: "+longvalue);
System.out.println("float value: "+floatvalue);
System.out.println("double value: "+doublevalue);
System.out.println("char value: "+charvalue);
System.out.println("boolean value: "+boolvalue);
}
}
Output:
*-*-*-*-*-*-*-*-*-*-*-*-*-*-**-*-*
Topics:10
Enumerations in java:
An enumeration (enum for short) in Java is a special
data type which contains a set of predefined constants.
The Enum in Java is a data type which contains a fixed set of constants.
Output:
WINTER
SPRING
SUMMER
Value of WINTER is: WINTER
Index of WINTER is: 0
Index of SUMMER is: 2
Example: 2
enum players
{
sachin, dravid, virat, dhoni;
}
public class A
{
public static void main(String[] args)
{
players a1 = players.virat;
switch(a1)
{
case sachin:
System.out.println("Sachin is best bastman ever");
break;
case dravid:
System.out.println("Dravid is the best Test Batsman");
break;
case virat:
System.out.println("Virat is a Stylish Batsmen");
break;
case dhoni:
System.out.println("Dhoni is the best captain ever");
break;
}
}
Output:
Virat is a Stylish Batsmen
Example:3
enum players
{
sachin, virat, dhoni;
}
public class A
{
public static void main(String[] args)
{
players a1 = players.dhoni;
if(a1 == players.virat || a1 == players.sachin)
{
System.out.println("Sachin and Virat are greatest batsmen");
}
else
{
System.out.println("Dhoni is the best Captain");
}
}
}
Output:
Dhoni is the best Captain
Example:4
enum games
{
ludo, Chess, Badminton, Cricket;
}
public class A
{
public static void main(String[] args)
{
System.out.println("Using for each loop");
for (games index:games.values())
{
System.out.println(index);
}
}
}
Output:
Using for each loop
ludo
Chess
Badminton
Cricket
*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-**-*
End of The Chapter
Chapter: 7
Discuss about the String Class in Java
Syntax:
<String_Type> <string_variable> = "<sequence_of_string>";
Example:
1. By string literal
2. By new keyword
1) String Literal:
For Example:
1. String s1="Welcome";
2. String s2="Welcome";//It doesn't create a new instance
The above example, only one object will be created.
Firstly, JVM will not find any string object with the value "Welcome" in
string constant pool that is why it will create a new object.
After that it will find the string with the value "Welcome" in the pool,
it will not create a new object but will return the reference to the same
instance.
1.Integer Literals:
Integer literals are sequences of digits. There are three types of integer literals:
Decimal Integer:
These are the set of numbers that consist of digits from 0
to 9. It may have a positive (+) or negative (-) Note that between numbers
commas and non-digit characters are not permitted. For example, 5678,
+657, -89, etc.
Ex:
int octVal = 067;
Hexa-Decimal:
The sequence of digits preceded by 0x or 0X is considered
as hexadecimal integers. It may also include a character
from a to f or A to F that represents numbers from 10 to 15, respectively.
For example, 0xd, 0xf,
Ex:
int hexVal = 0x1a;
Binary Integer:
Base 2, whose digits consists of the numbers 0 and 1 (you
can create binary literals in Java SE 7 and later). Prefix 0b represents the
Binary system. For example, 0b11010
Ex:
int binVal = 0b11010;
Character Literals:
For example:
'a', '%', '\u000d', etc.
String Literals:
For example:
Boolean literals are the value that is either true or false. It may
also have values 0 and 1. For example, true, 0, etc.
Ex:
boolean isEven = true;
Example:
public class Main
{
public static void main(String[] args)
{
//String literals
String testString1 = "Welcome";
String testString2 = "Welcome";
System.out.println(testString1 == testString2); // true
//String Object
testString2 = new String("Wel");
System.out.println(testString1 == testString2); // false
System.out.println(testString1.equals(testString2)); // false
}
}
Output:
true
false
false
2) By new keyword:
Example:
import java.io.*;
import java.lang.*;
class Test
{
public static void main(String[] args)
{
// Declare String without using new operator
String s = "PARUL UNIVERSITY @ VADODARA";
// Prints the String.
System.out.println("String s = " + s);
// Declare String using new operator
String s1 = new String("Dept of CSE @ PARUL ");
System.out.println("String s1 = " + s1); // Prints the String
}
}
Output:
Constructor Description
public
synchronized reverse() It is used to reverse the string.
StringBuffer
The append() method concatenates the given argument with this String
class StringBufferExample
{
public static void main(String args[])
{
StringBuffer sb=new StringBuffer("Hello ");
sb.append("Dept of CSE"); //now original string is changed
System.out.println(sb); //prints Hello Java
}
}
Output:
the insert() method inserts the given String with this string at the given position.
class StringBufferExample2
{
public static void main(String args[])
{
StringBuffer sb=new StringBuffer("Hello ");
sb.insert(1,"Java");//now original string is changed
System.out.println(sb);//prints HJavaello
}
}
Output:
HJavaello
3) StringBuffer replace() Method
the replace() method replaces the given String from the specified beginIndex and
endIndex.
class StringBufferExample3
{
public static void main(String args[])
{
StringBuffer sb=new StringBuffer("Hello");
sb.replace(1,3,"Java");
System.out.println(sb);//prints HJavalo
}
}
Output:
HJavalo
The delete() method of the StringBuffer class deletes the String from the specified
beginIndex to endIndex.
class StringBufferExample4
{
public static void main(String args[])
{
StringBuffer sb=new StringBuffer("Hello");
sb.delete(1,3);
System.out.println(sb);//prints Hlo
}
}
Output:
Hlo
5) StringBuffer reverse() Method
The reverse() method of the StringBuilder class reverses the current String.
class StringBufferExample5
{
public static void main(String args[])
{
StringBuffer sb=new StringBuffer("Hello");
sb.reverse();
System.out.println(sb);//prints olleH
}
}
Output:
olleH
6) StringBuffer capacity() Method
class StringBufferExample6
{
public static void main(String args[])
{
StringBuffer sb=new StringBuffer();
System.out.println(sb.capacity());//default 16
sb.append("Hello");
System.out.println(sb.capacity());//now 16
sb.append("java is my favourite language");
System.out.println(sb.capacity());//now (16*2)+2=34 i.e (oldcapacity*2)+2
}
}
Output:
16
16
34
7) StringBuffer ensureCapacity() method
Class StringBufferExample7
{
public static void main(String args[])
{
StringBuffer sb=new StringBuffer();
System.out.println(sb.capacity());//default 16
sb.append(“Hello”);
System.out.println(sb.capacity());//now 16
sb.append(“java is my favourite language”);
System.out.println(sb.capacity());//now (16*2)+2=34 i.e (oldcapacity*2)+2
sb.ensureCapacity(10);//now no change
System.out.println(sb.capacity());//now 34
sb.ensureCapacity(50);//now (34*2)+2
System.out.println(sb.capacity());//now 70
}
}
Output:
16
16
34
34
70
Note:
Output:
Output:
Converted String from StringBuffer: Dept of CSE
Converted String from StringBuilder: Dept of CSE @ Parul
Example:4
Exception Hierarchy:
All exception and error types are subclasses of class Throwable, which
is the base class of the hierarchy.
One branch is headed by Exception.
This class is used for exceptional conditions that user programs should
catch.
NullPointerException is an example of such an exception.
Another branch, Error is used by the Java run-time system(JVM) to
indicate errors having to do with the run-time environment itself(JRE).
StackOverflowError is an example of such an error.
Types of Java Exceptions:
1) Built-in Exceptions
Checked Exception
Unchecked Exception
2).User-Defined Exceptions
Built-in Exceptions:
Built-in exceptions are the exceptions that are available in Java libraries.
These exceptions are suitable to explain certain error situations.
The built-in-exceptions are classified into two types Checked exception
and unchecked exception.
1.Checked Exceptions:
2.Unchecked Exceptions:
Example:
import java.io.File;
import java.io.FileReader;
public class FilenotFound_Demo
{
public static void main(String args[])
{
File file = new File("E://file.txt");
FileReader fr = new FileReader(file);
}
}
Output:
javac /tmp/ekGroR0BeB/FilenotFound_Demo.java
/tmp/ekGroR0BeB/FilenotFound_Demo.java:8: error: unreported exception
FileNotFoundException; must be caught or declared to be thrown
FileReader fr = new FileReader(file);
^
1 error
3) Error:
Example:
……………………………………………………………
at ErrorExample.recursiveDemo(ErrorExample.java:15)
User-Defined Exceptions:
Sometimes, the built-in exceptions in Java are not
able to describe a certain situation. In such cases, users can also create
exceptions, which are called ‘user-defined Exceptions’.
Example:
class MyException extends Exception
{
}
// A Class that uses above MyException
public class setText
{
// Driver Program
public static void main(String args[])
{
try
{
// Throw an object of user defined exception
throw new MyException();
}
catch (MyException ex)
{
System.out.println("Caught");
System.out.println(ex.getMessage());
}
}
}
Output:
Caught
Null
Java Exception Keywords:
Java provides five keywords that are used to handle the exception.
Keyword Description
finally The "finally" block is used to execute the necessary code of the program.
It is executed whether an exception is handled or not.
class Main
{
public static void main(String[] args)
{
try
{
// code that generates exception
int divideByZero = 5 / 0;
}
catch (ArithmeticException e)
{
System.out.println("ArithmeticException => " + e.getMessage());
}
finally
{
System.out.println("Finally Block Completed Successfully");
}
}
}
Output:
ArithmeticException => / by zero
This is the finally block
Example Program:3
Output:
Example:4
Output:
Exception in thread "main" java.lang.ArithmeticException:
Number is negative, cannot calculate square
at TestThrow.checkNum(TestThrow.java:5)
at TestThrow.main(TestThrow.java:14)
Example:6
Output:
Number cannot be divided by 0
Rest of the code..
Example:6
public class TestThrowAndThrows
{
// defining a user-defined method
// which throws ArithmeticException
static void method() throws ArithmeticException
{
System.out.println("Inside the method()");
throw new ArithmeticException("throwing ArithmeticException");
}
//main method
public static void main(String args[])
{
try
{
method();
}
catch(ArithmeticException e)
{
System.out.println("caught in main() method");
}
}
}
End of the Chapter
Chapter: 9
Threads:
Uses of Threads:
1
Life cycle of a Thread in Java:(Imp)
1. New
2. Runnable
3. Running
4. Blocked (Non-runnable state)
5. Dead
2
1.New State: Born State:
That is, when a thread is created, it enters a new state, but the start()
method on the instance has not yet been invoked.
2.Runnable State:
That is, the thread has entered the queue (line) of threads waiting for
execution.
3.Running State:
Running implies that the processor (CPU) has assigned a time slot to the
thread for execution.
When a thread from the runnable state is chosen for execution by the
thread scheduler, it joins the running state.
In the running state, the processor allots time to the thread for execution
and runs its run procedure.
This is the state in which the thread directly executes its operations.
Only from the runnable state will a thread enter the running state.
3
4.Blocked State:
When the thread is alive, i.e., the thread class object persists,
It is now inactive.
5.Dead State:
That is, when a thread exits the run() process, it is terminated or killed.
4
Types of Threads:
How many types of threads are there in Java?
There are two types of threads in an application - User thread and daemon
thread.
Threads
1) User Thread :
User threads are threads which are created by the application or user.
They are high priority threads.
JVM (Java Virtual Machine) will not exit until all user threads finish their
execution.
JVM wait for these threads to finish their task.
These threads are foreground threads.
5
2)Daemon Thread:
Daemon threads are threads which are mostly created by the JVM.
These threads always run in background.
These threads are used to perform some background tasks like garbage
collection and house-keeping tasks.
These threads are less priority threads.
JVM will not wait for these threads to finish their execution.
JVM will exit as soon as all user threads finish their execution.
JVM doesn’t wait for daemon threads to finish their task.
7
Creating a Thread in Java:
In this case, a thread is created by a new class that extends the Thread
class, creating an instance of that class.
The new thread begins inside the void run() method.(Heart of a Thread)
Example:
8
2.Implementing Runnable interface:
The code for executing the Thread should always be written inside the
run() method.
Example Program:
class ThreadEx2 implements Runnable
{
public void run()
{
System.out.println("My thread is running...");
}
public static void main(String args[])
{
ThreadEx2 Th1=new ThreadEx2();
Thread t1 =new Thread(Th1); // Using the constructor Thread(Runnable r)
t1.start();
}
}
Output:
My thread is running...
Note:
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.
9
3).Using the Thread Class: Thread(String Name)
We can directly use the Thread class to spawn new threads using the constructors
defined above.
Example Program:
Output:
My first thread………
10
4) Using the Thread Class: Thread(Runnable r, String name)
Output:
My new thread
11
Example:
// try-catch block
try
{
// moving thread t2 to the state timed waiting
Thread.sleep(100);
}
catch (InterruptedException ie)
{
ie.printStackTrace();
}
System.out.println("The state of thread t1 while it invoked the method join() on
thread t2 -"+ ThreadState.t1.getState());
// try-catch block
try
{
Thread.sleep(200);
}
catch (InterruptedException ie)
{
ie.printStackTrace();
}
}
}
// ThreadState class implements the interface Runnable
class ThreadState implements Runnable
{
public static Thread t1;
public static ThreadState obj;
// main method
public static void main(String argvs[])
{
// creating an object of the class ThreadState
obj = new ThreadState();
12
t1 = new Thread(obj);
// thread t1 is spawned
// The thread t1 is currently in the NEW state.
System.out.println("The state of thread t1 after spawning it - " + t1.getState());
13
// try-catch block for the smooth flow of the program
try
{
// waiting for thread t2 to complete its execution
t2.join();
}
catch (InterruptedException ie)
{
ie.printStackTrace();
}
System.out.println("The state of thread t2 when it has completed it's execution -
" + t2.getState());
}
}
Output:
14
Multithreading in Java:
Multithreading in java is a process of executing multiple threads
simultaneously.
A thread is a lightweight sub-process, the smallest unit of processing.
Multiprocessing and multithreading, both are used to achieve
multitasking.
we use multithreading than multiprocessing because threads use a shared
memory area.
They don't allocate separate memory area so saves memory, and context-
switching between the threads takes less time than process.
1) It doesn't block the user because threads are independent and you can
perform multiple operations at the same time.
2) You can perform many operations doesn't affect other together, so it
saves time.
Multitasking:
15
1. Process-based Multitasking (Multiprocessing)
Switching from one process to another requires some time for saving and
loading registers, memory maps, updating lists, etc.
16
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.
Example:1
17
int n = 10; // Number of threads
for (int i = 0; i < n; i++)
{
MultithreadingDemo object= new MultithreadingDemo();
object.start();
}
}
}
Output:
Thread 17 is running
Thread 13 is running
Thread 10 is running
Thread 16 is running
Thread 11 is running
Thread 14 is running
Thread 12 is running
Thread 19 is running
18
2.Implementing the Runnable Interface:
Example:
// Java code for thread creation by extending
// the Thread class
19
{
public static void main(String[] args)
{
int n = 8; // Number of threads
for (int i = 0; i < n; i++)
{
MultithreadingDemo object = new MultithreadingDemo();
object.start();
}
}
}
Output:
Thread 11 is running
Thread 16 is running
Thread 10 is running
Thread 12 is running
Thread 14 is running
Thread 17 is running
Thread 15 is running
Thread 13 is running
20
Example:1
import java.util.Scanner;
class Main
input.close();
Output:
21
Example:2
import java.util.Scanner;
class Main
{
public static void main(String[] args)
{
// creates an object of Scanner
Scanner input = new Scanner(System.in);
System.out.print("Enter your name: ");
// reads the entire line
String Str1 = input.nextLine();
String Str2 = input.nextLine();
String Str3 = input.nextLine();
System.out.println("Using nextLine: " + Str1);
System.out.println("Using nextLine: " + Str2);
System.out.println("Using nextLine: " + Str3);
input.close();
}
}
Output:
Enter your names: Naga Malleswara Rao
Vidhya Bhavani
Bavvy
Using nextLine: Naga Malleswara Rao
Using nextLine: Vidhya Bhavani
import java.util.Scanner;
22
Example: 3
class Main
input.close();
Output:
23
What is a Collection in Java?
Def:
Collection:
Any group of individual objects are grouped into a single
object is known as Collection.
Frame Work:
Frame work is a set of classes and interface, which provides
ready-made Architecture in order to implement new feature of class.
Collection of Frame Work:
Collection of frame work defined in JDK1.2
in which holds collection of classes and interface in it. It is used to store
and manipulating a group of objects.
in Java collection is a framework that provides an architecture to store and
manipulate the group of objects.
A Collection in Java is an object which represents a group of objects,
known as its elements.
It is a single unit. They are used to standardize the way in which objects
are handled in the class.
The following are the differences between Collection in Java and Collections
Framework.
Class:
A class is a collection of similar types of objects. It is an implementation
of the collection interface.
Interface:
There are many methods declared in the Collection interface. They are as follows:
public Object next()- It returns the next element in the collection. It throws
the exception of NoSuchElementException if there is no next element.
public void remove()- It removes the current element from the collection.
public boolean hasNext()- It returns true, if there are more elements in the
collection. Else, returns false.
List Interface:
you must've figured it out from the name itself, that ArrayList is similar
to Arrays.
They are also called as dynamic arrays.
That means, it does not have a fixed size.
Its size can be increased or decreased if elements are added or removed.
Since the ArrayList cannot be used for primitive data types like int, char
etc. , we need to use a wrapper class.
Dept of CSE
Example:
import java.util.*;
str.add("CSE");
str.add("IT");
str.add("CIVIl");
str.add("MECHANICAL");
str.add("BDA");
Output:
Example:
import java.util.*;
//creating a LinkedList
//add elements
list.add("Java");
list.add("C++");
list.add("JavaScript");
list.addFirst("C#");
list.addLast("MongoDB");
list.add(2,"Python");
list.remove(5);
list.remove("C#");
Output:
CSE Parul
Example:
import java.util.*;
//creating a Vector
//add elements
v.add(55);
v.add(66);
v.add(77);
v.add(99);
//displaying the Vector
System.out.println(v);
v.remove(3);
System.out.println(v);
Output:
import java.util.*;
//creating a Stack
//push elements
s.push(99);
s.push(88);
s.push(77);
s.push(66);
s.push(55);
//the size remains the same as peek does not remove the element
Output:
Popped element 55
Top-most element 66
Priority Queue:
import java.util.*;
pq.add(10);
pq.add(20);
pq.add(40);
pq.add(80);
Output:
Top-most element 10
Removing 10
New PriorityQueue
2. Creating a HashSet with a specified size It is used to create a HashSet with the
given size.
3. Creating a HashSet with a specified size and fill ratio It is used to create a
HashSet with a given size and fill ratio.
Example:
import java.util.*;
//creating a HashSet
//add elements
str.add("Hi");
str.add("Hello");
str.add("Namaste");
str.add("Dept of CSE");
System.out.println(str);
str.remove("Dept of CSE");
System.out.println(str);
Output:
3. Creating a LinkedHashSet with a specified size and fill ratio It is used to create
a LinkedHashSet with a given size and fill ratio. Fill ratio determines how full the
hash set can be before it is resized.
import java.util.*;
//creating a HashSet
//add elements
str.add("C Language");
str.add("C++");
str.add("Python");
str.add("Java");
str.add("Data Structure");
System.out.println(str);
System.out.println(str);
Output:
Note:
Example
import java.util.*;
class Parul
// Creating a TreeSet
ts.add("India");
ts.add("USA");
ts.add("Uk");
ts.add("Saudi");
System.out.println(ts);
ts.add("Japan");
System.out.println(ts);
Output:
HashMap:
The HashMap class extends AbstractMap and implements the Map interface.
If we want to access a value in a** hash map**, we must know its key.
Example:
import java.util.*;
// Creating a HashMap
hmp.put(2, 2.2);
hmp.put(3, 3.3);
hmp.put(4, 4.4);
hmp.put(5, 5.5);
Output: