0% found this document useful (0 votes)
38 views110 pages

Java Report

about java programs using jdk17

Uploaded by

azeesbabi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
38 views110 pages

Java Report

about java programs using jdk17

Uploaded by

azeesbabi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 110

SIDDARTHA INSTITUTE OF SCIENCE AND TECHNOLOGY

(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

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

COURSE REPORT
OBJECT ORIENTED PROGRAMMING THROUGH JAVA

(20CS0506)

II B.TECH - II SEMESTER

SUBMITTED BY

BABI AZEES SHAIK

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.

About Java Programing?


Java is a high level, object oriented programming language and made by Computes platform
Javia was available to the public in 1995 by Sun microsystems, which is now owned by
Oracle corporation.
object oriented programming or loop is way of writing code based on the concept It is able
to implement object oriented principles such as encapsulation
inheritance&polymorphisam.And one of the key feature of Java is its write once run
anywhere capability.

Different types of Java.


 Java SE
 Java EE
 Java ME
 Java FX
 Open JDK
 Oracle JDK
 Android

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

About Java IDE’s.


Usually Java IDE include a code edition a complies a debugger and a interpreter that the
developer may access via single graphical were interface .java IDE’s also provide language
speed elements such as moven anti building tools.

Structure of JAVA:

Characters of java programming.


There are two types of characters
1.Source character
2.Esacpe characters

Java tokens (identifiers)


In java identifiers are names given to various programming elements such as variables
methods classes,packages& interfaces here the rule for defining identifiers in java

1. Character set – It can be consists of refers


uppercase,lowercase,digit,underscores&dolor sign.
2. Length- any length.
3. Reserved words- It cannot be the same word as java keyword (or) reserved words
4. Conventions- For example variable names usually starts with lowercase letters,class
names starts with uppercase letter&contants are often written in all uppercase with
underscore
Examples:- Variable name, Variable,$ value, my class,total_sum

java tokens (keyword)


abstract continue for new switch
***
assert default goto* package synchronized
boolean do if private this
break double implements protected throw
byte else import public throws
case enum**** instanceof return transient
catch Extend int short try
char Final interface static void
class finally long strictfp** volatile
*
const Float native super while

1. Integer literals- we specify in Decimal:123


2. Java tokens (literals)
Octal:0755
Hexa :oxff
1. Floating-standard notations:3.56,0.874.
specific notation :2.de.3
2. String literals-There enclosed in double quotes.
Ex:”hello world”
“java programming”
3. Character literals- There enclosed in single quotes
Ex: character:’a’,’1’,’e’.
Escape sequence:’\n’,’\t’.
4. Boolean literals:True (or) False.
5. Null literals:Null it refers to no object (or) value absence

Java tokens (separators)


The following Special Symbas are used in Jave having some specia, meanings and thus,
cannot be used for some other purpose.
{ },[ ],( ),(,), ; , * , =,., ::

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.

Semi Colone(;): It is an operator, that essentially invoke something called an initialization


list.

asterick (*) : It is used to create pointer variable.

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:

Symbol Description Example


+ Adds together two values A +B
- Substracts one value from another A -B
* Multiply two values A*B
/ Divides one value by another A/B
% Returned the division remainder A%B
PROGRAM:

OUTPUT:

2.ASSIGNMENT OPERATORS:

Operato Description Example


r
= Assigns RHS to LHS Operand a=5
+= Adds LHS with RHS Operand & assigns the value to the a += b
LHS Operand
-= Subtracts RHS from LHS Operand & assigns the value to a -= b
the LHS Operand
*= Multiplies LHS with RHS Operand & assigns the value to a *= b
the LHS Operand
/= Divides LHS by RHS Operand & assigns the value to the a /= b
LHS Operand
%= LHS operand is divide by the RHS operand & assigns the a %= b
Remainder to the LHS Operand

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

Strings ARRAY class function


Integer float Boolean char
1. Primitive Data Type:
a) Boolean Type: - A Boolean data type can store either true or false
They can be used to check whether two values are equal or not.
b) Character Type: -the char data type stores a single character,it stores
lowercase & uppercase characters which must be enclosed in signal
quotes. It supports Unicodes also
c) Integer Type: -An integer type stores an integer number with no
factorial or decimal places java has four integer type byte, short, int &
long.
I. Byte: -It can store -128 to 127 it can store 8-bit value signed
two’s complement.
II. Short: -It is a 16-bit signed two’s complement Range -32768 to
32767.
III. Int: - It is a 32 -bit signed two’s complement integer Range-
2147483648(-231) to 2147483647(231).
IV. Long: -It is a 64-bit signed two’s complement integer Range -
9223372036854775808(-263) to 9223372036854775807(263-1).
2. Non-Primitive Data Type:
a) String: -String in java are immutable, meaning once created, their content
cannot be changes. Any change requires creating a new String object.
Example:
String name=” Robert”
Name=”honey”

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);
}
}

