Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
31 views

Java Final-2

Uploaded by

roughuse2029
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
31 views

Java Final-2

Uploaded by

roughuse2029
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 35

Java Arrays

An array is a collection of similar type of elements which has contiguous memory location.

Advantages

• Code Optimization: It makes the code optimized, we can retrieve or sort the data
efficiently.
• Random access: We can get any data located at an index position.
• Efficient for Iteration: Java arrays are well-suited for iterative operation.

Disadvantages

• Size Limit: We can store only fixed size of elements in the array. It doesn’t grow its size
at runtime.
• Homogeneous data type: Arrays in Java store elements of the same data type.
• No Built-in Resize Mechanism: Unlike some dynamic data structures like ArrayList, Java
arrays do not have a built-in mechanism for automatic resizing.

Types

• Single Dimensional Array


• Multidimensional Array

Single Dimensional Array


Syntax to Declare and Instantiation of an Array in Java
dataType[] arr = new dataType[size]; (or)
dataType []arr = new dataType[size]; (or)
dataType arr[] = new dataType[size];

Example
Multidimensional Array

Syntax to Declare and Instantiate Multidimensional Array in Java


dataType[][] array = new dataType[size][size]; (or)
dataType [][]array = new dataType[size][size]; (or)
dataType array[][] = new dataType[size][size]; (or)

Example to initialize Multidimensional Array in Java


Example of Multidimensional Array in Java

Output

For-each Loop for Java Array

Syntax:
Example:

Anonymous Array in Java


An array in Java without any name is known as anonymous array.

Examples
Some Important Array methods
1. ‘toString’: Returns a string representation of the contents of an array

2. ‘copyOf’: Copies the specified array.

3. ‘equals’: Checks if two arrays are equal or not. It returns a Boolean value

4. ‘fill’: Assigns the specified value to each element of the specified array.

5. ‘sort’: Sorts the specified array into ascending order

Sorting into descending order


6. ‘asList’: Converts an array to a fixed-size list.

7. ‘stream’: converts an array to a stream.

Loops in Java

In Java, a loop is a control flow statement that allows a certain block of code to be
executed repeatedly.

For Loop:
The for loop is used when the number of iterations is known in advance. It consists of
three parts: initialization, condition, and iteration expression.
Syntax:

Example:
While Loop:
The while loop is used when the number of iterations is not known in advance, and it
depends on a specified condition.
Syntax:

Example:

Do-While Loop:
The do-while loop is similar to the while loop, but it guarantees that the code block is
executed at least once because the condition is checked after the block is executed.
Syntax:

Example:
Decision Making Statements
Decision making statements decide which statement to execute and when.
Decision making statements are two types

• If-else statement
• Switch statement

If-else statement:
Syntax:

Nested if-else
Syntax:
Switch Statement:
Syntax:

Jump statements

• break statement
• continue statement

break statement:
The break statement is used to break the current flow of the program and transfer the control
to the next statement outside a loop or switch statement.
continue statement:
Unlike break statement, the continue statement doesn’t break the loop, whereas, it skips the
specific part of the loop and jumps to the next iteration of the loop immediately.
Example:

Encapsulation in Java
Encapsulation is a process of wrapping code and data together into single unit.
Example:
Polymorphism in Java
Polymorphism in Java is the task that performs a single action in different ways.
There are two types of polymorphism in Java
1. Compile-time Polymorphism (Method Overloading)
2. Runtime Polymorphism (Method Overriding)

Compile-time Polymorphism (Method Overloading)


Method Overloading allows a class to have multiple methods having the same name, but
different parameter lists.

Example:

Runtime Polymorphism (Method Overriding)


Method overriding occurs when a subclass provides a specific implementation for a method
that is already defined in its superclass.

Example:
Method Overloading VS Method Overriding

Method Overloading Method Overriding


Method overloading is performed within Method overriding occurs in two classes that
class. have inheritance relationship.

In case of method overloading, parameter In case of method overriding, parameter


must be different. must be same.

Method overloading is the example of Method overriding is the example of run time
compile time polymorphism. polymorphism.
Inheritance in Java
Inheritance allows a class (subclass) to inherit the properties and behaviors of another class
(superclass or base class).

Types

• Single Inheritance
• Multiple Inheritance (through Interface)
• Multilevel Inheritance
• Hierarchical Inheritance
• Hybrid Inheritance

