Unit1_Java
Unit1_Java
Example:
public enum TypeName {
CONSTANT1,
CONSTANT2,
CONSTANT3,
// add more constants as needed
}
enum Level {
LOW, MEDIUM, HIGH
}
public class EnumLevel {
public static void main(String[] args) {
Level myVar = Level.MEDIUM;
switch(myVar) {
case LOW:
System.out.println("Low level");
break;
case MEDIUM:
System.out.println("Medium level");
break;
case HIGH:
System.out.println("High level");
break;
} } }
enum Day { // Define an enum for days of the week
SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY
}
public class EnumDay {
public static void main(String[] args) {
for (Day day : Day.values()) { // Print all days of the week using the enum
System.out.println(day);
}
Day today = Day.MONDAY; // Accessing a specific enum constant
System.out.println("Today is: " + today);
} Enum Declaration: The Day enum is declared with the days of
} the week as its constants (SUNDAY, MONDAY, etc.).
Using Enum: In the main method, we iterate through all the
enum constants using Day.values() and print each day.
Accessing Specific Enum: We access a specific enum constant
(Day.MONDAY) and print it.
values() and valuesOf() methods
• values(): Returns an array of all the values defined in an enumeration
• valueOf(): Returns an enum constant by its name
enum Direction {
East, South, West, North
}
public class EnumDirection {
public static void main(String args[]) {
Direction dir;
Direction all[] = Direction.values(); // use values()
for (Direction a : all)
System.out.println(a);
System.out.println();
dir = Direction.valueOf("South"); // use valueOf()
System.out.println(“The current direction is” +dir);
} }
Enumerations are class types
enum fruits {
// Attributes associated to enum
Apple(120), Kiwi(60), Banana(20), Orange(80);
// internal data
private int price;
// Constructor
fruits(int pr) { price = pr; }
// Method
int getPrice() { return price; }
}
class Enumconstructor {
public static void main(String[] args)
{
System.out.println("All fruit prices : ");
// Iterating using enhanced for each loop
for (fruits f : fruits.values())
// Print and display the cost and perkg cost of fruits
System.out.println(f + " costs " + f.getPrice() + " rupees per kg.");
}
All fruit prices :
} Apple costs 120 rupees per kg.
Kiwi costs 60 rupees per kg.
Banana costs 20 rupees per kg.
Orange costs 80 rupees per kg.
Type Wrappers
• A Wrapper class in Java is a class whose object wraps or contains primitive
data types.
• Wrapper classes provide a way to use primitive data types (int, boolean,
etc..) as objects.
• In Java, sometimes we might need to use objects instead of primitive data
types. For example, while working with collections.
ArrayList<int> list = new ArrayList<>(); // error
ArrayList<Integer> list = new ArrayList<>(); // runs perfectly
We can store the null value in wrapper objects. For example,
int a = null; // error
Integer a = null; // runs perfectly
Primitive Data Type Wrapper Class
byte Byte
short Short
int Integer
long Long
float Float
double Double
boolean Boolean
char Character
To create a wrapper object, use the wrapper class instead of the primitive type.
The following methods are used to get the value associated with the
corresponding wrapper object: intValue(), byteValue(), shortValue(),
longValue(), floatValue(), doubleValue(), charValue(), booleanValue()
@FunctionalInterface
interface FuncInter1 {
int operation(int a, int b);
}
public class Test {
public static void main(String[] args) {
// Using lambda expressions to define the operations
FuncInter1 add = (a, b) -> a + b;
FuncInter1 multiply = (a, b) -> a * b;
// Using the operations
System.out.println(add.operation(6, 3)); // Output: 9
System.out.println(multiply.operation(4, 5)); // Output: 20
}
}
Block Lambda Expressions
• Java supports Expression Lambdas which contains blocks of code with more
than one statement. We call this type of Lambda Body a “Block Body“.
Lambdas that contain block bodies can be known as “Block Lambdas“.
• Block Lambda contains many operations that work on lambda expressions
as it allows the lambda body to have many statements.
• This includes variables, loops, conditional statements like if, else and switch
statements, nested blocks, etc. This is created by enclosing the block of
statements in lambda body within braces {}. This can even have a return
statement i.e return value.
Syntax:
Syntax
interface SomeFunc {
T func(T t);
}
interface MyGeneric<T> {
T compute(T t);
}
public class LambdaGenericFuncI {
public static void main(String args[]) {
MyGeneric<String> reverse = (str) -> { // Lambda Expression
String result = "";
for(int i = str.length()-1; i >= 0; i--)
result += str.charAt(i);
return result;
};
MyGeneric<Integer> factorial = (Integer n) -> { // Lambda Expression
int result = 1;
for(int i=1; i <= n; i++)
result = i * result;
return result;
};
MyGeneric<Double> tax=(Double d) ->{
return tax*0.05;
};
System.out.println(reverse.compute("Generic Functional Interfaces"));
System.out.println(factorial.compute(7));
System.out.println(“Tax is:” +tax.compute(2353.56));
}
Passing Lambda expression as
arguments
• A lambda expression is an anonymous function that can be passed as
an argument to a method.
• In Java, we can pass a lambda expression as an argument to a method.
A lambda expression provides a clear and concise way to express
instances of functional interfaces.
• When we use a lambda expression to a method, the lambda
essentially implements the functional interface expected by the
method.
• A functional interface is an interface with only one abstract method.
@FunctionalInterface
interface MathOperation {
int operate(int a, int b);
}
public class LambdaExample {
// Method that accepts a MathOperation and performs the operation
public static int performOperation(int a, int b, MathOperation operation) {
return operation.operate(a, b);
}
public static void main(String[] args) {
// Passing a lambda expression to the method
int result = performOperation(5, 3, (a, b) -> a + b); // Lambda expression for addition
System.out.println("Addition Result: " + result);
result = performOperation(5, 3, (a, b) -> a - b); // Lambda expression for subtraction
System.out.println("Subtraction Result: " + result);
}
}
IO Basics
• Java I/O (Input and Output) is used to process the input and
produce the output.
• Java uses the concept of a stream to make I/O operation fast.
The java.io package contains all the classes required for input
and output operations.
• Streams: Streams represent a sequence of data. In Java, there
are two types of streams: input streams and output streams.
• Input streams are used to read data from a source, while output
streams are used to write data to a destination.
Byte Streams and Character Streams
• Character streams are useful in reading or writing text files which
are processed character by character.
• Java character streams are used to perform input and output for
16-bit unicode.
• Character stream is used to read and write a single character of
data.
• Using these we can read and write text data only.
• Byte streams are useful to read/write data from raw binary files.
• Java byte streams are used to perform input and output of 8-bit
bytes.
• Byte stream is used to read and write a single byte (8 bits) of data.
• Using these you can store characters, videos, audios, images etc.
Byte Stream classes
• ByteStream classes are used to read bytes from the input stream
and write bytes to the output stream.
• In other words, we can say that ByteStream classes read/write
the data of 8-bits.
• These classes are part of the java.io package.
• The ByteStream classes are divided into two types of classes, i.e.,
InputStream and OutputStream.
• The InputStream class provides methods to read bytes from a
file, console or memory.
• The OutputStream is used to write 8-bit bytes to the stream.
InputStream classes
• BufferedInputStream - This class provides methods to read bytes from
the buffer.
• DataInputStream - This class provides methods to read Java primitive
data types.
• FileInputStream - This class provides methods to read bytes from a
file.
OutputStream classes
• BufferedOutputStream - This class provides methods to write the
bytes to the buffer.
• DataOutputStream - This class provides methods to write the java
primitive data types.
• FileOutputStream - This class provides methods to write bytes to a
file.
Character Stream classes
• CharacterStream classes are used to work with 16-bit Unicode
characters. They can perform operations on characters, char arrays
and Strings.
• The CharacterStream classes are mainly used to read characters from
the source and write them to the destination.
• For this purpose, the CharacterStream classes are divided into two
types of classes, I.e., Reader class and Writer class.
• Reader class is used to read the 16-bit characters from the input
stream. All methods of the Reader class throw an IOException.
• Writer class is used to write 16-bit Unicode characters to the output
stream. The methods of the Writer class generate IOException.
Reader classes
• BufferedReader - This class provides methods to read characters from
the buffer.
• FileReader - This class provides methods to read characters from the
file.
• InputStreamReader - This class provides methods to convert bytes to
characters.
Writer classes
• BufferedWriter - This class provides methods to write characters to the
buffer.
• FileWriter - This class provides methods to write characters to the file.
• OutpuStreamWriter - This class provides methods to convert from bytes
to characters.
Predefined streams
• System class also contains three predefined stream variables, in, out, and
err.
• System.in refers to standard input, which is the keyboard by default.
Accessed through in which is used to read input from the keyboard.
• System.in is an object of type InputStream. To use Standard Input as a
character stream, wrap System.in within the InputStreamReader as an
argument.
• System.in is a byte stream that has no character stream features.
• To obtain a character-based stream that is attached to the console, we
wrap System.in in a BufferedReader object.
BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
• System.out and System.err are objects of type PrintStream.
System.out refers to the standard output stream. By default, this is the
console. Accessed through out which is used to write output to the
display (console).
System.out.println("This is a regular message.");
• System.err refers to the standard error stream, which also is the console
by default. Accessed through err which is used to write error output to
the display (console).
System.err.println("This is an error message.");
Reading Console Input
The constructor for BufferedReader is:
BufferedReader(Reader in, Charset cs)
Output:
Aa#
PrintWriter Class
• The PrintWriter class of the java.io package can be used to write
output data in a commonly readable form (text).
• PrintWriter converts the primitive data(int, float, char, etc.) into the
text format. It then writes that formatted data to the writer.
Constructor
PrintWriter(OutputStream outputstream, boolean flushingOn)
Example
PrintWriter pw=new PrintWriter(System.out, true);
If flushingOn is true, flushing automatically takes place. If false, flushing
is not automatic.
public class PrintWriterExample {
public static void main(String[] args) {
//Data to write on Console using PrintWriter
PrintWriter writer = new PrintWriter(System.out, true);
writer.write("writing the data on a console");
writer.close();
//Data to write in File using PrintWriter
PrintWriter writer1 =null;
try {
writer1 = new PrintWriter(new File("D:\\testout.txt"));
writer1.write("writing the data in a text file testout.txt ");
} catch (FileNotFoundException e) {
System.out.println("An error occurred: " + e.getMessage());
} finally { // Close the writer if it was initialized
if (writer1 != null) {
writer1.close();
}
}}}
Reading and Writing Files
• Java provides a number of classes and meyhods that allow you to
read and write files.
• Two of the most often used stream classes are FileInputStream and
FileOutputStream which create byte streams linked to files.
• To open a file, you simply create an object of these classes, specifying
the name of the file as an argument to the constructor.
Constructors
FileInputStream(String fileName) throws FileNotFoundException
FileOutputStream(String fileName) throws FileNotFoundException
fileName specifies the name of the file that you want to open. When
you create an input stream, if the file does not exist, then
FileNotFoundException is thrown.
• When you are done with a file, you must close it. This is done by the
close() method.
void close() throws IOException
• Closing a file releases the system resources allocated to the file, allowing
them to be used by another file.
• To read from a file, you can use a version of read() that is defined within
FileInputStream.
int read() throws IOException
• Each time that is called,it reads a single byte from the file and returns
the byte as an integer value read() returns -1 when an attempt to read at
the end of the stream. It can throw an IOException.
import java.io.*;
public class FileReadWrite
{
public static void main(String[] args) {
try { // Write to a file
FileWriter writer = new FileWriter("c:\\test.txt");
writer.write("Hello! This is a test file.\n");
writer.write("This is the second line.");
writer.close();
System.out.println("Successfully wrote to the file.");
} catch (IOException e) {
System.out.println("An error occurred while writing the file.");
e.printStackTrace();
}
// Read from the file
try {
FileReader reader = new FileReader("c:\\test.txt");
int character;
System.out.println("\nContent of the file:");
while ((character = reader.read()) != -1) {
System.out.print((char) character);
}
reader.close();
} catch (IOException e) {
System.out.println("An error occurred while reading the file.");
e.printStackTrace(); Successfully wrote to the file.
}
Content of the file:
} Hello! This is a test file.
} This is the second line.