Person robert = new Person();


robert.name = "Robert";
robert.age = 34;
robert.sayHello(); // Prints "Hello, my name is John"

Input Functions in Java:

S.NO Function Description Example


1 next Line() Reads the next I/P token as String scan.nextLine();
2 nextInt() Reads the next I/P token as Integer scan.nextInt();
3 nextDouble() Reads the next I/P token as Double scan.nextDouble();
4 nextBoolean( Reads the next I/P token as Boolean scan.nextBoolean()
) ;
5 nextByte() Reads the next I/P token as Byte scan.nextByte();
6 nextShort() Reads the next I/P token as Short scan.nextShort();
7 nextLong() Reads the next I/P token as Long scan.nextLong();
8 nextFloat() Reads the next I/P token as Float scan.nextFloat();
Control Statements:
Conditional loop jump
--simpleif() -- while() -- Break
--if-else() -- dowhile() -- continue
--else-if() -- for() -- return
--nested if() --for each()
--switch()

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:

Q. Finding Student Grade.


Algorithm:
1.Start the program.

2.Prompt the user to enter the percentage of marks he /she got

3.Read the input of percentage of marks

4Check the average marks:

 If the average is greater than or equal to 90, print "A grade".


 If the average is between 80 and 89 (inclusive), print "B grade".
 If the average is between 70 and 79 (inclusive), print "C grade".
 If the average is between 60 and 69 (inclusive), print "D grade".
 If the average is between 50 and 59 (inclusive), print "E grade".
 If none of the above conditions are met, print "Fail".

5.End the program.

Program:-
Output:-

Q. Finding Electricity Bill Based on Input Units.


Algorithm: -

1.Start the program.


2.Prompt the user to enter the number of units consumed.
3.Read the input number of units.
4.Define a service charge of 25.
5.Check the number of units consumed:
 If it's less than 200, calculate the current bill as the service charge.
 If it's between 200 and 299 (inclusive), calculate the current bill as the units
consumed multiplied by 2 (rate per unit) plus the service charge.
 If it's between 300 and 399 (inclusive), calculate the current bill as the units
consumed multiplied by 4 (rate per unit) plus the service charge.
 If it's between 400 and 499 (inclusive), calculate the current bill 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.
6.Print the calculated current bill.
7.End the program.

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.

2.Prompt the user to enter the total shopping value.

3. Read the input total shopping value from the user.


4. Check the total shopping value:
5. If it's between 3000 (inclusive) and 4000 (exclusive), calculate the
discounted price after applying a 20% discount and print the result.
6. If it's between 4000 (inclusive) and 5000 (exclusive), calculate the
discounted price after applying a 30% discount and print the result.
7. If it's 5000 or more, calculate the discounted price after applying a 40%
discount and print the result.
8. If none of the above conditions are met, print that no offer is applied
along with the original total shopping value.
9. End 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:

for (initialization; condition; update) {


// Code to execute in each iteration
}

Example 1: Display a Text Five Times

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
}

Example: Display Numbers from 1 to 10

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);

Example: Display Sum of Natural Numbers


Output:

In the above program, the value of sum is calculated by adding natural numbers from 1 to 1000.

Jump statements:

They are mainly divided into three types:

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;

Java Continue Statement Example


ContinueExample.java
Output:

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.

String [] array = new String[100];

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?

In Java, here is how we can declare an array.

dataType[] arrayName;

For example:

double[] data;

Initialization of arrays:

In Java, we can initialize arrays during declaration. For example,

//declare and initialize and array


int[] age = {12, 4, 5, 2, 5};

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,

// access array elements


array[index]

Let's see an example of accessing array elements using index numbers.

Example: Access Array Elements

Output:
Types of Array in java
There are two types of array.

o Single Dimensional Array


o Multidimensional Array

Single Dimensional Array in Java


Syntax to Declare an Array in Java

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:

1. Two-Dimensional Array (2D Array): A two-dimensional array is the simplest form of a


multidimensional array. It can be visualized as an array of one-dimensional arrays.

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:

 Compile: javac commandline.java


 Run: java commandline sonoo jaiswal 1 3 abc

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, { }.

Object class in Java


The Object class is the parent class of all the classes in java by default. In other words, it is the topmost
class of java.

Difference between object and class


There are many differences between object and class. A list of differences between object and class are
given below:

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:

1. returnType functionName(dataType parameterName)