Single Inheritance
In single inheritance, a class can only inherit from one superclass

Multiple Inheritance (through Interface)


Java does not support multiple inheritance directly with classes, meaning a class cannot directly
extend more than one class.
However, Java support multiple inheritance through interface. A class can implement multiple
inheritance.
Multilevel Inheritance
In multilevel inheritance, a class derived from another class, and then another class is derived
from that class.
Hierarchical Inheritance
In hierarchical inheritance, multiple classes are derived from a single base class.
Hybrid Inheritance
Hybrid inheritance is a combination of two or more types of inheritance.

Constructor in Java
A constructor is a special method within a class that is automatically called when an instance of
that class is created.
Types

• Default constructor (no-arg constructor)


• Parameterized constructor

Default constructor
A constructor is called default constructor when it doesn’t have any parameter.
Parameterized constructor
A constructor which has a specific number of parameters is called a parameterized constructor.
Java String Processing
1. charAt(int index):
• Returns the character at the specified index.

2. length():
• Returns the length of the string.

3. Substring(int beginIndex, int endIndex):


• Returns a new string that is a substring of the original string, starting from the
specified beginIndex (inclusive) and ending at the specified endIndex (exclusive).

4. concat(String str):
• Concatenates the specified string to the end of the original string.

5. indexOf(string str):
• Returns the index of the first occurrence of the specified substring.

6. toLowerCase() and toUpperCase():


• Returns a new string with all characters in lowercase or uppercase, respectively.
7. trim():
• Returns a new string with leading and trailing whitespaces removed.

8. replace(char oldChar, char newChar):


• Replaces occurrences of a specified character or substring with another character or
substring.

9. startsWith(String prefix) and endsWith(String suffix)


• checks if the string starts or ends with the specified prefix or suffix.

10. isEmpty():
• Returns true if the string is empty, otherwise returns false.

11. equals() and equalsIgnoreCase():


• Checks if the string is equal to another string. ‘equalsIgnoreCase’ performs a case-
sensitive comparison.

12. indexOf() and lastIndexOf():


• Returns the index of the first or last occurrence of the specified character.
String Tokenizer in Java
The java.util.StringTokenizer class allows you to break a String into tokens. It is simple
way to break a String.

Methods

Methods Description
boolean hasMoreTokens() It checks if there is more tokens available.

String nextToken() It returns the next token from the


StringTokenizer object.
int countTokens() It returns the total number of tokens.

Example
StringBuffer in Java
In Java, StringBuffer is a class that provides a mutable sequence of characters. It is part
of the ‘java.lang’ package and is used for manipulating strings.
Mutable means that you can modify their content.

Some important methods


1. ‘append(String str)’: This method is used to add the specified string at end of the
existing StringBuffer object.

2. ‘insert()’: Inserts the specified string at the specified index in the StringBuffer object.

3. ‘delete(int start, int end)’: Deletes the characters from the start index to the end-1
index in the StringBuffer.

4. ‘deleteCharAt(int index)’: Deletes the character at the specified index in the


StringBuffer.

5. ‘replace(int start, int end, String str)’: Replaces the characters from the start index
to the end-1 index with the specified string.
6. ‘reverse()’: Reverse the characters in the StringBuffer object.

7. ‘toString()’: Converts the StringBuffer object to a String.

StringBuilder in Java
In Java, the StringBuilder class is part of the ‘java.lang’ package and provides a mutable
sequence of characters.

Some important methods


1. ‘append()’: Appends the specified string representation to the end of the sequence.

2. ‘insert()’: Insert the specified string representation at the specified position in the
sequence.

3. ‘delete()’: Remove a substring of characters from the sequence. The substring to be


removed starts from the start index (inclusive) and ends at the end index (exclusive).
4. ‘deleteCharAt()’: Removes the character at the specified position.

5. ‘replace()’: Replaces a specific substring with another string.

6. ‘reverse()’: Reverses the sequence of characters in the StirngBuilder.

StringBuffer VS StringBuilder
Java Exception Handling
The Exception Handling in Java is one of the powerful mechanism to handle the runtime
errors so that the normal flow of the application can be maintained.

Some important exception


ArithmeticException:

ArrayIndexOutOfBoundsException:
FileNotFoundException:

