Java3 (New)
Java3 (New)
Arrays :
Java Arrays:
Accessing Elements: Individual elements are accessed using their index, which starts from 0.
EX:
int[] numbers = {10, 20, 30};
int firstElement = numbers[0]; // Accesses the element at index 0 (value 10)
Modifying Elements: Values of elements can be changed by assigning a new value to a specific
index.
Traversing Elements: Iterating through all elements, typically using a for loop or an enhanced for-
each loop.
import java.util.Arrays;
int[] numbers = {50, 20, 40, 10, 30};
Arrays.sort(numbers); // Sorts the array: {10, 20, 30, 40, 50}
Filling Elements: Assigning a specific value to all elements in an array using Arrays.fill().
import java.util.Arrays;
int[] numbers = new int[5];
Arrays.fill(numbers, 7); // Fills the array with 7s: {7, 7, 7, 7, 7}
EX:
import java.util.Scanner;
public class CodesCracker
{
public static void main(String[] args)
{
int size=10, i, search, first, last, middle;
int[] arr = new int[size];
Scanner scan = new Scanner(System.in);
System.out.print("Enter 10 Elements (in Ascending): ");
for(i=0; i<size; i++)
{
arr[i] = scan.nextInt();
}
System.out.print("Enter an Element to Search: ");
search = scan.nextInt();
first = 0;
last = size-1;
middle = (first+last)/2;
while(first<=last)
{
if(arr[middle]<search)
{
first = middle+1;
}
else if(arr[middle]==search)
{
System.out.println("\nThe element is available at Index No." +middle);
break;
}
else
{
last = middle-1;
}
middle = (first+last)/2;
}
if(first>last)
{
System.out.println("\nThe element is not available in given array");
}
}
}
Assigning Array to Another Array :
Copying an array can be done in several ways, depending on our needs such as shallow copy or deep copy.
Assigning one array to another array variable results in a shallow copy.
shallow copy meaning both array variables will refer to the same underlying array object in memory.
Shallow Copy (Assignment Operator):
int[] originalArray = {1, 2, 3};
int[] assignedArray = originalArray; // assignedArray now points to the same object as originalArray
EX:
public class Test {
public static void main(String[] args) {
int a[] = { 1, 8, 3 };
EX:
// Java Program to Implement a Dynamic Array
if (arr.length == count) {
arr[count++] = ele;
}
}
Sorting of Arrays :
The sort() method sorts an array in ascending order. This method sorts arrays of strings alphabetically, and
arrays of integers numerically.
EX:
// Java Program to Implement sort()
import java.util.Arrays;
class Geeks {
public static void main(String args[]) {
// Integer Array
int[] a = { 2, -1, 3, 4 };
// Character Array
char[] b = { 'b', 'a', 'c', 'b' };
// Sort both arrays
Arrays.sort(a);
Arrays.sort(b);
EX:
public class ArraySearch {
public static boolean linearSearch(int[] arr, int target) {
for (int element : arr) {
if (element == target) {
return true; // Value found
}
}
return false; // Value not found
}
}
EX:
// Java program to check whether
// an element is present in array or not
import java.util.Arrays;
import java.util.stream.IntStream;
class Geeks
{
// Method to check if the specified element
// is present in the array or not
private static boolean isElementPresent(int[] arr, int key)
{
// check if the specified element
// is present in the array or not
// using Linear Search method
for (int element : arr) {
if (element == key) {
return true;
}
}
return false;
}
}
}
EX:
// Java program to check whether
// an element is present in array or not
import java.util.Arrays;
import java.util.stream.IntStream;
class Geeks
{
// Method to check if the specified element
// is present in the array or not
private static boolean isElementPresent(int[] arr, int key)
{
// sort given array
Arrays.sort(arr);
}
}
The Arrays class in Java, found in the java.util package, is a utility class that provides static methods for
manipulating arrays. It is part of the Java Collections Framework and offers various functionalities for
common array operations.
Key aspects of the Arrays class:
Static Methods:
All methods within the Arrays class are static, meaning they can be called directly using the class name
(e.g., Arrays.sort()) without needing to create an instance of the Arrays class.
Array Manipulation:
It provides methods for a wide range of array manipulations, including:
Sorting: sort() methods for various primitive types and objects.
Searching: binarySearch() for efficiently searching sorted arrays.
Comparing: equals() for comparing two arrays for equality.
Filling: fill() for assigning a specific value to all elements of an array.
Copying: copyOf() and copyOfRange() for creating copies of arrays or sub-arrays.
Converting to List: asList() to view an array as a fixed-size List.
NullPointerException:
Most methods in the Arrays class throw a NullPointerException if the specified array reference is null,
unless otherwise noted in the method's documentation.
Implementation Notes:
The documentation for the methods often includes brief descriptions of their implementations, which are
considered implementation notes rather than parts of the strict specification. This allows implementers to
substitute different algorithms as long as the method's specified behavior is maintained.
EX:
class Testarray3{
public static void main(String args[]){
//declaring and initializing 2D array
int arr[][]={{1,2,3},{2,4,5},{4,4,5}};
//printing 2D array
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
System.out.print(arr[i][j]+" ");
}
System.out.println();
}
}}
Three-dimensional Arrays :
a three-dimensional (3D) array is essentially an array of two-dimensional (2D) arrays. This structure allows
for storing data in a cube-like or layered fashion, where each element is accessed using three indices.
};
EX:
import java.io.*;
class Geeks
int[][][] arr = { { { 1, 2 }, { 3, 4 } }, { { 5, 6 }, { 7, 8 } } };
// Dimensional Array
int n = arr.length;
int m = arr[0].length;
int o = arr[0][0].length;
// Printing the Array
arrays have a fixed length determined at the time of creation, arrays of varying lengths can be achieved
through specific structures:
EX :
import java.util.ArrayList;
ArrayList<String> dynamicArray = new ArrayList<>(); // Create an ArrayList of Strings
dynamicArray.add("Banana");
dynamicArray.add("Cherry");
// The size of dynamicArray can change as more elements are added or removed.Arrays as Vectors :
the Vector class provides functionality similar to a dynamic array, allowing for a growable array of
objects. While both Vector and traditional Java arrays can store collections of elements, they differ in key
aspects:
Key Differences:
Fixed vs. Dynamic Size:
Java arrays have a fixed size defined at creation and cannot be resized. Vector, on the other hand, is
dynamic and can automatically expand or shrink as elements are added or removed.
Synchronization:
Vector is a legacy class and is synchronized, meaning its methods are thread-safe. This can lead to
performance overhead in single-threaded environments compared to ArrayList, which is not synchronized
by default.
Legacy Class:
Vector was part of the original Java Collections Framework, but ArrayList is generally preferred for new
code due to its better performance in most scenarios.
Converting between Arrays and Vectors:
Array to Vector:
Using Collections.addAll(): This method can efficiently add all elements from an array to a Vector.
Using Arrays.asList(): This creates a fixed-size List from an array, which can then be used to initialize
a Vector.
Using a loop: Iterate through the array and add each element to the Vector one by one.
Vector to Array:
Using Vector.toArray(): This method returns a new array containing all elements from the Vector. An
overloaded version allows specifying the runtime type of the returned array.
Example of converting an array to a Vector:
import java.util.Arrays;
import java.util.Vector;
import java.util.Vector;
myVector.add("red");
myVector.add("green");
myVector.add("blue");
myArray = myVector.toArray(myArray);
System.out.println("Array elements:");
System.out.println(s);
}
UNIT – II
Inheritance in Java is a mechanism one object acquires all the properties and behaviors of a parent object.
It is an important part of OOPs (Object Oriented programming system).
inheritance in Java is that you can create new classes that are built upon existing classes. When you inherit
from an existing class, you can reuse methods and fields of the parent class. Moreover, you can add new
methods and fields in your current class also.
Inheritance represents the IS-A relationship which is also known as a parent-child relationship.
o Class: A class is a group of objects which have common properties. It is a template or blueprint from
which objects are created.
o Sub Class/Child Class: Subclass is a class which inherits the other class. It is also called a derived
class, extended class, or child class.
o Super Class/Parent Class: Superclass is the class from where a subclass inherits the features. It is
also called a base class or a parent class.
o Reusability: As the name specifies, reusability is a mechanism which facilitates you to reuse the
fields and methods of the existing class when you create a new class. You can use the same fields and
methods already defined in the previous class.
extends Keyword
extends is the keyword used to inherit the properties of a class. Following is the syntax of extends keyword.
Syntax
class Super {
.....
.....
}
class Sub extends Super {
.....
.....
}
As displayed in the above figure, Programmer is the subclass and Employee is the superclass. The
relationship between the two classes is Programmer IS-A Employee. It means that Programmer is a type of
Employee.
EX:
class Employee{
float salary=40000;
}
class Programmer extends Employee{
int bonus=10000;
public static void main(String args[]){
Programmer p=new Programmer();
System.out.println("Programmer salary is:"+p.salary);
System.out.println("Bonus of Programmer is:"+p.bonus);
}
}
Types of inheritance in java
On the basis of class, there can be three types of inheritance in java: single, multilevel and hierarchical.
In java programming, multiple and hybrid inheritance is supported through interface only. We will learn
about interfaces later.
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.
EX:
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class TestInheritance{
public static void main(String args[]){
Dog d=new Dog();
d.bark();
d.eat();
}}
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.
EX:
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class BabyDog extends Dog{
void weep(){System.out.println("weeping...");}
}
class TestInheritance2{
public static void main(String args[]){
BabyDog d=new BabyDog();
d.weep();
d.bark();
d.eat();
}}
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.
Ex:
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class Cat extends Animal{
void meow(){System.out.println("meowing...");}
}
class TestInheritance3{
public static void main(String args[]){
Cat c=new Cat();
c.meow();
c.eat();
//c.bark();//C.T.Error
}}
EX :
class Animal {
// method in the superclass
public void eat() {
System.out.println("I can eat");
}
}
class Main {
public static void main(String[] args) {
// Driver class
class Dispatch
{
public static void main(String args[])
{
// object of type A
A a = new A();
// object of type B
B b = new B();
// object of type C
C c = new C();
// obtain a reference of type A
A ref;
A class which is declared with the abstract keyword is known as an abstract class in Java. It can have
abstract and non-abstract methods (method with the body).
Abstraction in Java
Abstraction is a process of hiding the implementation details and showing only functionality to the user.
Another way, it shows only essential things to the user and hides the internal details, for example, sending
SMS where you type the text and send the message. You don't know the internal processing about the
message delivery.
Points to Remember
o An abstract class must be declared with an abstract keyword.
o It can have abstract and non-abstract methods.
o It cannot be instantiated.
o It can have constructors and static methods also.
o It can have final methods which will force the subclass not to change the body of the method.
Mostly, we don't know about the implementation class (which is hidden to the end user), and an object of the
implementation class is provided by the factory method.
A factory method is a method that returns the instance of the class. We will learn about the factory method
later.
In this example, if you create the instance of Rectangle class, draw() method of Rectangle class will be
invoked.
he java final keyword can be used in many context. Final can be:
1. variable
2. method
3. class
The final keyword can be applied with the variables, a final variable that have no value it is called blank final
variable or uninitialized final variable. It can be initialized in the constructor only. The blank final variable can
be static also which will be initialized in the static block only. We will have detailed learning of these. Let's first
learn the basics of final keyword.
If you make any variable as final, you cannot change the value of final variable(It will be constant).
There is a final variable speedlimit, we are going to change the value of this variable, but It can't be changed
because final variable once assigned a value can never be changed.
EX:
class Bike9{
final int speedlimit=90;//final variable
void run(){
speedlimit=400;
}
public static void main(String args[]){
Bike9 obj=new Bike9();
obj.run();
}
}//end of class
An interface in Java is a blueprint of a class. It has static constants and abstract methods.
The interface in Java is a mechanism to achieve abstraction. There can be only abstract methods in the Java
interface, not method body. It is used to achieve abstraction and multiple inheritance in Java.
In other words, you can say that interfaces can have abstract methods and variables. It cannot have a method
body.
declare an interface :
An interface is declared by using the interface keyword. It provides total abstraction; means all the methods
in an interface are declared with the empty body, and all the fields are public, static and final by default. A
class that implements an interface must implement all the methods declared in the interface.
Syntax:
interface <interface_name>{
Interface fields are public, static and final by default, and the methods are public and abstract.
The relationship between classes and interfaces
As shown in the figure given below, a class extends another class, an interface extends another interface, but
a class implements an interface.
Example:
interface printable{
void print();
}
class A6 implements printable{
public void print(){System.out.println("Hello");}
EX:2
// Java program to demonstrate the
// real-world example of Interfaces
import java.io.*;
interface Vehicle {
int speed;
int gear;
// to change gear
@Override
public void changeGear(int newGear){
gear = newGear;
}
// to increase speed
@Override
public void speedUp(int increment){
// to decrease speed
@Override
public void applyBrakes(int decrement){
speed = speed - decrement;
}
int speed;
int gear;
// to change gear
@Override
public void changeGear(int newGear){
gear = newGear;
}
// to increase speed
@Override
public void speedUp(int increment){
speed = speed + increment;
}
// to decrease speed
@Override
public void applyBrakes(int decrement){
}
class GFG {
interface Interface1
class ExtendingInterface
v2.f1();
v2.f2();
x xl=new x();
xl.f3();
An interface, i.e., declared within another interface or class, is known as a nested interface. The nested
interfaces are used to group related interfaces so that they can be easy to maintain. The nested interface must
be referred to by the outer interface or class. It can't be accessed directly.
interface interface_name{
...
interface nested_interface_name{
...
}
}
Example :
interface Showable{
void show();
interface Message{
void msg();
}
}
class TestNestedInterface1 implements Showable.Message{
public void msg(){System.out.println("Hello nested interface");}
interfaces could only have abstract methods. The implementation of these methods has to be provided in a
separate class. So, if a new method is to be added in an interface, then its implementation code has to be
provided in the class implementing the same interface. To overcome this issue, Java 8 has introduced the
concept of default methods which allow the interfaces to have methods with implementation without affecting
the classes that implement the interface.
EX :
// A simple program to Test Interface default
// methods in java
interface TestInterface
{
// abstract method
public void square(int a);
// default method
default void show()
{
System.out.println("Default Method Executed");
}
}
// Static method
static int multiply(int a, int b) {
return a * b;
}
}
Functional Interfaces :
A functional interface in Java is an interface that contains only one abstract method. Functional interfaces can
have multiple default or static methods, but only one abstract method.
EX:
@FunctionalInterface
interface Square {
int calculate(int x);
}
class Geeks {
public static void main(String args[]) {
int a = 5;
// parameter passed and return type must be same as defined in the prototype
int ans = s.calculate(a);
System.out.println(ans);
}
}
Annotations :
Annotations are used to represent the syntactic metadata related to the class, interface, methods or fields used in
the source code and some additional information which is used by java interpreter and the JVM.
An "annotation interface" refers to a special type of interface declared using the @interface keyword, which is
used to define custom annotations.
// Main class
class GFG {
return 0;
}
}