2. {
3. // Function body
4. // Use the parameterName within the function
5. }

In the above syntax:

o returnType represents the return type of the function.


o functionName represents the name of the function.
o dataType represents the data type of the formal parameter.
o parameterName represents the name of the formal parameter.

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)

In the above syntax:

o functionName represents the name of the function or method.


o argument represents the actual value or expression being passed as an argument to the function or method.

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 1: Create a class named CallByValueExample.


Step 2: Inside the main method:

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.

Step 3.2: Print the value of value inside the method.

Implementation:

The implementation of the above steps given below

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 2: Define the class "CallByReference"

Step 2.1: Declare instance variables: a (int) and b (int)

Step 2.1: Define a constructor to assign values to a and b

Step 3: Define the method "changeValue" inside the "CallByReference" class:

Step 3.1: Accept a parameter of type "CallByReference" called "obj"

Step 3.2: Add 10 to the value of "obj.a"

Step 3.3: Add 20 to the value of "obj.b"

Step 4: Define the class "Main"

Step 4.1: Define the main method

Step 4.2: Create an instance of "CallByReference" called "object" with values 10 and 20

Step 4.3: Print the values of "object.a" and "object.b"

Step 4.4: Call the "changeValue" method on "object" and pass "object" as an argument

Step 4.5: Print the updated values of "object.a" and "object.b"

Step 5: End

Implementation:
The implementation of the above steps given below

FileName: CallByReferenceExample.java
Output:

Constructor overloading in Java


In Java, we can overload constructors like methods. The constructor overloading can be defined as the
concept of having more than one constructor with different parameters so that every constructor can perform
a different task.

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:

1. class Subclass-name extends Superclass-name


2. {
3. //methods and fields
4. }

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.

Types of inheritance in java


On the basis of class, there can be three types of inheritance in java: single, multilevel and hierarchical.

1.Single Inheritance Example


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.

SYNTAX:

class ChildClass extends ParentClass {

// Fields and methods specific to the child class

EXAMPLE:
OUTPUT:

2.Multilevel Inheritance Example


When there is a chain of inheritance, it is known as multilevel inheritance. As you can see in the example
given below, BabyDog class inherits the Dog class which again inherits the Animal class, so there is a
multilevel inheritance.
SYNTAX:

class GrandparentClass {

// Fields and methods

class ParentClass extends GrandparentClass {

// Fields and methods

class ChildClass extends ParentClass {

// Fields and methods

EXAMPLE:
Output:

3.Hierarchical Inheritance Example


When two or more classes inherits a single class, it is known as hierarchical inheritance. In the example
given below, Dog and Cat classes inherits the Animal class, so there is hierarchical inheritance.
SYNTAX:

class Animal {

// Fields and methods

class Dog extends Animal {

// Fields and methods specific to dogs

class Cat extends Animal {

// Fields and methods specific to cats

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:

Method Overloading in Java


If a class has multiple methods having same name but different in parameters, it is known as Method
Overloading.

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

PACKAGES AND INTERFACES PACKAGES


A java package is a group of similar types of classes, interfaces and sub-packages. Package
in java can be categorized in two form, built-in package and user-defined package.There are
many built-in packages such as java, lang, awt, javax, swing, net, io, util, sql etc.
Packages are two types:

etc. between 300


and 399 (inclusive), calculate the current bill as the units consumed multiplied by 4
(rate per unit) plus the service charge.
If it's bet

How to Create Package in Java


In Java, a package is a group of classes, interfaces, enumeration, and annotations. Java
contains many pre-defined packages such as java.lang, java.io, java.net, etc. When we
create any Java program the java.lang package is imported by default. We need not to
write the package name at the top of the program

To create a package, use the package keyword:

Program:
Save the file as MyPackageClass.java, and compile it:

C:\Users\Your Name>javac MyPackageClass.java

Then compile the package:

C:\Users\Your Name>javac -d . MyPackageClass.java

".

To run the MyPackageClass.java file, write the following:

C:\Users\Your Name>java mypack.MyPackageClass

The output will be:

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).

Java try and catch


The try statement allows you to define a block of code to be tested for errors while it is being
executed.
The catch statement allows you to define a block of code to be executed, if an error occurs in
the try block.

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

Examples of Built-in Exception


A. Arithmetic exception:
Output:

B. NullPointer Exception:

Output:

C. NumberFormat Exception:
Output:

THROW:

The Java throw keyword is used to explicitly throw an exception.


We can throw either checked or uncheked exception in java by throw
keyword. The throw keyword is mainly used to throw custom exception.
We will see custom exceptions later.
syntax :
throw exception;
Example:
Output:

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:

Life Cycle of a Thread:


A thread goes through various stages in its life cycle. For example, a thread is born,
started, runs, and then dies. The following diagram shows the complete life cycle of a
thread.

Following are the stages of the life cycle −