NullPointerException:
Stream in Java
Stream is introduced in Java 8, Stream API is used to process collections of
objects.
A stream in Java is a sequence of objects that supports various methods which
can be pipelined to produce the desired result.

Use of Stream in Java


There uses of Stream in Java are mentioned below:
1. Stream API is a way to express and process collections of objects.
2. Enable us to perform operations like filtering, mapping, reducing and
sorting.
Create Java Stream
Syntax: Stream<T> stream;
Here T is either a class, object, or data type depending upon the declaration.

Different Operations On Streams


There are two types of Operations in Streams:
1. Intermediate Operations
2. Terminate Operations

Intermediate Operations
Intermediate Operations are the types of operations in which multiple methods
are chained in a row.
Important Intermediate Operations
There are a few Intermediate Operations mentioned below:
1. map()
The map method is used to return a stream consisting of the result of applying
the given function to the elements of this stream.
2. filter()
The filter method is used to select elements as per the Predicate passed as an
argument.
3. sorted()
The sorted method is used to sort te stream.

Example:

Terminal Operations
Terminal Operations are the type of Operations that return the result. These
Operations are not processed further just return a final result value.

Important Terminal Operations


There are a few Terminal Operations mentioned below:
1. collect()
The collect method is used to return the result of the intermediate
operations performed on the stream.

2. forEach()
The forEach method is used to iterate through every element of the stream.

3. reduce()
The reduce method is used to reduce the elements of a stream to a single
value. The reduce method takes a BinaryOperator as a parameter.

Stream IO (input/Output):

InputStream:
OutputStream:
File Reading/Writing
There are multiple ways of writing and reading a text file in Java. This is
required while dealing with many applications. There are several ways to
read a plain text file in Java e.g. we can use FileReader, BufferedReader, or
Scanner to read a text file. Every utility provides something special e.g.
BufferedReader provides buffering of data for fast reading, and Scanner
provides parsing ability.
Methods:
1. Using BufferedReader/BufferedWriter class
2. Using Scanner class

1. BufferedReader/BufferedWriter class for file reading and writing


Example:
2. Scanner class for file reading
The ‘Scanner’ class in Java is primarily designed for reading input, and it
doesn’t provide direct methods for writing to files. If we need to write to a
file, it’s generally more appropriate to use classes like ‘FileWriter’,
‘BufferedWriter’, or ‘PrintWriter’.
Example:
Thread in Java
A Thread is a very light-weighted process, or we can say the smallest part of
the process that allows a program to operate more efficiently by running
multiple tasks simultaneously.

Create Threads using Java


We can create Threads in java using two ways,
1. Extending Thread Class
2. Implementing a Runnable interface

1. Extending Thread Class

2. Implementing a Runnable interface


Multithreading
Multithreading in Java refers to the concurrent execution of two or more threads.
Multithreading allows a program to perform multiple tasks concurrently, thereby
improving the overall performance and responsiveness of the application.

Multitasking
When a single processor (CPU) does many jobs (program, threads, process, task)
simultaneously, it is called multi-tasking.

Difference between Multithreading and Multitasking


Features Multithreading Multitasking
Basic Multithreading allows a CPU to A CPU may perform multiple tasks at
generate numerous threads from a once by using the multitasking
job and process them all at the method.
same time.
Resources The system assigns a single memory The system must assign different
and block to each process. resources and memory to separate
Memory
programs that are running
concurrently in multitasking.
Switching CPU switches between the threads CPU switches between programs
frequently. frequently.
Speed of It is comparatively faster in It is comparatively slower in
Execution execution. execution.

Swing Components
1. JFrame:
• A top-level container that represents the main window of an application.

2. JPanel:
• A Container that can hold other components.

3. JButton:
• A button that can trigger an action when clicked.

4. JTextField:
• A single-line text input field.

5. JTextArea:
• A multi-line text area.
6. JLabel:
• A non-editable text display.

7. JCheckBox:
• A checkbox for selecting multiple options.

8. JRadioButton:
• A radio button for selecting a single option from a group.

9. JComboBox:
• A drop-down list of items.

10. JScrollPane:
• A scrollable pane that allows viewing content that doesn’t fit in a container.

11. JDiolog:
• A pop-up dialog box.

12. JProgressBar:
• A component that visually displays the progress of a task.

You might also like