Java Report
Java Report
(AUTONOMOUS)
(Approved by AICTE, New Delhi & Affiliated to JNTUA, Ananthapuramu) (Accredited by NBA for EEE,
Mech., ECE & CSE and Accredited by NAAC with ‘A’ Grade)
Siddartha Nagar, Narayanavanam Road, Puttur-517583
COURSE REPORT
OBJECT ORIENTED PROGRAMMING THROUGH JAVA
(20CS0506)
II B.TECH - II SEMESTER
SUBMITTED BY
224E1A09A7
2024-2025
UNIT- I :
The Java Language -Importance of Java -Programming Paradigms - The History and
Evolution of Java -Java Byte Code -The Java Buzzwords. Introduction of OOP- Abstraction,
Encapsulation, Inheritance, Polymorphism-Understanding static -Varargs -Data Types -Type
Casting -Java Tokens - Java Statements -Arrays -Command line arguments.
Applications of JAVA:
1. Standalone Applications
2. Web Applications
3. Enterprise Applications
4. Mobile Applications
1. Standalone Applications:-
It is also known as Desktop or Windows based applications. An application that we
need to install on every machine EX:- Notepad, Media Player etc.
2. Web Applications:-
It runs on a server side and creates dynamic pages called Web Application EX:- Docs
etc.
3. Enterprise Applications:-
An application that is distributed in nature such as banking applications etc. It has the
advantages of high level security EX:- Email System etc.
4. Mobile Applications:-
These are created for mobile devices android and java ME are used for creating
mobile apps EX:- Twitter, Spotify etc
Structure of JAVA:
Brackets []: opening and closing backets are used as array element references. These
indicate sigle and multidimensional subscription.
Parenthesis (): These Special Symbols one used to indicate function calls and function
parameters.
Braces {}: These opening and ending Curly brace marks the containing Stort and end of a
block of code containing more than one executable Statement
comma (,): It is used to seperate more than one. Statments like for seperating parameters in
function calls.
Java operators: -
Java provides many types of operators which can be used accessing to the need. They are
classified based on the functionality they provide.
Some of the types are:
1. Arithmetic
2. Assignment
3. Relational operators
4. Logical operators
5. Bit wise operators
6. Shift operators
7. conditional operators
8. unary operators
1.ARTHEMETIC OPERATORS:
OUTPUT:
2.ASSIGNMENT OPERATORS:
Ex:
EX:
OUTPUT:
3.RELATIONAL OPERATORS:
Operator Description Example
== Is Equal a == b
!= Is Not Equal a != b
> Is Greater Than a>b
< Is Less Than a<b
>= Is Greater Than Equal a >= b
<= Is Less Than Equal a <= b
EX:
OUTPUT:
4.LOGICAL OPERATORS:
Operator Description
&& Logical AND
|| Logical OR
! Logical NOT
EX:
OUTPUT:
5.BIT-WISE OPERATORS:
Operator Description Example
& AND Operation a&b
| OR Operation a|b
~ NOT Operation a~b
^ XOR Operation a^b
EX:
OUTPUT:
6.SHIFT OPERATORS:
Operator Description Example
>> Right Shift a >> b
<< Left Shift a << b
EX:
OUTPUT:
7.CONDITIONAL OPERATORS:
Operator Description
?: <Condition>?<True statement>:<False statement>
EX:
OUTPUT:
8.UNARY OPERATORS:
Operator Description
++ Var++ : Post Increment
++Var : Pre Increment
-- Var- - : Post Increment
- -Var : Pre Increment
EX:
OUTPUT:
Data types:
Data types
Primitive non-primitive
Numerical non-numerical
String manipulation: Use methods like length (), char At(), substring()
to Uppercase(), etc.
b) Array: - Collection of elements: Arrays store a fixed number of elements of
the same data type.
Accessed by index: Each element has a unique index (starting from 0) for
access and modification.
Example:
int[] numbers = {1, 2, 3, 4, 5};
System.out.println(numbers[2]);
numbers[0] = 10;
Multidimensional arrays: Arrays can have multiple dimensions for
representing grids or matrices.
c) Class:- Blueprint for objects: A class defines the properties (variables) and
methods (functions) that objects of that class will have.
Creating objects: Use the new keyword to create instances of a class
Examples:
class Person {
String name;
int age;
void sayHello() {
System.out.println("Hello, my name is " + name);
}
}
Selection/Conditional Statements:
1. Simple if
Syntax:-
if (condition) {
// code to execute if condition is true
}
Control flow:
Ex:
Output:
2.If Else
Syntax :-
if (condition) {
// code to execute if condition is true
} else {
// code to execute if condition is false
}
The if-else statement allows you to execute different code blocks based on whether a
specified condition is true or false.
Flow chart:-
Example:-
Output:-
3.Else If
Syntax :-
if (condition1) {
// code to execute if condition1 is true
} else if (condition2) {
// code to execute if condition1 is false and condition2 is true
} else if (condition3) {
// code to execute if condition1 and condition2 are false and condition3 is true
} else {
// code to execute if all conditions are false
}
Control Flow:
Example:-
Output:
4.Nested If
Syntax:-
if (condition1) {
if (condition2) {
// code to execute if both condition1 and condition2 are true
} else {
// code to execute if condition1 is true but condition2 is false
}
} else {
// code to execute if condition1 is false
}
Example:-
Output:-
5.Switch Case
Syntax :-
switch (expression) {
case value1:
// code to execute if expression equals value1
break;
case value2:
// code to execute if expression equals value2
break;
// ... more cases
default:
// code to execute if expression doesn't match any case
}
EXAMPLE:
OUTPUT:
Program:-
Output:-
Example:
Output: -
Q. Calculate the Monthly Salary after deductions of HRA,FA
and Taxes and display the monthly income.
Algorithm: -
1.Start the program.
2.Prompt the user to enter the annual salary (SALARY_PER_ANNUM).
1. Read the input annual salary from the user.
2. Define constants for health insurance rate, tax rate, and PF (Provident Fund) rate.
3. Calculate the health insurance amount by multiplying the annual salary with the health
insurance rate.
4. Calculate the tax amount by multiplying the annual salary with the tax rate.
5. Calculate the PF amount by multiplying the annual salary with the PF rate.
6. Calculate the net salary by subtracting the total deductions (health insurance, tax, and
PF) from the annual salary.
7. Print the original salary, health insurance, tax, PF, net salary, and net salary per month.
10.End the program.
Example: -
Output:-
Q. Validate Offer based on Purchase amount and print the
discount amount.
Algorithm: -
1.Start the program.
EXAMPLE:
Example:-
Output:-
Loop statements:
1. for Loop
2. while Loop
3. do-while Loop
1. for Loop:
The for loop is used to run a block of code for a certain number of times. It provides a concise way of writing
the loop structure.
Control flow:
Syntax:
Output:
Example 2: Display Numbers from 1 to 5
Output:
2. while Loop:
The while loop executes a block of code as long as a specified condition is true.
Control flow:
Syntax:
while (condition) {
// Code to execute while the condition is true
}
Output:
3. do-while Loop:
The do-while loop is similar to the while loop, but it checks the condition after executing the statements. It is
an example of an exit control loop.
Control flow:
Syntax:
do {
// Code to execute
} while (condition);
In the above program, the value of sum is calculated by adding natural numbers from 1 to 1000.
Jump statements:
1. break
2.continue
3.return
1. break statement:
The Break statement in Java terminates the loop immediately, and the control of the program
moves to the next statement following the loop.
It is almost always used with decision-making
Here is the syntax of the break statement in Java:
break;
Example 1: Java break statement
Output:
2.Continue Statement
The continue statement is used in loop control structure when you need to jump to the next iteration of the
loop immediately. It can be used with for loop or while loop.
Syntax:
continue;
3.return statement:
Syntax:
The syntax of a return statement is the return keyword is followed by the value to be returned.
return returnvalue;
example:
Output:
Java Arrays
An array is a collection of similar types of data.
For example, if we want to store the names of 100 people then we can create an array of the
string type that can store 100 names.
Here, the above array cannot store more than 100 names. The number of values in a Java array is
always fixed.
How to declare an array in Java?
dataType[] arrayName;
For example:
double[] data;
Initialization of arrays:
Here, we have created an array named age and initialized it with the values inside the curly
brackets.
In the Java array, each memory location is associated with a number. The number is known as
an array index. We can also initialize arrays in Java, using the index number. For example,
// declare an array
int[] age = new int[5];
// initialize array
age[0] = 12;
age[1] = 4;
age[2] = 5;
..
Array indices always start from 0. That is, the first element of an array is at index 0.
If the size of an array is n , then the last element of the array will be at index n-1 .
How to Access Elements of an Array in Java?
We can access the element of an array using the index number. Here is the syntax for accessing
elements of an array,
Output:
Types of Array in java
There are two types of array.
1. datatype[] arr;
Example for single dimensional array:
OUTPUT:
Syntax to Declare Multidimensional Array in Java
1. datatype[][] arrayRefVar;
Example for multidimensional array:
There are two types in multidimensional array:
Example:
Output:
2. Three-Dimensional Array (3D Array): A three-dimensional array is more complex and can be
thought of as an array of 2D arrays. It’s useful for representing data in a tabular form with additional
depth.
Here’s an example:
Output:
Command line arugument:
, command-line arguments allow you to pass information to your program when it is executed. These
arguments are provided as input from the command line and can be accessed within your Java code
Example:
OUTPUT:
UNIT- II
INTRODUCING CLASSES
Introducing Classes –Class Fundamentals -Declaring Objects -Introducing Methods Introduction to
Constructors -Garbage Collection-Introducing final -Inheritance - Method Overriding - abstract classes -
Packages and Interfaces.
CLASS FUNDAMENTALS
A class is a user defined blueprint or prototype from which object are created It represents the set of
properties or methods that are common to all objects of one type. In general, class
declarations can include these components, in order:
1. Modifiers: A class can be public or has default access.
2. class keyword: class keyword is used to create a class.
3. Class name: The name should begin with an initial letter (capitalized by convention).
4. Superclass(if any): The name of the class‘s parent (superclass), if any, preceded by the keyword extends.
A class can only extend (subclass) one parent.
5. Interfaces(if any): A comma-separated list of interfaces implemented by the class, if any, preceded by the
keyword implements. A class can implement more than one interface.
Body: The class body surrounded by braces, { }.
Parameters: Parameter passing in Java refers to the mechanism of transferring data between
methods or functions. Java supports two types of parameters passing techniques.
1. Call-by-value.
2. Call-by-reference.
Understanding these techniques is essential for effectively utilizing method parameters in Java.
Types of Parameters:
1. Formal Parameter:
A variable and its corresponding data type are referred to as formal parameters when they exist in the
definition or prototype of a function or method. As soon as the function or method is called and it serves as a
placeholder for an argument that will be supplied. The function or method performs calculations or actions
using the formal parameter.
Syntax:
2. Actual Parameter:
The value or expression that corresponds to a formal parameter and is supplied to a function or method
during a function or method call is referred to as an actual parameter is also known as an argument. It offers
the real information or value that the method or function will work with.
Syntax:
functionName(argument)
1. Call-by-Value:
In Call-by-value the copy of the value of the actual parameter is passed to the formal parameter of the
method. Any of the modifications made to the formal parameter within the method do not affect the actual
parameter.
ALGORITHM:
Step 2.1: Declare an integer variable num and assign it the value 10.
Step 2.2: Print the value of num before calling the method.
Step 2.3: Call the modifyValue method, passing num as the actual parameter.
Step 2.4: Print the value of num after calling the method.
Step 3: Define the modifyValue method that takes an integer parameter value:
Step 3.1: Modify the formal parameter value by assigning it the value 20.
Implementation:
FileName: CallByValueExample.java
Output:
Call-by-Reference:
call by reference" is a method of passing arguments to functions or methods where the memory address (or
reference) of the variable is passed rather than the value itself. This means that changes made to the formal
parameter within the function affect the actual parameter in the calling environment.
ALGORITHM:
Step 1: Start
Step 4.2: Create an instance of "CallByReference" called "object" with values 10 and 20
Step 4.4: Call the "changeValue" method on "object" and pass "object" as an argument
Step 5: End
Implementation:
The implementation of the above steps given below
FileName: CallByReferenceExample.java
Output:
Consider the following Java program, in which we have used different constructors in the class.
Example
Output:
Inheritance in Java:
Inheritance in Java is a mechanism in which one object acquires all the properties and behaviors of a
parent object. It is an important part of oops
The syntax of Java Inheritance:
The extends keyword indicates that you are making a new class that derives from an existing class. The
meaning of "extends" is to increase the functionality.
SYNTAX:
EXAMPLE:
OUTPUT:
class GrandparentClass {
EXAMPLE:
Output:
class Animal {
EXAMPLE:
Output:
4.multiple inheritance:
multiple inheritance occurs when a child class extends more than one superclass.
SYNTAX:
interface Parent1 {
void method1();
}
interface Parent2 {
void method2();
}
class Child implements Parent1, Parent2 {
// Implement methods from Parent1 and Parent2
}
EXAMPLE:
OUTPUT:
5.Hybrid inheritance:
Hybrid inheritance in Java refers to a combination of two or more types of inheritance.
While Java itself does not directly support multiple class inheritance, we can achieve hybrid
inheritance through a clever mix of class inheritance and interfaces .
SYNTAX:
class A {
// Fields and methods
}
class B extends A {
// Fields and methods
}
class C extends A {
// Fields and methods
}
class D extends B {
// Fields and methods
}
EXAMPLE:
OUTPUT:
Garbage Collection/Collector
Garbage collection is the process by which Java runtime system (JVM)
automatically reclaims memory that is no longer in use by the program. This
frees the programmer from manually managing memory allocation and
deallocation, reducing the chances of memory leaks and segmentation faults.
Output:
PROGRAM:
OUTPUT:
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 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.
PROGRAM:
Output:
eck the number of units consumed:
If- an 200, cal
Program:
Save the file as MyPackageClass.java, and compile it:
".
This is my package!
as the units consumed multiplied by 6 (rate per unit) plus the service charge.
If it's 500 or more, calculate the current bill as the units consumed multiplied by 8 (rate
per unit) plus the service charge.
Print the calculated current bill.
UNIT- III EXCEPTION HANDLING
Exception Handling - Exception Fundamentals - Exception Types -
Uncaught Exceptions - Using try and catch - Nested try Statements -throw -
throws –finally Multithreaded Programming - The Java Thread Model -Thread
Priorities -The Thread Class and the Runnable Interface - Creating Multiple
Threads -Using is Alive( ) and join( ) – Thread Priorities - Synchronization -
String Handling
Java Exceptions
When executing Java code, different errors can occur: coding errors made by the
programmer, errors due to wrong input, or other unforeseeable things.
When an error occurs, Java will normally stop and generate an error message. The technical
term for this is: Java will throw an exception (throw an error).
Syntax :
try {
// Block of code to try
}
catch(Exception e) {
// Block of code to handle errors
}
PROGRAM:
Out put:
In this example, the try block throws an ArrayIndexOutOfBoundsException when trying to access an index
that doesn't exist in the array. The catch block catches this exception and prints an appropriate message.
The finally block is executed regardless of the exception and prints a message indicating its
execution. The program then continues to run, demonstrating that the exception was handled
gracefully.
Types of exceptions:
There are mainly two types of exceptions: checked and unchecked. Here, an error is
considered as the unchecked exception. According to Oracle, there are three types of
exceptions:
1. Checked Exception
2. Unchecked Exception
3. Error
1) Checked Exception
The classes which directly inherit Throwable class except Runtime Exception and Error are
known as checked exceptions e.g. IOException, SQL Exception etc. Checked exceptions are
checked at compile-time.
2) Unchecked Exception
The classes which inherit Runtime Exception are known as unchecked exceptions
e.g.
Arithmetic Exception, Null Pointer Exception, Array Index Out Of Bounds Exception etc.
Unchecked exceptions are not checked at compile-time, but they are checked at runtime.
3) Error
Error is irrecoverable e.g. Out Of Memory Error, Virtual Machine Error, Assertion Error etc
B. NullPointer Exception:
Output:
C. NumberFormat Exception:
Output:
THROW:
THROWS:
The Java throws keyword is used to declare an exception. It gives an
information to the programmer that there may occur an exception so it is
better for the programmer to provide the exception handling code so that
normal flow can be maintained.
Exception Handling is mainly used to handle the checked exceptions. If
there occurs any unchecked exception such as NullPointerException, it is
programmers fault that he is not performing check up before the code
being used.
Syntax of java throws:
1. return_type method_name() throws exception_class_name{
2. //method code
3. }
FINALLY:
A finally block contains all the crucial statements that must be executed
whether exception occurs or not. The statements present in this block will
always execute regardless of whether exception occurs in try block or not
such as closing a connection, stream etc.
Syntax of Finally block:
try {
//Statements that may cause an exception
}
catch {
//Handling exception
}
finally {
//Statements to be executed
}
MULTITHREADED PROGRAMMING
Threads:
we can define threads as a subprocess with lightweight with the smallest unit of
processes and also has separate paths of execution.
Step 1: Create thread.
class cad extends thread
(or)
class cad implements runnable
Step 2: Create run() in class.
Step 3: Create an object attach to thread.
Cad Obj = new cad()
thread t= new thread (obj);
Step 4: method_name start()
t.start()
Example:
Output:
The Thread class defines several methods that help manage threads. Several of those
used in this chapter are shown here:
STRING HANDLING
In Java, a string is an object that represents a sequence of characters or char values.
The java.lang.String class is used to create a Java string object.
There are two ways to create a String object:
1. By string literal : Java String literal is created by using
double quotes. For Example: String s=―Welcome‖;
2. By new keyword : Java String is created by using a
keyword ―new‖.
For example:
String s=new String(―Welcome‖);
// charAt
System.out.println("charAt(1): " + str.charAt(1)); // e
// length
System.out.println("length: " + str.length()); // 13
// substring
System.out.println("substring(7): " + str.substring(7)); // World!
System.out.println("substring(0, 5): " + str.substring(0, 5)); // Hello
// contains
System.out.println("contains('World'): " + str.contains("World")); // true
// equals
System.out.println("equals('Hello, World!'): " + str.equals("Hello, World!")); // true
// equalsIgnoreCase
System.out.println("equalsIgnoreCase('hello, world!'): " + str.equalsIgnoreCase("hello,
world!")); // true
// compareTo
System.out.println("compareTo('Hello, World!'): " + str.compareTo("Hello, World!")); // 0
System.out.println("compareTo('hello, world!'): " + str.compareTo("hello, world!")); // Negative
value
// isEmpty
System.out.println("isEmpty: " + str.isEmpty()); // false
// startsWith
System.out.println("startsWith('Hello'): " + str.startsWith("Hello")); // true
// endsWith
System.out.println("endsWith('World!'): " + str.endsWith("World!")); // true
// indexOf
System.out.println("indexOf('o'): " + str.indexOf('o')); // 4
// lastIndexOf
System.out.println("lastIndexOf('o'): " + str.lastIndexOf('o')); // 8
// toLowerCase
System.out.println("toLowerCase: " + str.toLowerCase()); // hello, world!
// toUpperCase
System.out.println("toUpperCase: " + str.toUpperCase()); // HELLO, WORLD!
// trim
String strWithSpaces = " Hello, World! ";
System.out.println("trim: '" + strWithSpaces.trim() + "'"); // 'Hello, World!'
// replace
System.out.println("replace('l', 'p'): " + str.replace('l', 'p')); // Heppo, Worpd!
// replaceAll
System.out.println("replaceAll('l', 'p'): " + str.replaceAll("l", "p")); // Heppo, Worpd!
// split
String[] words = str.split(", ");
System.out.println("split(', '): " + String.join(" | ", words)); // Hello | World!
// join
System.out.println("join('-'): " + String.join("-", words)); // Hello-World!
// valueOf
int number = 123;
System.out.println("valueOf(123): " + String.valueOf(number)); // 123
// format
String formattedString = String.format("Formatted number: %.2f", 123.456);
System.out.println("format: " + formattedString); // Formatted number: 123.46
// toCharArray
char[] charArray = str.toCharArray();
System.out.println("toCharArray: " + java.util.Arrays.toString(charArray)); // [H, e, l, l, o, ,, ,
W, o, r, l, d, !]
// concat
String str2 = " Let's learn Java.";
System.out.println("concat: " + str.concat(str2)); // Hello, World! Let's learn Java.
// matches
String regex = "Hello,.*";
System.out.println("matches('Hello,.*'): " + str.matches(regex)); // true
// intern
String internedString = str.intern();
System.out.println("intern: " + (internedString == str)); // true
// getBytes
byte[] bytes = str.getBytes();
System.out.println("getBytes: " + java.util.Arrays.toString(bytes)); // [72, 101, 108, 108, 111, 44,
32, 87, 111, 114, 108, 100, 33]
// regionMatches
System.out.println("regionMatches: " + str.regionMatches(7, "World", 0, 5)); // true
// codePointAt
System.out.println("codePointAt(1): " + str.codePointAt(1)); // 101
// subSequence
System.out.println("subSequence(0, 5): " + str.subSequence(0, 5)); // Hello
}
}
Output:
UNIT-IV
GENERICS:
Object is the superclass of all other classes and Object reference can refer to any
type object. These features lack type safety. Generics adds that type safety feature.
Example:
A simple generic example generics means parameterized types. The idea is to allow
type (Integer, String, … etc, and user- defined types) to be a parameter to methods,
classes, and interfaces. Using Generics, it is possible to create classes that work with
different data types.
An entity such as class, interface, or method that operates on a parameterized type is
called generic entity.
.
Output:
COLLECTION:
The Collection in Java is a framework that provides an architecture to store and
manipulate the group of objects.
COLLECTION CLASS
COLLECTION INTERFACES
3 The Set
This extends Collection to handle sets, which must contain unique elements.
4 The SortedSet
This extends Set to handle sorted sets.
5 The Map
1 AbstractCollection
Implements most of the Collection interface.
2 AbstractList
Extends AbstractCollection and implements most of the List interface.
3 AbstractSequentialList
Extends AbstractList for use by a collection that uses sequential rather than random
access of its elements.
4 LinkedList
Implements a linked list by extending AbstractSequentialList.
5 Array List
Implements a dynamic array by extending AbstractList.
6 AbstractSet
Extends AbstractCollection and implements most of the Set interface.
7 HashSet
Extends AbstractSet for use with a hash table.
8 LinkedHashSet
Extends HashSet to allow insertion-order iterations.
9 TreeSet
Implements a set stored in a tree. Extends AbstractSet.
10 AbstractMap
Implements most of the Map interface.
11 HashMap
Extends AbstractMap to use a hash table.
12 TreeMap
Extends AbstractMap to use a tree.
13 WeakHashMap
Extends AbstractMap to use a hash table with weak keys.
14 LinkedHashMap
Extends HashMap to allow insertion-order iterations.
15 IdentityHashMap
Extends AbstractMap and uses reference equality when comparing documents.
Vector:
Vector is like the dynamic array which can grow or shrink its size.
SN Method Description
2) addAll() It is used to append all of the elements in the specified collection to the end of
this Vector.
3) addElement() It is used to append the specified component to the end of this vector. It
increases
the vector size by one.
7) remove() It is used to remove the specified element from the vector. If the vector does
not contain the element, it is unchanged.
8) removeAll() It is used to delete all the elements from the vector that are present in the
specified collection.
9) set() It is used to replace the element at the specified position in the vector with the
specified element.
10) size() It is used to get the number of components in the given vector.
Example:
Output:
ArrayList:
Java ArrayList is a part of the Java collections framework and it is a class of
java.util package. It provides us with dynamic arrays in Java.
Method Description
void add(int index, E element) It is used to insert the specified element at the specified position
in a list.
int size() It is used to return the number of elements present in the list.
clear() This method is used to remove all the elements from any list.
Example:
Output:
Stack:
The stack is a linear data structure that is used to store the collection of objects. It is
based on Last-In-First-Out (LIFO).
push(E item) E The method pushes (insert) an element onto the top of the st
pop() E The method removes an element from the top of the stack an
returns the same element as the value of that function.
peek() E The method looks at the top element of the stack without
removing it.
search(Object o) int The method searches the specified object and returns the
position of the object.
Output:
Queue:
The interface Queue is available in the java.util package and does extend the Collection interface. It is used
to keep the elements that are processed in the First In First Out (FIFO) manner.
Method Description
boolean add(object) It is used to insert the specified element into this queue and return
true upon success.
boolean offer(object) It is used to insert the specified element into this queue.
Object remove() It is used to retrieves and removes the head of this queue.
Object poll() It is used to retrieves and removes the head of this queue, or returns
null if this queue is empty.
Object element() It is used to retrieves, but does not remove, the head of this queue.
Object peek() It is used to retrieves, but does not remove, the head of this queue, or
returns null if this queue is empty.
Java HashSet class is used to create a collection that uses a hash table for storage. It inherits the AbstractSet
class and implements Set interface.
Method Description
contains(Object o) It is used to return true if this set contains the specified element.
remove(Object o) It is used to remove the specified element from this set if it is present.
Example:
Output:
Linked List:
Method Description
Hashmap:
Output:
For example:
import java.io.File
File obj = new File("filename.txt");
Java uses the concept of a stream to make I/O operations on a file. So
let‘s now understand what is a Stream in Java.
WHAT IS A STREAM?
In Java, Stream is a sequence of data which can be of two types.
1. Byte Stream
This mainly incorporates with byte data. When an input is provided and executed
with byte data, then it is called the file handling process with a byte stream.
2. Character Stream
Character Stream is a stream which incorporates with characters. Processing of
input data with character is called the file handling process with a character
stream.
Now that you know what is a stream, let‘s dive deeper into this article on File
Handling in Java and know the various methods that are useful for operations on
the files like creating, reading and writing.
1.Create a File
To create a file in Java, you can use the createNewFile() method.
Program:
Output:
Write in file:
In the following example, we use the FileWriter class together with its write() method to write some text to the
file we created in the example above. Note that when you are done writing to the file, you should close it with
the close() method:
Program:
Output:
UNIT V
Introducing the AWT - Using AWT Controls-Layout Managers -Introducing Swing -
Exploring Swing.
Introducing Java8 Features –Lambda Expression –Method references –forEach() method -
Method and Constructor reference by double colon(::) operator - Stream API –Date & Time
API.
Java AWT(Abstract Window Toolkit) controls are the controls that are used to design
graphical user interfaces or web applications. To make an effective GUI, Java provides
java.awt package that supports various AWT controls like Label, Button, CheckBox,
CheckBox Group, List, Text Field, Text Area, Choice, Canvas, Image, Scrollbar, Dialog, File
Dialog, etc that creates or draw various components on web and manage the GUI based
application.
Container
The Container is a component in AWT that can contain another components like buttons,
textfields, labels etc. The classes that extends Container class are known as container such as
Frame, Dialog and Panel.
Window
The window is the container that have no borders and menu bars. You must use frame, dialog
or another window for creating a window.
Panel
The Panel is the container that doesn't contain title bar and menu bars. It can have other
components like button, textfield etc.
Frame
The Frame is the container that contain title bar and can have menu bars. It can have other
components like button, textfield etc.
1. Label
A label is a user for placing text inside the container. A label is used only for inputting text.
The label does not imply that the text can be altered or it can be used as a button which can be
further worked upon.
Syntax:
Label n=new Label("Name:",Label.CENTER);
2. Button
This command generates a button in the User Interface. Clicking on the button would move
the command to another page or another web server which is used to show several other
outputs in the user interface page.
Syntax:
a1=new
Button("submit");
a2=new
Button("cancel");
3. Checkbox
There can be a certain question and the checkbox is used to determine the true or false nature
of the question being asked. If the checkbox is ticked then it means that the said question is
true which if it is unchecked it means that the said question is false. It is basically a true or
false state in Java programming language.
Syntax:
Checkbox checkbox1 = new Checkbox("Hello World");
4. Checkbox Group
As the name implies the checkbox group is a set of checkboxes that are being used in the
programming language. There are many checkboxes that are being used and hence the group
of checkboxes is known as the checkbox group.
Syntax:
CheckboxGroup cb = new CheckboxGroup();
Checkbox checkBox1 = new Checkbox("Hello", cb, true);
checkBox1.setBounds (100,100, 50,50);
5. List
The list gives a scrolling list of items for the user. The scrolling list of items is also being set
by the user. The user sets the scrolling list of items such as Fruits, Vegetables, some
questionnaire or other facts.
Syntax:
List l1=new List(4);
l1.setBounds(100,100,
75,75);
6. Text Field
A text field is used for the editing of a particular line of text which can be used within the
programming concept.
Syntax:
na=new TextField(20);
7. Text Area
A text area is used for the editing of multiple lines of text. The only difference between the
Text field and Text area is that Text Field is used for editing a single line of text within the
user interface while a Text Area is used for editing multiple lines of text.
Syntax:
TextArea area=new TextArea("Welcome to the universe");
area.setBounds(10,30, 300,300);
8. Choice
A choice, as the name implies, shows the various options and the choice that is selected is
shown in the top menu bar of the screen.
Syntax:
Choice c=new Choice();
c.setBounds(100,100,
75,75);
c.add("Subject 1");
c.add("Subject 2");
c.add("Subject 3");
c.add("Subject 4");
c.add("Subject 5");
9. Canvas
In the canvas space, there can be an input being given by the user or the user can draw
something on the Canvas space being given.
Syntax:
f.add(new
MyCanvas());
f.setLayout(null);
f.setSize(400, 400);
f.setVisible(true);
10. Image
There can be a single image or multiple images within a UI. There can be a button
being associated with an image and when it is clicked it can produce some functionality.
Syntax:
Image i=t.getImage("pic2.gif");
11. Scroll Bar
The scroll bar like a normal one is used to scroll or move from a varied range of values. The
user selects one value from those range of values.
Syntax:
Scrollbar s=new Scrollbar();
s.setBounds(100,100,
50,100);
12. Dialog
The dialog is used to take some form of input from the user and produce it in a
sequential manner.
Syntax:
d = new Dialog(f , "Hello World", true);
Let's see a simple example of AWT where we are inheriting Frame class. Here, we are showing
Button component on the Frame.
import java.awt.*;
class First extends Frame
{
First()
{
Button b=new Button("click me");
b.setBounds(30,100,80,30); // setting button position
setBounds(xcoordinate,ycoordinate,width, hight);
add(b); //adding button into frame
setSize(300,300); //frame size 300 width and 300
height setLayout(null); //no layout manager
setVisible(true); //now frame will be visible, by default not visible
}
public static void main(String args[])
{ First f=new First();
}}
INTRODUCING SWING
Swing in java is part of Java foundation class which is lightweight and platform independent.
It is used for creating window based applications. It includes components like button, scroll
bar, text field etc. Putting together all these components makes a graphical user interface.
Container Class
Any class which has other components in it is called as a container class. For building GUI
applications at least one container class is necessary.
JButton Class
It is used to create a labelled button. Using the ActionListener it will result in some action
when the button is pushed. It inherits the AbstractButton class and is platform independent.
Example:
import javax.swing.*;
public class example
{
public static void main(String args[])
{
JFrame a = new JFrame("example");
JButton b = new JButton("click me");
b.setBounds(40,90,85,20);
a.add(b);
a.setSize(300,300);
a.setLayout(null);
a.setVisible(true);
}
}
Output:
JTextField Class
It inherits the JTextComponent class and it is used to allow editing of single line text.
Example:
import javax.swing.*;
public class example{
public static void main(String args[])
{ JFrame a = new JFrame("example");
JTextField b = new
JTextField("edureka");
b.setBounds(50,100,200,30);
a.add(b);
a.setSize(300,300);
a.setLayout(null);
a.setVisible(true);
}
}
JScrollBar Class
It is used to add scroll bar, both horizontal and vertical.
import javax.swing.*;
class example{
example(){
JFrame a = new JFrame("example");
JScrollBar b = new JScrollBar();
b.setBounds(90,90,40,90);
a.add(b);
a.setSize(300,300);
a.setLayout(null);
a.setVisible(true);
}
public static void main(String args[])
{ new example();
}
}
Output:
JPanel Class
It inherits the JComponent class and provides space for an application which can attach
any other component.
import java.awt.*;
import javax.swing.*;
public class Example{
Example(){
JFrame a = new JFrame("example");
JPanel p = new JPanel();
p.setBounds(40,70,200,200);
JButton b = new JButton("click me");
b.setBounds(60,50,80,40);
p.add(b);
a.add(p);
a.setSize(400,400);
a.setLayout(null);
a.setVisible(true);
}
public static void main(String args[])
{
new Example();
}
}
Syntax
The simplest lambda expression contains a single parameter and an expression:
parameter -> expression
Example:
Output:
METHOD REFERENCES
Java provides a new feature called method reference in Java 8. Method
reference is used to refer method of functional interface. It is compact and easy
form of lambda expression. Each time when you are using lambda expression to
just referring a method, you can replace your lambda expression with method
reference
A. To refer to a method in an object
Object :: methodName
B. To print all elements in a list
Following is an illustration of a lambda expression that just calls a single method in its
entire execution:
list.forEach(s -> System.out.println(s));
C. Shorthand to print all elements in a list
To make the code clear and compact, In the above example, one can turn lambda
expression into a method reference:
list.forEach(System.out::println);
Types of Method References
There are following types of method references in java:
1. Reference to a static method.
2. Reference to an instance method.
3. Reference to a constructor.
1. Reference to a static method:
You can refer to static method defined in the class. Following is the syntax and
example which describe the process of referring static method in Java.
Syntax
ContainingClass::staticMethodName
2) Reference to an Instance Method
like static methods, you can refer instance methods also. In the following
example, we are describing the process of referring the instance method.
Syntax
containingObject::instanceMethodName
3)Reference to a Constructor
You can refer a constructor by using the new keyword. Here, we are referring
constructor with the help of functional interface.
Syntax
ClassName::new
FOREACH() METHOD
Java provides a new method forEach() to iterate the elements. It is defined in
Iterable and Stream interface. It is a default method defined in the Iterable
interface. Collection classes which extends Iterable interface can use forEach
loop to iterate elements.
This method takes a single parameter which is a functional interface. So, you can
pass lambda expression as an argument.
forEach() Signature in Iterable Interface
Example:
You can refer to static method defined in the class. Following is the syntax and
example which describe the process of referring static method in Java.
2. Reference to an instance method of a particular object.
Like static methods, you can refer instance methods also. In the following example,
we are describing the process of referring the instance method.
Syntax:
<target class object>::<instance method>
3. Reference to an instance method of an arbitrary object of a particular type
Like static methods, you can refer instance methods also. In the following example,
we are describing the process of referring the instance method.
Syntax:
<arbitary object type>::<instance method>
STREAM API
Java 8 introduces a new date-time API under the package java.time. Following are
some of the important classes introduced in java.time package.
Local − Simplified date-time API with no complexity of timezone handling.
Zoned − Specialized date-time API to deal with various timezones.
// Driver code
public static void main(String[] args)
{
LocalDateTimeApi();
}
}
Output:
SUBMITTED BY
BABI AZEES SHAIK