 New − A new thread begins its life cycle in the new state. It remains in this
state until the program starts the thread. It is also referred to as a born thread.
 Runnable − After a newly born thread is started, the thread becomes runnable.
A thread in this state is considered to be executing its task.
 Waiting − Sometimes, a thread transitions to the waiting state while the thread
waits for another thread to perform a task. A thread transitions back to the
runnable state only when another thread signals the waiting thread to continue
executing.
 Timed Waiting − A runnable thread can enter the timed waiting state for a
specified interval of time. A thread in this state transitions back to the runnable
state when that time interval expires or when the event it is waiting for occurs.
 Terminated (Dead) − A runnable thread enters the terminated state when it
completes its task or otherwise terminates.

THE THREAD CLASS AND THE RUNNABLE INTERFACE:


Java‘s multithreading system is built upon the Thread class, its methods, and its
companion interface, Runnable. Thread encapsulates a thread of execution. Since you can‘t directly refer
to the ethereal state of a running thread, you will deal with it through its proxy, the Thread instance that
spawned it. To create a new thread, your program will either extend Thread or implement the Runnable
interface

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‖);

Java String Methods


1) Java String length(): The Java String length() method tells the length of the
string. It returns count of total number of characters present in the String. For
Here, String length() function will return the length 5 for s1 and 7 for s2
respectively.
2) Java String compareTo(): The Java String compareTo() method compares
the given string with current string. It is a method of ‗Comparable‘ interface
which is implemented by String class. Don‘t worry, we will be learning about
String interfaces later. It either returns positive number, negative number or 0.
For }}
3) Java String concat() : The Java String concat() method combines a specific
string at the end of another string and ultimately returns a combined string. It is
like appending another string. For example:
4) Java String IsEmpty() : This method checks whether the String contains
anything or not. If the java String is Empty, it returns true else false. For
example:
5) Java String Trim() : The java string trim() method removes the leading and
trailing spaces. It checks the unicode value of space character (‗u0020‘) before and
after the string. If it exists, then removes the spaces and return the omitted string.
6) Java String toLowerCase() : The java string toLowerCase() method
converts all the characters of the String to lower case. For example:
7) Java String toUpper() : The Java String toUpperCase() method converts all
the characters of the String to upper case. For example:

ALL STING HANDLING FUNCTIONS IN ONE PROGRAM:


public class StringMethodsExample {
public static void main(String[] args) {
String str = "Hello, World!";

// 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 AND INTRODUCING FILE


HANDLING..
Generics- A simple Generic Example-General form of Generic class-
Generic Interfaces Collections overview, Collection class, Collection interfaces.
Introducing File Handling –File handling in java –Stream –Java File Method –File
Operation in Java-Create file –Write to a file –Read from a file.
____________________________________________________________

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

Java provides a set of standard collection classes that implement Collection


interfaces. Some of the classes provide full implementations that can be used as-is
and others are abstract class, providing skeletal implementations that are used as
starting points for creating concrete collections.

COLLECTION INTERFACES

The collections framework defines several interfaces. This section provides an


overview of each interface –

Sr.No. Interface & Description

1 The Collection Interface


This enables you to work with groups of objects; it is at the top of the collections
hierarchy.

2 The List Interface


This extends Collection and an instance of List stores an ordered collection of
elements.

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

Sr.No. Class & Description

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

1) add() It is used to append the specified element in the given vector.

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.

4) capacity() It is used to get the current capacity of this vector.

5) clear() It is used to delete all of the elements from this vector.

6) get() It is used to get an element at the specified position in the vector.

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.

isEmpty?() Returns true if this list contains no elements.

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).

Method Modifier and Type Method Description

empty() boolean The method checks the stack is empty or not.

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

clear() It is used to remove all of the elements from the set.

contains(Object o) It is used to return true if this set contains the specified element.

isEmpty() It is used to return true if this set contains no elements.

iterator() It is used to return an iterator over the elements in this set.

remove(Object o) It is used to remove the specified element from this set if it is present.

size() It is used to return the number of elements in the set.

Example:
Output:

Linked List:
Method Description

addFirst() Adds an item to the beginning of the list.

addLast() Add an item to the end of the list

removeFirst() Remove an item from the beginning of the list.

removeLast() Remove an item from the end of the list

getFirst() Get the item at the beginning of the list

getLast() Get the item at the end of the list


Output:

Hashmap:
Output:

INTRODUCING FILE HANDLING


FILE HANDLING IN JAVA
File handling in Java implies reading from and writing data to a file. The
File class from the java.io package, allows us to work with different formats of
files. In order to use the File class, you need to create an object of the class and
specify the filename or directory name.

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.

JAVA FILE METHODS


Below table depicts the various methods that are used for performing operations on Java
files.
Method Type Description
canRead() Boolean It tests whether the file is readable or not
canWrite() Boolean It tests whether the file is writable or not
createNewFile() Boolean This method creates an empty file
delete() Boolean Deletes a file
exists() Boolean It tests whether the file exists
getName() String Returns the name of the file
getAbsolutePath() String Returns the absolute pathname of the file
length() Long Returns the size of the file in bytes
list() String[] Returns an array of the files in the directory
mkdir() Boolean Creates a directory

FILE OPERATION IN JAVA


Basically, you can perform four operations on a file. They are as follows:
1. Create a File
2. Get File Information
3. Write To a File
4. Read from a File

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.

INTRODUCING THE AWT…


USING AWT CONTROLS:

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.

Java AWT Hierarchy


The hierarchy of Java AWT classes are given below

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);

13. File Dialog


From a file dialog, a user can select a file which he/she wishes to use.
Syntax:
FileDialog(Dialog parent)

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.

Following are the three types of container classes:


 Panel – It is used to organize components on to a window
 Frame – A fully functioning window with icons and titles
 Dialog – It is like a pop up window but not fully functional like the frame

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

INTRODUCING JAVA8 FEATURES


LAMBDA
EXPRESSION
Lambda expressions are an anonymous function, meaning that they have no
name or identifier. They can be passed as a parameter to another function. They
are paired with a functional interface and feature a parameter with an expression
that references that parameter.

Syntax
The simplest lambda expression contains a single parameter and an expression:
parameter -> expression

To use more than one parameter, wrap them in parentheses:

(parameter1, parameter2) -> 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

default void forEach(Consumer<super T>action)

Example:

METHOD AND CONSTRUCTOR REFERENCE BY DOUBLE COLON(::)


OPERATOR:

The double colon operator (::) introduced in java 8, also known


as method reference operator in java. It is used to call a method by referring to it with
the help of its class/instance. They behave exactly as the lambda expressions. The
only difference it has from lambda expressions is that this uses direct reference to the
method by name instead of providing a delegate to the method.
To reference a method or to reference a constructor, we must use double colon
operator. Following are the various scenarios where it can used.
1. References to static method.
2. References to an instance mrthod of a particular object.
3. References to an instance method of an arbitrary objectr of a particular type.
4. Reference to a constructor.
1. Reference to 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.
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 provides a new additional package in Java 8 called


java.util.stream. This package consists of classes, interfaces and enum to
allows functional-style operations on the elements. You can use stream by
importing java.util.stream package.
Stream Creation
There are many ways to create a stream instance of different sources. Once
created, the instance will not modify its source, therefore allowing the creation of
multiple instances from a single source.
Empty Stream
We should use the empty() method in case of the creation of an empty

stream: Stream<String> streamEmpty = Stream.empty();

DATE & TIME 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.

Local Date-Time API


LocalDate/LocalTime and LocalDateTime classes simplify the development where
timezones are not required. Let's see them in action.
PROGRAM:
// Java code for LocalDate
// / LocalTime Function
import java.time.*;
import java.time.format.DateTimeFormatter;

public class Date {

public static void LocalDateTimeApi()


{

// the current date


LocalDate date = LocalDate.now();
System.out.println("the current date is "+
date);

// the current time


LocalTime time = LocalTime.now();
System.out.println("the current time is "+
time);

// will give us the current time and date


LocalDateTime current = LocalDateTime.now();
System.out.println("current date and time : "+
current);

// to print in a particular format


DateTimeFormatter format =
DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm:ss");

String formatedDateTime = current.format(format);

System.out.println("in formatted manner "+


formatedDateTime);

// printing months days and seconds


Month month = current.getMonth();
int day = current.getDayOfMonth();
int seconds = current.getSecond();
System.out.println("Month : "+month+" day : "+
day+" seconds : "+seconds);

// printing some specified date


LocalDate date2 = LocalDate.of(1950,1,26);
System.out.println("the republic day :"+date2);

// printing date with current time.


LocalDateTime specificDate =
current.withDayOfMonth(24).withYear(2016);

System.out.println("specific date with "+


"current time : "+specificDate);
}

// Driver code
public static void main(String[] args)
{
LocalDateTimeApi();
}
}

Output:

SUBMITTED BY
BABI AZEES SHAIK

You might also like