Welcome To JAVA Programming





Introduction to JAVA Programming

JAVA was developed by James Gosling at Sun Microsystems Inc in the year 1991, later acquired by Oracle Corporation. It is a simple programming language. Java makes writing, compiling, and debugging programming easy. It helps to create reusable code and modular programs.

Java is a class-based, object-oriented programming language and is designed to have as few implementation dependencies as possible. A general-purpose programming language made for developers to write once run anywhere that is compiled Java code can run on all platforms that support Java.


History of java

Java’s history is very interesting. It is a programming language created in 1991. James Gosling, Mike Sheridan, and Patrick Naughton, a team of Sun engineers known as the Green team initiated the Java language in 1991. Sun Microsystems released its first public implementation in 1996 as Java 1.0. It


Some Java Termologies

1.  Java Virtual Machine(JVM):  This is generally referred to as JVM. There are three execution phases of a program. They are written, compile and run the program.

  • Writing a program is done by a java programmer like you and me.
  • The compilation is done by the JAVAC compiler which is a primary Java compiler included in the Java development kit (JDK). It takes Java program as input and generates bytecode as output.
  • In the Running phase of a program, JVM executes the bytecode generated by the compiler.

2. Bytecode in the Development process:  As discussed, the Javac compiler of JDK compiles the java source code into bytecode so that it can be executed by JVM. It is saved as .class file by the compiler. To view the bytecode, a disassembler like javap can be used.

3. Java Development Kit(JDK): While we were using the term JDK, when we learn about bytecode and JVM . So, as the name suggests, it is a complete Java development kit that includes everything including compiler, Java Runtime Environment (JRE), java debuggers, java docs, etc. For the program to execute in java, we need to install JDK on our computer in order to create, compile and run the java program.


4. Java Runtime Environment (JRE): JDK includes JRE. JRE installation on our computers allows the java program to run, however, we cannot compile it. JRE includes a browser, JVM, applet supports, and plugins. For running the java program, a computer needs JRE.

5. Garbage Collector: In Java, programmers can’t delete the objects. To delete or recollect that memory JVM has a program called Garbage Collector. Garbage Collectors can recollect the of objects that are not referenced. So Java makes the life of a programmer easy by handling memory management. However, programmers should be careful about their code whether they are using objects that have been used for a long time. Because Garbage cannot recover the memory of objects being referenced.


First JAVA Program

A "Hello, World!" is a simple program that outputs Hello, World! on the screen. Since it's a very simple program, it's often used to introduce a new programming language to a newbie.

class HelloWorld {
    public static void main(String[] args) {
        System.out.println("Hello, World!");
    }
}

How to java programs works

In Java, any line starting with // is a comment. Comments are intended for users reading the code to understand the intent and functionality of the program. It is completely ignored by the Java compiler (an application that translates Java program to Java bytecode that computer can execute). To learn more, visit Java comments.

In Java, every application begins with a class definition. In the program, HelloWorld is the name of the class, and the class definition is:

class HelloWorld {
... .. ...
}

For now, just remember that every Java application has a class definition, and the name of the class should match the filename in Java.

This is the main method. Every application in Java must contain the main method. The Java compiler starts executing the code from the main method.

How does it work? Good question. However, we will not discuss it in this article. After all, it's a basic program to introduce Java programming language to a newbie. We will learn the meaning of public, static, void, and how methods work? in later chapters.

For now, just remember that the main function is the entry point of your Java application, and it's mandatory in a Java program. The signature of the main method in Java is:


public static void main(String[] args) {
... .. ...
}

The code above is a print statement. It prints the text Hello, World! to standard output (your screen). The text inside the quotation marks is called String in Java.

Things to take away in java programming world

  • Every valid Java Application must have a class definition (that matches the filename).
  • The main method must be inside the class definition.
  • The compiler executes the codes starting from the main function.
public class HelloWorld {
    public static void main(String[] args) {
        // Write your code here
    }
}


Comments in Java Programming

Comments can be used to explain Java code, and to make it more readable. It can also be used to prevent execution when testing alternative code.




Single-line Comments

Single-line comments start with two forward slashes (//). Any text between // and the end of the line is ignored by Java (will not be executed).

// This is comment



Multi-line Comments in Java Programming

Multi-line comments start with /* and ends with */. Any text between /* and */ will be ignored by Java.

/* this
is
a
Multi-line
comment */



Variables in Java Programming

Variables are containers for storing data values.

Types of variables in Java Programming

  • String - stores text, such as "Hello". String values are surrounded by double quotes
  • int - stores integers (whole numbers), without decimals, such as 123 or -123
  • float - stores floating point numbers, with decimals, such as 19.99 or -19.99
  • char - stores single characters, such as 'a' or 'B'. Char values are surrounded by single quotes
  • boolean - stores values with two states: true or false



String var1 = "Codolearn"
int var2 = 50
float var3 = 39.4f
double var4 = 45.54d
boolean var5 = True



Data Types

Data types are divided into two groups:

  • Primitive data types - includes byte, short, int, long, float, double, boolean and char
  • Non-primitive data types - such as String, Arrays and Classes (you will learn more about these in a later chapter)
int myNum = 5;
float myFloatNum = 5.99f;
char myLetter = 'D';
boolean myBool = true;
String myText = "Hello";     



Primitive Data Types

In Java, the primitive data types are the predefined data types of Java. They specify the size and type of any standard values. Java has 8 primitive data types namely byte, short, int, long, float, double, char and boolean. When a primitive data type is stored, it is the stack that the values will be assigned. When a variable is copied then another copy of the variable is created and changes made to the copied variable will not reflect changes in the original variable. Here is a Java program to demonstrate all the primitive data types in Java.


Numbers

Integer types stores whole numbers, positive or negative (such as 123 or -456), without decimals. Valid types are byte, short, int and long. Which type you should use, depends on the numeric value. Floating point types represents numbers with a fractional part, containing one or more decimals. There are two types: float and double.


Integer Types

Byte
The byte data type can store whole numbers from -128 to 127. This can be used instead of int or other integer types to save memory when you are certain that the value will be within -128 and 127:
byte myNum = 100;
System.out.println(myNum);

Short

The short data type can store whole numbers from -32768 to 32767:

short myNum = 5000;
System.out.println(myNum);

Int

The int data type can store whole numbers from -2147483648 to 2147483647. In general, and in our tutorial, the int data type is the preferred data type when we create variables with a numeric value.

int myNum = 100000;
System.out.println(myNum);

Long

The long data type can store whole numbers from -9223372036854775808 to 9223372036854775807. This is used when int is not large enough to store the value. Note that you should end the value with an "L":

long myNum = 15000000000L;
System.out.println(myNum);



Operators in Java Programming

Operators are used to perform operations on variables and values.

int x = 390 + 50;

Although the + operator is often used to add together two values, like in the example above, it can also be used to add together a variable and a value, or a variable and another variable:

int sum1 = 100 + 50;
int sum2 = sum1 + 250;
int sum3 = sum2 + sum2;     



Types of operators in Java Programming
  • Arithmetic operators
  • Assignment operators
  • Comparison operators
  • Logical operators
  • Bitwise operators

Arithmetic Operators

Operator Name Description Example
+ Addition Adds together two values x + y
- Subtraction Subtracts one value from another x - y
* Multiplication Multiplies two values x * y
/ Division Divides one value by another x / y
% Modulus Returns the division remainder x % y
++ Increment Increases the value of a variable by 1 ++x
-- Decrement Decreases the value of a variable by 1 --x

Java Assignment Operators

Operator Example Same As
= x = 5 x = 5
+= x += 3 x = x + 3
-= x -= 3 x = x - 3
*= x *= 3 x = x * 3
/= x /= 3 x = x / 3
%= x %= 3 x = x % 3
&= x &= 3 x = x & 3
|= x |= 3 x = x | 3
^= x ^= 3 x = x ^ 3
>>= x >>= 3 x = x >> 3
<<= x <<= 3 x = x << 3

Java Logical Operators

Operator Name Description Example
&&  Logical and Returns true if both statements are true x < 5 &&  x < 10
||  Logical or Returns true if one of the statements is true x < 5 || x < 4
! Logical not Reverse the result, returns false if the result is true !(x < 5 && x < 10)


Java Strings

Strings are used for storing text. A String variable contains a collection of characters surrounded by double quotes:

String greeting = "Hello Good Evening";


String Lenght

A String in Java is actually an object, which contain methods that can perform certain operations on strings. For example, the length of a string can be found with the length() method:

String txt = "codolearn";
System.out.println("The length of the txt string is: " + txt.length());

More String Methods

There are many string methods available, for example toUpperCase() and toLowerCase():

String txt = "Hello World";
System.out.println(txt.toUpperCase());   // Outputs "HELLO WORLD"
System.out.println(txt.toLowerCase());   // Outputs "hello world"


Java Math

The Java Math class has many methods that allows you to perform mathematical tasks on numbers.

math.max() function

The Math.max(x,y) method can be used to find the highest value of x and y:

Math.max(5, 10);

math.min() function

The Math.min(x,y) method can be used to find the lowest value of x and y:

Math.min(5, 10);

math.sqrt() function

The Math.sqrt(x) method returns the square root of x:

Math.sqrt(64);

math.abs() function

The Math.abs(x) method returns the absolute (positive) value of x:

Math.abs(-4.7);

Random number
Math.random() returns a random number between 0.0 (inclusive), and 1.0 (exclusive):
Math.random();



Java Booleans

In programming booleans are used to check the statement is True or False


Java Boolean values

A boolean type is declared with the boolean keyword and can only take the values true or false:

boolean isJavaFun = true;
boolean isFishTasty = false;
System.out.println(isJavaFun);
System.out.println(isFishTasty);   

Boolean Expression
A Boolean expression is a Java expression that returns a Boolean value: true or false. You can use a comparison operator, such as the greater than (>) operator to find out if an expression (or a variable) is true:
int x = 10;
int y = 9;
System.out.println(x > y); 



Java If..else

Java supports the usual logical conditions from mathematics:
  • Less than: a < b
  • Less than or equal to: a <= b
  • Greater than: a > b
  • Greater than or equal to: a >= b
  • Equal to a == b
  • Not Equal to: a != b

  • Use if to specify a block of code to be executed, if a specified condition is true
  • Use else to specify a block of code to be executed, if the same condition is false
  • Use else if to specify a new condition to test, if the first condition is false
  • Use switch to specify many alternative blocks of code to be executed

If Statement

Use the if statement to specify a block of Java code to be executed if a condition is true.
if (condition) {
  // code goes here
}

In the example below, we test two values to find out if 20 is greater than 18. If the condition is true, print some text:
if (20 > 18) {
  System.out.println("20 is greater than 18");
}

The Else Statement

Use the else statement to specify a block of code to be executed if the condition is false.
if (condition) {
  // code goes here
} else {
  // code goes here
}

The else if Statement

Use the else if statement to specify a new condition if the first condition is false.
int time = 22;
if (time < 10) {
  System.out.println("Good morning.");
} else if (time < 20) {
  System.out.println("Good day.");
} else {
  System.out.println("Good evening.");
}
// Outputs "Good evening."

Java Switch Statements

Use the switch statement to select one of many code blocks to be executed.
switch(expression) {
  case x:
    // code block
    break;
  case y:
    // code block
    break;
  default:
    // code block
}

  • The switch expression is evaluated once.
  • The value of the expression is compared with the values of each case.
  • If there is a match, the associated block of code is executed.
  • The break and default keywords are optional, and will be described later in this chapter


example

int day = 4;
switch (day) {
  case 1:
    System.out.println("Monday");
    break;
  case 2:
    System.out.println("Tuesday");
    break;
  case 3:
    System.out.println("Wednesday");
    break;
  case 4:
    System.out.println("Thursday");
    break;
  case 5:
    System.out.println("Friday");
    break;
  case 6:
    System.out.println("Saturday");
    break;
  case 7:
    System.out.println("Sunday");
    break;
}


The break Keyword

When Java reaches a break keyword, it breaks out of the switch block. This will stop the execution of more code and case testing inside the block. When a match is found, and the job is done, it's time for a break. There is no need for more testing.

The default Keyword

The default keyword specifies some code to run if there is no case match:

int day = 4;
switch (day) {
  case 6:
    System.out.println("Today is Saturday");
    break;
  case 7:
    System.out.println("Today is Sunday");
    break;
  default:
    System.out.println("Looking forward to the Weekend");
}



While Loop in Java Programming

Loops

Loops can execute a block of code as long as a specified condition is reached. Loops are handy because they save time, reduce errors, and they make code more readable.


What is while loop in java ?

The while loop loops through a block of code as long as a specified condition is true:

while (condition) {
  // block of code
}

Example of while loop
int i = 0;
    while (i < 5) {
    System.out.println(i);
    i++;
}


The Do/While Loop

The do/while loop is a variant of the while loop. This loop will execute the code block once, before checking if the condition is true, then it will repeat the loop as long as the condition is true.


syntax:

do {
  // code block
}
while (condition);

The example below uses a do/while loop. The loop will always be executed at least once, even if the condition is false, because the code block is executed before the condition is tested:

int i = 0;
do {
  System.out.println(i);
  i++;
}
while (i < 5);



Java For Loop

When you know exactly how many times you want to loop through a block of code, use the for loop instead of a while loop:

for (statement 1; statement 2; statement 3) {
  // code block
}

Statement 1 is executed (one time) before the execution of the code block. Statement 2 defines the condition for executing the code block. Statement 3 is executed (every time) after the code block has been executed.

for (int i = 0; i < 5; i++) {
  System.out.println(i);
}

code exaplanation

Statement 1 sets a variable before the loop starts (int i = 0). Statement 2 defines the condition for the loop to run (i must be less than 5). If the condition is true, the loop will start over again, if it is false, the loop will end. Statement 3 increases a value (i++) each time the code block in the loop has been executed.


example

for (int i = 0; i <= 10; i = i + 2) {
  System.out.println(i);
}


For-Each Loop

There is also a "for-each" loop, which is used exclusively to loop through elements in an array:
for (type variableName : arrayName) {
  // code block to be executed
}


example:

String[] cars = {"Lamborgini", "Audi", "Ferrari", "Buggati"};
for (String i : cars) {
  System.out.println(i);
}



Break and Continue in Java

You have already seen the break statement used in an earlier chapter of this tutorial. It was used to "jump out" of a switch statement. The break statement can also be used to jump out of a loop. This example stops the loop when i is equal to 4:

for (int i = 0; i < 10; i++) {
  if (i == 4) {
    break;
  }
  System.out.println(i);
}


Java Continue

The continue statement breaks one iteration (in the loop), if a specified condition occurs, and continues with the next iteration in the loop. This example skips the value of 4:

for (int i = 0; i < 10; i++) {
  if (i == 4) {
    continue;
  }
  System.out.println(i);
}


Break and Continue in While Loop

You can also use break and continue in while loops:

break

int i = 0;
while (i < 10) {
  System.out.println(i);
  i++;
  if (i == 4) {
    break;
  }
}

continue

int i = 0;
while (i < 10) {
  if (i == 4) {
    i++;
    continue;
  }
  System.out.println(i);
  i++;
}



Java Arrays

Arrays are used to store multiple values in a single variable, instead of declaring separate variables for each value. To declare an array, define the variable type with square brackets:

String[] cars;

We have now declared a variable that holds an array of strings. To insert values to it, we can use an array literal - place the values in a comma-separated list, inside curly braces:

String[] cars = {"Lamborgini, "Audi", "Farrari", "Buggati"};

Access the Elements of an Array

You access an array element by referring to the index number. This statement accesses the value of the first element in cars:

String[] cars = {"Lamborgini, "Audi", "Farrari", "Buggati"};
System.out.println(cars[0]);

Change an Array Element

To change the value of a specific element, refer to the index number:

String[] cars = {"Lamborgini, "Audi", "Farrari", "Buggati"};
cars[0] = "Opel";
System.out.println(cars[0]);



Array Length

To find out how many elements an array has, use the length property:

String[] cars = {"Lamborgini, "Audi", "Farrari", "Buggati"};
System.out.println(cars.length);



Loop Through an Array

You can loop through the array elements with the for loop, and use the length property to specify how many times the loop should run. The following example outputs all elements in the cars array:

String[] cars = {"Lamborgini, "Audi", "Farrari", "Buggati"};
for (int i = 0; i < cars.length; i++) {
  System.out.println(cars[i]);
}


Loop Through an Array with For-Each

There is also a "for-each" loop, which is used exclusively to loop through elements in arrays:

for (type variable : arrayname) {
  ...
}
The following example outputs all elements in the cars array, using a "for-each" loop:
String[] cars = {"Lamborgini, "Audi", "Farrari", "Buggati"};
for (String i : cars) {
  System.out.println(i);
}



The example above can be read like this: for each String element (called i - as in index) in cars, print out the value of i. If you compare the for loop and for-each loop, you will see that the for-each method is easier to write, it does not require a counter (using the length property), and it is more readable.




JAVA Methods

A method is a block of code which only runs when it is called. You can pass data, known as parameters, into a method. Methods are used to perform certain actions, and they are also known as functions. Why use methods? To reuse code: define the code once, and use it many times.

Create a Method

A method must be declared within a class. It is defined with the name of the method, followed by parentheses (). Java provides some pre-defined methods, such as System.out.println(), but you can also create your own methods to perform certain actions:

public class Main {
  static void myMethod() {
    // code to be executed
  }
}

Example Explained myMethod() is the name of the method static means that the method belongs to the Main class and not an object of the Main class. You will learn more about objects and how to access methods through objects later in this tutorial. void means that this method does not have a return value. You will learn more about return values later in this chapter


Call a Method

To call a method in Java, write the method's name followed by two parentheses () and a semicolon; In the following example, myMethod() is used to print a text (the action), when it is called:

public class Main {
  static void myMethod() {
    System.out.println("I just got executed!");
  }

  public static void main(String[] args) {
    myMethod();
  }
}
public class Main {
  static void myMethod() {
    System.out.println("I just got executed!");
  }

  public static void main(String[] args) {
    myMethod();
    myMethod();
    myMethod();
  }
}

Java Method Parameters

Parameters and Arguments

Information can be passed to methods as parameter. Parameters act as variables inside the method. Parameters are specified after the method name, inside the parentheses. You can add as many parameters as you want, just separate them with a comma. The following example has a method that takes a String called fname as parameter. When the method is called, we pass along a first name, which is used inside the method to print the full name:

public class Main {
  static void myMethod(String fname) {
    System.out.println(fname + " Refsnes");
  }

  public static void main(String[] args) {
    myMethod("Liam");
    myMethod("Jenny");
    myMethod("Anja");
  }
}
public class Main {
  static void myMethod(String fname, int age) {
    System.out.println(fname + " is " + age);
  }

  public static void main(String[] args) {
    myMethod("Liam", 5);
    myMethod("Jenny", 8);
    myMethod("Anja", 31);
  }
}

Return Values

The void keyword, used in the examples above, indicates that the method should not return a value. If you want the method to return a value, you can use a primitive data type (such as int, char, etc.) instead of void, and use the return keyword inside the method:

public class Main {
  static int myMethod(int x) {
    return 5 + x;
  }

  public static void main(String[] args) {
    System.out.println(myMethod(3));
  }
}
public class Main {
  static int myMethod(int x, int y) {
    return x + y;
  }

  public static void main(String[] args) {
    System.out.println(myMethod(5, 3));
  }
}

A Method with If...Else

public class Main {

  // Create a checkAge() method with an integer variable called age
  static void checkAge(int age) {

    // If age is less than 18, print "access denied"
    if (age < 18) {
      System.out.println("Access denied - You are not old enough!");

    // If age is greater than, or equal to, 18, print "access granted"
    } else {
      System.out.println("Access granted - You are old enough!");
    }

  }

  public static void main(String[] args) {
    checkAge(20); // Call the checkAge method and pass along an age of 20
  }
}



Method Overloading

With method overloading, multiple methods can have the same name with different parameters:

int myMethod(int x)
float myMethod(float x)
double myMethod(double x, double y)

Example:

static int plusMethodInt(int x, int y) {
  return x + y;
}

static double plusMethodDouble(double x, double y) {
  return x + y;
}

public static void main(String[] args) {
  int myNum1 = plusMethodInt(8, 5);
  double myNum2 = plusMethodDouble(4.3, 6.26);
  System.out.println("int: " + myNum1);
  System.out.println("double: " + myNum2);
}

Instead of defining two methods that should do the same thing, it is better to overload one. In the example below, we overload the plusMethod method to work for both int and double:

static int plusMethod(int x, int y) {
  return x + y;
}

static double plusMethod(double x, double y) {
  return x + y;
}

public static void main(String[] args) {
  int myNum1 = plusMethod(8, 5);
  double myNum2 = plusMethod(4.3, 6.26);
  System.out.println("int: " + myNum1);
  System.out.println("double: " + myNum2);
}static int plusMethod(int x, int y) {
  return x + y;
}

static double plusMethod(double x, double y) {
  return x + y;
}

public static void main(String[] args) {
  int myNum1 = plusMethod(8, 5);
  double myNum2 = plusMethod(4.3, 6.26);
  System.out.println("int: " + myNum1);
  System.out.println("double: " + myNum2);
}



Java Scope

In Java, variables are only accessible inside the region they are created. This is called scope.


Method Scope

Variables declared directly inside a method are available anywhere in the method following the line of code in which they were declared:

public class Main {
  public static void main(String[] args) {

    // Code here CANNOT use x

    int x = 100;

    // Code here can use x
    System.out.println(x);
  }
}


Block Scope

A block of code refers to all of the code between curly braces {}. Variables declared inside blocks of code are only accessible by the code between the curly braces, which follows the line in which the variable was declared:

public class Main {
  public static void main(String[] args) {

    // Code here CANNOT use x

    { // This is a block

      // Code here CANNOT use x

      int x = 100;

      // Code here CAN use x
      System.out.println(x);

   } // The block ends here

  // Code here CANNOT use x

  }
}


Java Recursion

Recursion is the technique of making a function call itself. This technique provides a way to break complicated problems down into simple problems which are easier to solve.

Recursion may be a bit difficult to understand. The best way to figure out how it works is to experiment with it.



Recursion

Adding two numbers together is easy to do, but adding a range of numbers is more complicated. In the following example, recursion is used to add a range of numbers together by breaking it down into the simple task of adding two numbers:

public class Main {
  public static void main(String[] args) {
    int result = sum(10);
    System.out.println(result);
  }
  public static int sum(int k) {
    if (k > 0) {
      return k + sum(k - 1);
    } else {
      return 0;
    }
  }
}


Halting Condition

Just as loops can run into the problem of infinite looping, recursive functions can run into the problem of infinite recursion. Infinite recursion is when the function never stops calling itself. Every recursive function should have a halting condition, which is the condition where the function stops calling itself. In the previous example, the halting condition is when the parameter k becomes 0. It is helpful to see a variety of different examples to better understand the concept. In this example, the function adds a range of numbers between a start and an end. The halting condition for this recursive function is when end is not greater than start:

public class Main {
  public static void main(String[] args) {
    int result = sum(5, 10);
    System.out.println(result);
  }
  public static int sum(int start, int end) {
    if (end > start) {
      return end + sum(start, end - 1);
    } else {
      return end;
    }
  }
}




OOPS in java programming


OOP stands for Object-Oriented Programming.

Procedural programming is about writing procedures or methods that perform operations on the data, while object-oriented programming is about creating objects that contain both data and methods.

  • OOP is faster and easier to execute
  • OOP provides a clear structure for the programs
  • OOP helps to keep the Java code DRY "Don't Repeat Yourself", and makes the code easier to maintain, modify and debug
  • OOP makes it possible to create full reusable applications with less code and shorter development time



What are classes and objects



Class

A class is a user defined blueprint or prototype from which objects are created. It represents the set of properties or methods that are common to all objects of one type.

  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.
  6. Body: The class body surrounded by braces, { }.


Constructors are used for initializing new objects. Fields are variables that provides the state of the class and its objects, and methods are used to implement the behavior of the class and its objects.




Object

It is a basic unit of Object-Oriented Programming and represents the real life entities. A typical Java program creates many objects, which as you know, interact by invoking methods. An object consists of :

  1. State: It is represented by attributes of an object. It also reflects the properties of an object.
  2. Behavior: It is represented by methods of an object. It also reflects the response of an object with other objects.
  3. Identity: It gives a unique name to an object and enables one object to interact with other objects.


Objects correspond to things found in the real world. For example, a graphics program may have objects such as “circle”, “square”, “menu”. An online shopping system might have objects such as “shopping cart”, “customer”, and “product”.


Declaring Objects (Also called instantiating a class)

When an object of a class is created, the class is said to be instantiated. All the instances share the attributes and the behavior of the class. But the values of those attributes, i.e. the state are unique for each object. A single class may have any number of instances.


As we declare variables like (type name;). This notifies the compiler that we will use name to refer to data whose type is type. With a primitive variable, this declaration also reserves the proper amount of memory for the variable. So for reference variable, type must be strictly a concrete class name. In general, we can’t create objects of an abstract class or an interface.

Dog tuffy;


Initializing an object

The new operator instantiates a class by allocating memory for a new object and returning a reference to that memory. The new operator also invokes the class constructor.

public class Dog
{
	String name;
	String breed;
	int age;
	String color;

	public Dog(String name, String breed,
				int age, String color)
	{
		this.name = name;
		this.breed = breed;
		this.age = age;
		this.color = color;
	}

	public String getName()
	{
		return name;
	}
	public String getBreed()
	{
		return breed;
	}
	public int getAge()
	{
		return age;
	}
	public String getColor()
	{
		return color;
	}

	@Override
	public String toString()
	{
		return("Hi my name is "+ this.getName()+
			".\nMy breed,age and color are " +
			this.getBreed()+"," + this.getAge()+
			","+ this.getColor());
	}

	public static void main(String[] args)
	{
		Dog tuffy = new Dog("tuffy","papillon", 5, "white");
		System.out.println(tuffy.toString());
	}
}



Java and class attributes

In the previous chapter, we used the term "variable" for x in the example (as shown below). It is actually an attribute of the class. Or you could say that class attributes are variables within a class:

public class Main {
  int x = 5;
  int y = 3;
}

Accessing Attributes

You can access attributes by creating an object of the class, and by using the dot syntax (.): The following example will create an object of the Main class, with the name myObj. We use the x attribute on the object to print its value:
public class Main {
  int x = 5;

  public static void main(String[] args) {
    Main myObj = new Main();
    System.out.println(myObj.x);
  }
}


Modify Attributes

public class Main {
  int x;

  public static void main(String[] args) {
    Main myObj = new Main();
    myObj.x = 40;
    System.out.println(myObj.x);
  }
}
public class Main {
  int x = 10;

  public static void main(String[] args) {
    Main myObj = new Main();
    myObj.x = 25; // x is now 25
    System.out.println(myObj.x);
  }
}


Multiple Objects

If you create multiple objects of one class, you can change the attribute values in one object, without affecting the attribute values in the other:

public class Main {
  int x = 5;

  public static void main(String[] args) {
    Main myObj1 = new Main();  // Object 1
    Main myObj2 = new Main();  // Object 2
    myObj2.x = 25;
    System.out.println(myObj1.x);  // Outputs 5
    System.out.println(myObj2.x);  // Outputs 25
  }
}

Multiple Attributes

public class Main {
  String fname = "John";
  String lname = "Doe";
  int age = 24;

  public static void main(String[] args) {
    Main myObj = new Main();
    System.out.println("Name: " + myObj.fname + " " + myObj.lname);
    System.out.println("Age: " + myObj.age);
  }
}



Class methods in java

You learned from the Java Methods chapter that methods are declared within a class, and that they are used to perform certain actions:

public class Main {
  static void myMethod() {
    System.out.println("Hello World!");
  }
}

myMethod() prints a text (the action), when it is called. To call a method, write the method's name followed by two parentheses () and a semicolon; Example

public class Main {
  static void myMethod() {
    System.out.println("Hello World!");
  }

  public static void main(String[] args) {
    myMethod();
  }
}


Static vs. Non-Static

You will often see Java programs that have either static or public attributes and methods.

In the example above, we created a static method, which means that it can be accessed without creating an object of the class, unlike public, which can only be accessed by objects:

public class Main {
  // Static method
  static void myStaticMethod() {
    System.out.println("Static methods can be called without creating objects");
  }

  // Public method
  public void myPublicMethod() {
    System.out.println("Public methods must be called by creating objects");
  }

  // Main method
  public static void main(String[] args) {
    myStaticMethod(); // Call the static method
    // myPublicMethod(); This would compile an error

    Main myObj = new Main(); // Create an object of Main
    myObj.myPublicMethod(); // Call the public method on the object
  }
}


Access Methods With an Object

// Create a Main class
public class Main {

  // Create a fullThrottle() method
  public void fullThrottle() {
    System.out.println("The car is going as fast as it can!");
  }

  // Create a speed() method and add a parameter
  public void speed(int maxSpeed) {
    System.out.println("Max speed is: " + maxSpeed);
  }

  // Inside main, call the methods on the myCar object
  public static void main(String[] args) {
    Main myCar = new Main();   // Create a myCar object
    myCar.fullThrottle();      // Call the fullThrottle() method
    myCar.speed(200);          // Call the speed() method
  }
}



Java Constructors

A constructor in Java is a special method that is used to initialize objects. The constructor is called when an object of a class is created. It can be used to set initial values for object attributes:

public class Main {
  int x;  // Create a class attribute

  // Create a class constructor for the Main class
  public Main() {
    x = 5;  // Set the initial value for the class attribute x
  }

  public static void main(String[] args) {
    Main myObj = new Main(); // Create an object of class Main (This will call the constructor)
    System.out.println(myObj.x); // Print the value of x
  }
}


Constructor Parameter

Constructors can also take parameters, which is used to initialize attributes. The following example adds an int y parameter to the constructor. Inside the constructor we set x to y (x=y). When we call the constructor, we pass a parameter to the constructor (5), which will set the value of x to 5:

public class Main {
  int x;

  public Main(int y) {
    x = y;
  }

  public static void main(String[] args) {
    Main myObj = new Main(5);
    System.out.println(myObj.x);
  }
}
public class Main {
  int modelYear;
  String modelName;

  public Main(int year, String name) {
    modelYear = year;
    modelName = name;
  }

  public static void main(String[] args) {
    Main myCar = new Main(1969, "Mustang");
    System.out.println(myCar.modelYear + " " + myCar.modelName);
  }
}



Java Modifiers

By now, you are quite familiar with the public keyword that appears in almost all of our examples:

public class Main

The public keyword is an access modifier, meaning that it is used to set the access level for classes, attributes, methods and constructors.

Access Modifiers - controls the access level Non-Access Modifiers - do not control access level, but provides other functionality

Access Modifiers

Modifier Description Try it
public The class is accessible by any other class
default The class is only accessible by classes in the same package. This is used when you don't specify a modifier. You will learn more about packages in the Packages chapter


Non-Access Modifiers

Modifier Description Try it
final The class cannot be inherited by other classes (You will learn more about inheritance in the Inheritance chapter)
abstract The class cannot be used to create objects (To access an abstract class, it must be inherited from another class. You will learn more about inheritance and abstraction in the Inheritance and Abstraction chapters)

public class Main {
  final int x = 10;
  final double PI = 3.14;

  public static void main(String[] args) {
    Main myObj = new Main();
    myObj.x = 50; // will generate an error: cannot assign a value to a final variable
    myObj.PI = 25; // will generate an error: cannot assign a value to a final variable
    System.out.println(myObj.x);
  }
}
public class Main {
  // Static method
  static void myStaticMethod() {
    System.out.println("Static methods can be called without creating objects");
  }

  // Public method
  public void myPublicMethod() {
    System.out.println("Public methods must be called by creating objects");
  }

  // Main method
  public static void main(String[ ] args) {
    myStaticMethod(); // Call the static method
    // myPublicMethod(); This would output an error

    Main myObj = new Main(); // Create an object of Main
    myObj.myPublicMethod(); // Call the public method
  }
}
// Code from filename: Main.java
// abstract class
abstract class Main {
  public String fname = "John";
  public int age = 24;
  public abstract void study(); // abstract method
}

// Subclass (inherit from Main)
class Student extends Main {
  public int graduationYear = 2018;
  public void study() { // the body of the abstract method is provided here
    System.out.println("Studying all day long");
  }
}
// End code from filename: Main.java

// Code from filename: Second.java
class Second {
  public static void main(String[] args) {
    // create an object of the Student class (which inherits attributes and methods from Main)
    Student myObj = new Student();

    System.out.println("Name: " + myObj.fname);
    System.out.println("Age: " + myObj.age);
    System.out.println("Graduation Year: " + myObj.graduationYear);
    myObj.study(); // call abstract method
  }
}



Java Encapsulation

The meaning of Encapsulation, is to make sure that "sensitive" data is hidden from users. To achieve this, you must:

  • declare class variables/attributes as private
  • provide public get and set methods to access and update the value of a private variable

Set and get

You learned from the previous chapter that private variables can only be accessed within the same class (an outside class has no access to it). However, it is possible to access them if we provide public get and set methods. The get method returns the variable value, and the set method sets the value. Syntax for both is that they start with either get or set, followed by the name of the variable, with the first letter in upper case:

public class Person {
  private String name; // private = restricted access

  // Getter
  public String getName() {
    return name;
  }

  // Setter
  public void setName(String newName) {
    this.name = newName;
  }
}

Instead, we use the getName() and setName() methods to access and update the variable:

public class Main {
  public static void main(String[] args) {
    Person myObj = new Person();
    myObj.setName("John"); // Set the value of the name variable to "John"
    System.out.println(myObj.getName());
  }
}


Why Encapsulation?

  • Better control of class attributes and methods
  • Class attributes can be made read-only (if you only use the get method), or write-only (if you only use the set method)
  • Flexible: the programmer can change one part of the code without affecting other parts
  • Increased security of data



Java Packages

Java Packages & API

A package in Java is used to group related classes. Think of it as a folder in a file directory. We use packages to avoid name conflicts, and to write a better maintainable code. Packages are divided into two categories:

  • Built-in Packages (packages from the Java API)
  • User-defined Packages (create your own packages)


Built-in Packages

The Java API is a library of prewritten classes, that are free to use, included in the Java Development Environment. The library contains components for managing input, database programming, and much much more. The complete list can be found at Oracles website: https://docs.oracle.com/javase/8/docs/api/. The library is divided into packages and classes. Meaning you can either import a single class (along with its methods and attributes), or a whole package that contain all the classes that belong to the specified package. To use a class or a package from the library, you need to use the import keyword:
import package.name.Class;   // Import a single class
import package.name.*;   // Import the whole package

Import a Class

If you find a class you want to use, for example, the Scanner class, which is used to get user input, write the following code:

import java.util.Scanner;

In the example above, java.util is a package, while Scanner is a class of the java.util package. To use the Scanner class, create an object of the class and use any of the available methods found in the Scanner class documentation. In our example, we will use the nextLine() method, which is used to read a complete line:

import java.util.Scanner;

class MyClass {
  public static void main(String[] args) {
    Scanner myObj = new Scanner(System.in);
    System.out.println("Enter username");

    String userName = myObj.nextLine();
    System.out.println("Username is: " + userName);
  }
}


Import a Package

There are many packages to choose from. In the previous example, we used the Scanner class from the java.util package. This package also contains date and time facilities, random-number generator and other utility classes. To import a whole package, end the sentence with an asterisk sign (*). The following example will import ALL the classes in the java.util package:

import java.util.*;



Java Inheritence

Inheritance is an important pillar of OOP(Object-Oriented Programming). It is the mechanism in java by which one class is allowed to inherit the features(fields and methods) of another class.

Some important terminoly in inheritence

  • Super Class: The class whose features are inherited is known as superclass(or a base class or a parent class).
  • Sub Class: The class that inherits the other class is known as a subclass(or a derived class, extended class, or child class). The subclass can add its own fields and methods in addition to the superclass fields and methods.
  • Reusability: Inheritance supports the concept of “reusability”, i.e. when we want to create a new class and there is already a class that includes some of the code that we want, we can derive our new class from the existing class. By doing this, we are reusing the fields and methods of the existing class.


Syntax:

class derived-class extends base-class
{
   // code goes here
}  

Example: In the below example of inheritance, class Bicycle is a base class, class MountainBike is a derived class that extends Bicycle class and class Test is a driver class to run program.



class Bicycle {
	public int gear;
	public int speed;
	public Bicycle(int gear, int speed)
	{
		this.gear = gear;
		this.speed = speed;
	}

	public void applyBrake(int decrement)
	{
		speed -= decrement;
	}

	public void speedUp(int increment)
	{
		speed += increment;
	}

	public String toString()
	{
		return ("No of gears are " + gear + "\n"
				+ "speed of bicycle is " + speed);
	}
}

// derived class
class MountainBike extends Bicycle {
	public int seatHeight;
	public MountainBike(int gear, int speed,
						int startHeight)
	{
		super(gear, speed);
		seatHeight = startHeight;
	}

	public void setHeight(int newValue)
	{
		seatHeight = newValue;
	}

	@Override public String toString()
	{
		return (super.toString() + "\nseat height is "
				+ seatHeight);
	}
}

public class Test {
	public static void main(String args[])
	{

		MountainBike mb = new MountainBike(3, 100, 25);
		System.out.println(mb.toString());
	}
}

In the above program, when an object of MountainBike class is created, a copy of all methods and fields of the superclass acquire memory in this object. That is why by using the object of the subclass we can also access the members of a superclass.



Types of Inheritance in Java

1. Single Inheritance: In single inheritance, subclasses inherit the features of one superclass. In the image below, class A serves as a base class for the derived class B.


2. Multilevel Inheritance: In Multilevel Inheritance, a derived class will be inheriting a base class and as well as the derived class also act as the base class to other class. In the below image, class A serves as a base class for the derived class B, which in turn serves as a base class for the derived class C.


3. Hierarchical Inheritance: In Hierarchical Inheritance, one class serves as a superclass (base class) for more than one subclass. In the below image, class A serves as a base class for the derived class B, C and D.


3. Hierarchical Inheritance: In Hierarchical Inheritance, one class serves as a superclass (base class) for more than one subclass. In the below image, class A serves as a base class for the derived class B, C and D.


4. Multiple Inheritance (Through Interfaces): In Multiple inheritances, one class can have more than one superclass and inherit features from all parent classes. Please note that Java does not support multiple inheritances with classes. In java, we can achieve multiple inheritances only through Interfaces. In the image below, Class C is derived from interface A and B.


5. Hybrid Inheritance(Through Interfaces): It is a mix of two or more of the above types of inheritance. Since java doesn’t support multiple inheritances with classes, hybrid inheritance is also not possible with classes. In java, we can achieve hybrid inheritance only through Interfaces.



Important facts about inheritance in Java

  • Default superclass: Except Object class, which has no superclass, every class has one and only one direct superclass (single inheritance). In the absence of any other explicit superclass, every class is implicitly a subclass of the Object class.
  • Superclass can only be one: A superclass can have any number of subclasses. But a subclass can have only one superclass. This is because Java does not support multiple inheritances with classes. Although with interfaces, multiple inheritances are supported by java.
  • Inheriting Constructors: A subclass inherits all the members (fields, methods, and nested classes) from its superclass. Constructors are not members, so they are not inherited by subclasses, but the constructor of the superclass can be invoked from the subclass.
  • Private member inheritance: A subclass does not inherit the private members of its parent class. However, if the superclass has public or protected methods(like getters and setters) for accessing its private fields, these can also be used by the subclass.



Java Polymorphism

The word polymorphism means having many forms. In simple words, we can define polymorphism as the ability of a message to be displayed in more than one form.
Real life example of polymorphism: A person at the same time can have different characteristic. Like a man at the same time is a father, a husband, an employee. So the same person posses different behavior in different situations. This is called polymorphism.
Polymorphism is considered one of the important features of Object-Oriented Programming. Polymorphism allows us to perform a single action in different ways. In other words, polymorphism allows you to define one interface and have multiple implementations. The word “poly” means many and “morphs” means forms, So it means many forms.



In Java polymorphism is mainly divided into two types:

  • Compile time Polymorphism
  • Runtime Polymorphism


1. Compile-time polymorphism: It is also known as static polymorphism. This type of polymorphism is achieved by function overloading or operator overloading. But Java doesn’t support the Operator Overloading.


Method Overloading: When there are multiple functions with same name but different parameters then these functions are said to be overloaded. Functions can be overloaded by change in number of arguments or/and change in type of arguments.

class MultiplyFun {

	static int Multiply(int a, int b)
	{
		return a * b;
	}

	static double Multiply(double a, double b)
	{
		return a * b;
	}
}

class Main {
	public static void main(String[] args)
	{

		System.out.println(MultiplyFun.Multiply(2, 4));

		System.out.println(MultiplyFun.Multiply(5.5, 6.3));
	}
}

Example 2: By using different numbers of arguments

class MultiplyFun {

	static int Multiply(int a, int b)
	{
		return a * b;
	}

	static int Multiply(int a, int b, int c)
	{
		return a * b * c;
	}
}

class Main {
	public static void main(String[] args)
	{
		System.out.println(MultiplyFun.Multiply(2, 4));

		System.out.println(MultiplyFun.Multiply(2, 7, 3));
	}
}



2. Runtime polymorphism: It is also known as Dynamic Method Dispatch. It is a process in which a function call to the overridden method is resolved at Runtime. This type of polymorphism is achieved by Method Overriding.

Method overriding, on the other hand, occurs when a derived class has a definition for one of the member functions of the base class. That base function is said to be overridden.

class Parent {

	void Print()
	{
		System.out.println("parent class");
	}
}

class subclass1 extends Parent {

	void Print()
	{
		System.out.println("subclass1");
	}
}

class subclass2 extends Parent {

	void Print()
	{
		System.out.println("subclass2");
	}
}

class TestPolymorphism3 {
	public static void main(String[] args)
	{

		Parent a;

		a = new subclass1();
		a.Print();

		a = new subclass2();
		a.Print();
	}
}



Inner Classes in java

In Java, it is also possible to nest classes (a class within a class). The purpose of nested classes is to group classes that belong together, which makes your code more readable and maintainable.

To access the inner class, create an object of the outer class, and then create an object of the inner class:

class OuterClass {
  int x = 10;

  class InnerClass {
    int y = 5;
  }
}

public class Main {
  public static void main(String[] args) {
    OuterClass myOuter = new OuterClass();
    OuterClass.InnerClass myInner = myOuter.new InnerClass();
    System.out.println(myInner.y + myOuter.x);
  }
}


Private Inner Class

Unlike a "regular" class, an inner class can be private or protected. If you don't want outside objects to access the inner class, declare the class as private:

class OuterClass {
  int x = 10;

  private class InnerClass {
    int y = 5;
  }
}

public class Main {
  public static void main(String[] args) {
    OuterClass myOuter = new OuterClass();
    OuterClass.InnerClass myInner = myOuter.new InnerClass();
    System.out.println(myInner.y + myOuter.x);
  }
}


Static Inner Class

An inner class can also be static, which means that you can access it without creating an object of the outer class:

class OuterClass {
  int x = 10;

  static class InnerClass {
    int y = 5;
  }
}

public class Main {
  public static void main(String[] args) {
    OuterClass.InnerClass myInner = new OuterClass.InnerClass();
    System.out.println(myInner.y);
  }
}



Access Outer Class From Inner Class

One advantage of inner classes, is that they can access attributes and methods of the outer class:

class OuterClass {
  int x = 10;

  class InnerClass {
    public int myInnerMethod() {
      return x;
    }
  }
}

public class Main {
  public static void main(String[] args) {
    OuterClass myOuter = new OuterClass();
    OuterClass.InnerClass myInner = myOuter.new InnerClass();
    System.out.println(myInner.myInnerMethod());
  }
}



Java Abstraction

Data Abstraction is the property by virtue of which only the essential details are displayed to the user. The trivial or the non-essentials units are not displayed to the user. Ex: A car is viewed as a car rather than its individual components.

Data Abstraction may also be defined as the process of identifying only the required characteristics of an object ignoring the irrelevant details. The properties and behaviours of an object differentiate it from other objects of similar type and also help in classifying/grouping the objects.

Consider a real-life example of a man driving a car. The man only knows that pressing the accelerators will increase the speed of a car or applying brakes will stop the car, but he does not know about how on pressing the accelerator the speed is actually increasing, he does not know about the inner mechanism of the car or the implementation of the accelerator, brakes, etc in the car. This is what abstraction is.




Some method in Abstract classes
  1. An abstract class is a class that is declared with an abstract keyword.
  2. An abstract method is a method that is declared without implementation.
  3. An abstract class may or may not have all abstract methods. Some of them can be concrete methods
  4. A method defined abstract must always be redefined in the subclass, thus making overriding compulsory OR either make the subclass itself abstract.
  5. Any class that contains one or more abstract methods must also be declared with an abstract keyword.
  6. There can be no object of an abstract class. That is, an abstract class can not be directly instantiated with the new operator.
  7. An abstract class can have parameterized constructors and the default constructor is always present in an abstract class.



When to use abstract classes and abstract methods

There are situations in which we will want to define a superclass that declares the structure of a given abstraction without providing a complete implementation of every method. That is, sometimes we will want to create a superclass that only defines a generalization form that will be shared by all of its subclasses, leaving it to each subclass to fill in the details.

Consider a classic “shape” example, perhaps used in a computer-aided design system or game simulation. The base type is “shape” and each shape has a color, size, and so on. From this, specific types of shapes are derived(inherited)-circle, square, triangle, and so on — each of which may have additional characteristics and behaviors. For example, certain shapes can be flipped. Some behaviors may be different, such as when you want to calculate the area of a shape. The type hierarchy embodies both the similarities and differences between the shapes.

abstract class Shape {
	String color;

	abstract double area();
	public abstract String toString();

	public Shape(String color)
	{
		System.out.println("Shape constructor called");
		this.color = color;
	}

	public String getColor() { return color; }
}
class Circle extends Shape {
	double radius;

	public Circle(String color, double radius)
	{
		super(color);
		System.out.println("Circle constructor called");
		this.radius = radius;
	}

	@Override double area()
	{
		return Math.PI * Math.pow(radius, 2);
	}

	@Override public String toString()
	{
		return "Circle color is " + super.getColor()
			+ "and area is : " + area();
	}
}
class Rectangle extends Shape {

	double length;
	double width;

	public Rectangle(String color, double length,
					double width)
	{
		super(color);
		System.out.println("Rectangle constructor called");
		this.length = length;
		this.width = width;
	}

	@Override double area() { return length * width; }

	@Override public String toString()
	{
		return "Rectangle color is " + super.getColor()
			+ "and area is : " + area();
	}
}
public class Test {
	public static void main(String[] args)
	{
		Shape s1 = new Circle("Red", 2.2);
		Shape s2 = new Rectangle("Yellow", 2, 4);

		System.out.println(s1.toString());
		System.out.println(s2.toString());
	}
}



Interface in Java

Like a class, an interface can have methods and variables, but the methods declared in an interface are by default abstract (only method signature, no body).

  • Interfaces specify what a class must do and not how. It is the blueprint of the class.
  • An Interface is about capabilities like a Player may be an interface and any class implementing Player must be able to (or must implement) move(). So it specifies a set of methods that the class has to implement.
  • If a class implements an interface and does not provide method bodies for all functions specified in the interface, then the class must be declared abstract.
  • A Java library example is,Comparator Interface. If a class implements this interface, then it can be used to sort a collection.
interface  {

    // declare constant fields
    // declare methods that abstract
    // by default.
}

To declare an interface, use interface keyword. It is used to provide total abstraction. That means all the methods in an interface are declared with an empty body and are public and all fields are public, static and final by default. A class that implements an interface must implement all the methods declared in the interface. To implement interface use implements keyword.

It is used to achieve total abstraction.

Since java does not support multiple inheritance in case of class, but by using interface it can achieve multiple inheritance .

It is also used to achieve loose coupling. Interfaces are used to implement abstraction. So the question arises why use interfaces when we have abstract classes?

// A simple interface
interface Player
{
	final int id = 10;
	int move();
}


import java.io.*;
interface In1
{
	final int a = 10;
	void display();
}

class TestClass implements In1
{
	public void display()
	{
		System.out.println("Codolearn");
	}

	// Driver Code
	public static void main (String[] args)
	{
		TestClass t = new TestClass();
		t.display();
		System.out.println(a);
	}
}



Java Enums

An enum is a special "class" that represents a group of constants (unchangeable variables, like final variables).

To create an enum, use the enum keyword (instead of class or interface), and separate the constants with a comma. Note that they should be in uppercase letters:


enum Level {
  LOW,
  MEDIUM,
  HIGH
}


Enum inside a Class

You can also have an enum inside a class:

public class Main {
  enum Level {
    LOW,
    MEDIUM,
    HIGH
  }

  public static void main(String[] args) {
    Level myVar = Level.MEDIUM;
    System.out.println(myVar);
  }
}


Enum in a Switch Statement

Enums are often used in switch statements to check for corresponding values:

enum Level {
  LOW,
  MEDIUM,
  HIGH
}

public class Main {
  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;
    }
  }
}


Loop Through an Enum

The enum type has a values() method, which returns an array of all enum constants. This method is useful when you want to loop through the constants of an enum:

for (Level myVar : Level.values()) {
  System.out.println(myVar);
}



Difference between Enums and Classes

An enum can, just like a class, have attributes and methods. The only difference is that enum constants are public, static and final (unchangeable - cannot be overridden).

An enum cannot be used to create objects, and it cannot extend other classes (but it can implement interfaces).

Why And When To Use Enums?
Use enums when you have values that you know aren't going to change, like month days, days, colors, deck of cards, etc.




Java User Input

The Scanner class is used to get user input, and it is found in the java.util package.

To use the Scanner class, create an object of the class and use any of the available methods found in the Scanner class documentation. In our example, we will use the nextLine() method, which is used to read Strings:

import java.util.Scanner;

class Main {
  public static void main(String[] args) {
    Scanner myObj = new Scanner(System.in);
    System.out.println("Enter username");

    String userName = myObj.nextLine();
    System.out.println("Username is: " + userName);
  }
}



Types ofn input

In the example above, we used the nextLine() method, which is used to read Strings. To read other types, look at the table below:

Method Description
nextBoolean() Reads a boolean value from the user
nextByte() Reads a byte value from the user
nextDouble() Reads a double value from the user
nextFloat() Reads a float value from the user
nextInt() Reads a int value from the user
nextLine() Reads a String value from the user
nextLong() Reads a long value from the user
nextShort() Reads a short value from the user

import java.util.Scanner;

class Main {
  public static void main(String[] args) {
    Scanner myObj = new Scanner(System.in);

    System.out.println("Enter name, age and salary:");
    String name = myObj.nextLine();

    int age = myObj.nextInt();
    double salary = myObj.nextDouble();
    System.out.println("Name: " + name);
    System.out.println("Age: " + age);
    System.out.println("Salary: " + salary);
  }
}



Java Date and Time


Date

Java does not have a built-in Date class, but we can import the java.time package to work with the date and time API. The package includes many date and time classes. For example:

Class Description
LocalDate Represents a date (year, month, day (yyyy-MM-dd))
LocalTime Represents a time (hour, minute, second and nanoseconds (HH-mm-ss-ns))
LocalDateTime Represents both a date and a time (yyyy-MM-dd-HH-mm-ss-ns)
DateTimeFormatter Formatter for displaying and parsing date-time objects



How to Display Current Date

To display the current date, import the java.time.LocalDate class, and use its now() method:

import java.time.LocalDate;

public class Main {
  public static void main(String[] args) {
    LocalDate myObj = LocalDate.now();
    System.out.println(myObj);
  }
}



How to display current time

To display the current time (hour, minute, second, and nanoseconds), import the java.time.LocalTime class, and use its now() method:

import java.time.LocalTime;

public class Main {
  public static void main(String[] args) {
    LocalTime myObj = LocalTime.now();s
    System.out.println(myObj);
  }
}



Java ArrayList

The ArrayList class is a resizable array, which can be found in the java.util package.

The difference between a built-in array and an ArrayList in Java, is that the size of an array cannot be modified (if you want to add or remove elements to/from an array, you have to create a new one). While elements can be added and removed from an ArrayList whenever you want. The syntax is also slightly different:

import java.util.ArrayList;
ArrayList cars = new ArrayList(); t 


Add Items

The ArrayList class has many useful methods. For example, to add elements to the ArrayList, use the add() method:

import java.util.ArrayList;

public class Main {
  public static void main(String[] args) {
    ArrayList cars = new ArrayList();
    cars.add("Lamborgini);
    cars.add("Audi");
    cars.add("Farrari");
    cars.add("Buggati");
    System.out.println(cars);
  }
}



Access an Item

To access an element in the ArrayList, use the get() method and refer to the index number:

cars.get(0);



How to change item

To modify an element, use the set() method and refer to the index number:

cars.set(0, "Opel");



How to remove an item

To remove an element, use the remove() method and refer to the index number:

cars.remove(0);

To remove all the elements in the ArrayList, use the clear() method:

cars.clear();



Size of ArrayList

To find out how many elements an ArrayList have, use the size method:

cars.size();



Loop Through an ArrayList

Loop through the elements of an ArrayList with a for loop, and use the size() method to specify how many times the loop should run:

public class Main {
  public static void main(String[] args) {
    ArrayList cars = new ArrayList();
    cars.add("Lamborgini);
    cars.add("Audi");
    cars.add("Farrari");
    cars.add("Buggati");
    for (int i = 0; i < cars.size(); i++) {
      System.out.println(cars.get(i));
    }
  }
}

You can also loop through an ArrayList with the for-each loop:

public class Main {
  public static void main(String[] args) {
    ArrayList cars = new ArrayList();
    cars.add("Lamborgini");
    cars.add("Audi");
    cars.add("Farrari");
    cars.add("Buggati");
    for (String i : cars) {
      System.out.println(i);
    }
  }
}



Other Types:

Elements in an ArrayList are actually objects. In the examples above, we created elements (objects) of type "String". Remember that a String in Java is an object (not a primitive type). To use other types, such as int, you must specify an equivalent wrapper class: Integer. For other primitive types, use: Boolean for boolean, Character for char, Double for double, etc:


Example


import java.util.ArrayList;

public class Main {
  public static void main(String[] args) {
    ArrayList myNumbers = new ArrayList();
    myNumbers.add(10);
    myNumbers.add(15);
    myNumbers.add(20);
    myNumbers.add(25);
    for (int i : myNumbers) {
      System.out.println(i);
    }
  }
}



Sorts of an ArrayList

Another useful class in the java.util package is the Collections class, which include the sort() method for sorting lists alphabetically or numerically:

import java.util.ArrayList;
import java.util.Collections;  // Import the Collections class

public class Main {
  public static void main(String[] args) {
    ArrayList cars = new ArrayList();
    cars.add("Lamborgini");
    cars.add("Audi");
    cars.add("Farrari");
    cars.add("Buggati");
    Collections.sort(cars);  // Sort cars
    for (String i : cars) {
      System.out.println(i);
    }
  }
}


import java.util.ArrayList;
import java.util.Collections;  // Import the Collections class

public class Main {
  public static void main(String[] args) {
    ArrayList myNumbers = new ArrayList();
    myNumbers.add(33);
    myNumbers.add(15);
    myNumbers.add(20);
    myNumbers.add(34);
    myNumbers.add(8);
    myNumbers.add(12);

    Collections.sort(myNumbers);  // Sort myNumbers

    for (int i : myNumbers) {
      System.out.println(i);
    }
  }
}



Java LinkedList

Linked List is a part of the Collection framework present in java.util package. This class is an implementation of the LinkedList data structure which is a linear data structure where the elements are not stored in contiguous locations and every element is a separate object with a data part and address part. The elements are linked using pointers and addresses. Each element is known as a node. Due to the dynamicity and ease of insertions and deletions, they are preferred over the arrays. It also has few disadvantages like the nodes cannot be accessed directly instead we need to start from the head and follow through the link to reach to a node we wish to access.




ArrayList vs. LinkedList

The LinkedList class is a collection which can contain many objects of the same type, just like the ArrayList.
The LinkedList class has all of the same methods as the ArrayList class because they both implement the List interface. This means that you can add items, change items, remove items and clear the list in the same way.

However, while the ArrayList class and the LinkedList class can be used in the same way, they are built very differently.

How the ArrayList works The ArrayList class has a regular array inside it. When an element is added, it is placed into the array. If the array is not big enough, a new, larger array is created to replace the old one and the old one is removed.




How the LinkedList works

The LinkedList stores its items in "containers." The list has a link to the first container and each container has a link to the next container in the list. To add an element to the list, the element is placed into a new container and that container is linked to one of the other containers in the list.




LinkedList Methods

For many cases, the ArrayList is more efficient as it is common to need access to random items in the list, but the LinkedList provides several methods to do certain operations more efficiently:

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



Java HashMap

In the ArrayList chapter, you learned that Arrays store items as an ordered collection, and you have to access them with an index number (int type). A HashMap however, store items in "key/value" pairs, and you can access them by an index of another type (e.g. a String).

One object is used as a key (index) to another object (value). It can store different types: String keys and Integer values, or the same type, like: String keys and String values:

import java.util.HashMap; // import the HashMap class
HashMap<String, String> capitalCities = new HashMap<tring, String>();


Add Items

The HashMap class has many useful methods. For example, to add items to it, use the put() method:

import java.util.HashMap;

public class Main {
  public static void main(String[] args) {
    // Create a HashMap object called capitalCities
    HashMap<String, String> capitalCities = new HashMap<String, String>();

    // Add keys and values (Country, City)
    capitalCities.put("England", "London");
    capitalCities.put("Germany", "Berlin");
    capitalCities.put("Norway", "Oslo");
    capitalCities.put("USA", "Washington DC");
    System.out.println(capitalCities);
  }
}



Access an Item

To access a value in the HashMap, use the get() method and refer to its key:

capitalCities.get("England");


Remove an Item

To remove an item, use the remove() method and refer to the key:

capitalCities.remove("England");


HashMap Size

To find out how many items there are, use the size() method:

capitalCities.size();



Other Types

Keys and values in a HashMap are actually objects. In the examples above, we used objects of type "String". Remember that a String in Java is an object (not a primitive type). To use other types, such as int, you must specify an equivalent wrapper class: Integer. For other primitive types, use: Boolean for boolean, Character for char, Double for double, etc:

import java.util.HashMap;

public class Main {
  public static void main(String[] args) {

    // Create a HashMap object called people
    HashMap<String, Integer> people = new HashMap<String, Integer>();


    // Add keys and values (Name, Age)
    people.put("John", 32);
    people.put("Steve", 30);
    people.put("Angie", 33);

    for (String i : people.keySet()) {
      System.out.println("key: " + i + " value: " + people.get(i));
    }
  }
}



Java Harsh Set

A HashSet is a collection of items where every item is unique, and it is found in the java.util package:

import java.util.HashSet;
HashSet<String> cars = new HashSet<String>();



Add Items

The HashSet class has many useful methods. For example, to add items to it, use the add() method:

import java.util.HashSet;

public class Main {
  public static void main(String[] args) {
    HashSet cars = new HashSet();
    cars.add("Lamborgini");
    cars.add("Buggati");
    cars.add("Mustang GT");
    cars.add("Buggati");
    cars.add("Farrari");
    System.out.println(cars);
  }
}



Check If an Item Exists

To check whether an item exists in a HashSet, use the contains() method:

cars.contains("Lamborgini");


Remove an Item

To remove an item, use the remove() method:

cars.remove("Lamborgini");


HashSet Size

To find out how many items there are, use the size method:

cars.size();




Other Types

Items in an HashSet are actually objects. In the examples above, we created items (objects) of type "String". Remember that a String in Java is an object (not a primitive type). To use other types, such as int, you must specify an equivalent wrapper class: Integer. For other primitive types, use: Boolean for boolean, Character for char, Double for double, etc:

import java.util.HashSet;

public class Main {
  public static void main(String[] args) {

    // Create a HashSet object called numbers
    HashSet<Integer> numbers = new HashSet<Integer>();

    // Add values to the set
    numbers.add(4);
    numbers.add(7);
    numbers.add(8);

    // Show which numbers between 1 and 10 are in the set
    for(int i = 1; i <= 10; i++) {
      if(numbers.contains(i)) {
        System.out.println(i + " was found in the set.");
      } else {
        System.out.println(i + " was not found in the set.");
      }
    }
  }
}






Iterator in java programming

An Iterator is an object that can be used to loop through collections, like ArrayList and HashSet. It is called an "iterator" because "iterating" is the technical term for looping.

To use an Iterator, you must import it from the java.util package.




Getting an Iterator

The iterator() method can be used to get an Iterator for any collection:

import java.util.ArrayList;
import java.util.Iterator;

public class Main {
  public static void main(String[] args) {

    // Make a collection
    ArrayList cars = new ArrayList();
    cars.add("Lamborgini");
    cars.add("Audi");
    cars.add("Farrari");
    cars.add("Mustang GT");

    // Get the iterator
    Iterator it = cars.iterator();

    // Print the first item
    System.out.println(it.next());
  }
}

Looping Through a Collection

To loop through a collection, use the hasNext() and next() methods of the Iterator:

while(it.hasNext()) {
  System.out.println(it.next());
}



Removing Items from a Collection

Iterators are designed to easily change the collections that they loop through. The remove() method can remove items from a collection while looping.

import java.util.ArrayList;
import java.util.Iterator;

public class Main {
  public static void main(String[] args) {
    ArrayList numbers = new ArrayList();
    numbers.add(12);
    numbers.add(8);
    numbers.add(2);
    numbers.add(23);
    Iterator it = numbers.iterator();
    while(it.hasNext()) {
      Integer i = it.next();
      if(i < 10) {
        it.remove();
      }
    }
    System.out.println(numbers);
  }
}



Wrapper classes in java

A Wrapper class is a class whose object wraps or contains primitive data types. When we create an object to a wrapper class, it contains a field and in this field, we can store primitive data types. In other words, we can wrap a primitive value into a wrapper class object.


Need of Wrapper Classes

  1. They convert primitive data types into objects. Objects are needed if we wish to modify the arguments passed into a method (because primitive types are passed by value).
  2. The classes in java.util package handles only objects and hence wrapper classes help in this case also.
  3. Data structures in the Collection framework, such asArrayList and Vector, store only objects (reference types) and not primitive types.
  4. An object is needed to support synchronization in multithreading.




Autoboxing and Unboxing

Autoboxing: Automatic conversion of primitive types to the object of their corresponding wrapper classes is known as autoboxing. For example – conversion of int to Integer, long to Long, double to Double etc.

// Java program to demonstrate Autoboxing

import java.util.ArrayList;
class Autoboxing
{
	public static void main(String[] args)
	{
		char ch = 'a';

		// Autoboxing- primitive to Character object conversion
		Character a = ch;

		ArrayList arrayList = new ArrayList();

		// Autoboxing because ArrayList stores only objects
		arrayList.add(25);

		// printing the values from object
		System.out.println(arrayList.get(0));
	}
}

Unboxing: It is just the reverse process of autoboxing. Automatically converting an object of a wrapper class to its corresponding primitive type is known as unboxing. For example – conversion of Integer to int, Long to long, Double to double, etc.

// Java program to demonstrate Unboxing
import java.util.ArrayList;

class Unboxing
{
	public static void main(String[] args)
	{
		Character ch = 'a';

		// unboxing - Character object to primitive conversion
		char a = ch;

		ArrayList<Integer> arrayList = new ArrayList<Integer>();
		arrayList.add(24);

		// unboxing because get method returns an Integer object
		int num = arrayList.get(0);

		// printing the values from primitive data types
		System.out.println(num);
	}
}

// Java program to demonstrate Wrapping and UnWrapping
// in Java Classes
class WrappingUnwrapping
{
	public static void main(String args[])
	{
		// byte data type
		byte a = 1;

		// wrapping around Byte object
		Byte byteobj = new Byte(a);

		// int data type
		int b = 10;

		//wrapping around Integer object
		Integer intobj = new Integer(b);

		// float data type
		float c = 18.6f;

		// wrapping around Float object
		Float floatobj = new Float(c);

		// double data type
		double d = 250.5;

		// Wrapping around Double object
		Double doubleobj = new Double(d);

		// char data type
		char e='a';

		// wrapping around Character object
		Character charobj=e;

		// printing the values from objects
		System.out.println("Values of Wrapper objects (printing as objects)");
		System.out.println("Byte object byteobj: " + byteobj);
		System.out.println("Integer object intobj: " + intobj);
		System.out.println("Float object floatobj: " + floatobj);
		System.out.println("Double object doubleobj: " + doubleobj);
		System.out.println("Character object charobj: " + charobj);

		// objects to data types (retrieving data types from objects)
		// unwrapping objects to primitive data types
		byte bv = byteobj;
		int iv = intobj;
		float fv = floatobj;
		double dv = doubleobj;
		char cv = charobj;

		// printing the values from data types
		System.out.println("Unwrapped values (printing as data types)");
		System.out.println("byte value, bv: " + bv);
		System.out.println("int value, iv: " + iv);
		System.out.println("float value, fv: " + fv);
		System.out.println("double value, dv: " + dv);
		System.out.println("char value, cv: " + cv);
	}
}



More about Exception Handling in Java programming

An exception is an unwanted or unexpected event, which occurs during the execution of a program i.e at run time, that disrupts the normal flow of the program's instructions.


Error vs Exception

Error: An Error indicates serious problem that a reasonable application should not try to catch.

Exception: Exception indicates conditions that a reasonable application might try to catch.


Exception Hierarchy

All exception and errors types are sub classes of class Throwable, which is base class of hierarchy.One branch is headed by Exception. This class is used for exceptional conditions that user programs should catch. NullPointerException is an example of such an exception.Another branch,Error are used by the Java run-time system(JVM) to indicate errors having to do with the run-time environment itself(JRE). StackOverflowError is an example of such an error.



How JVM handle an Exception?

Default Exception Handling : Whenever inside a method, if an exception has occurred, the method creates an Object known as Exception Object and hands it off to the run-time system(JVM). The exception object contains name and description of the exception, and current state of the program where exception has occurred. Creating the Exception Object and handling it to the run-time system is called throwing an Exception.There might be the list of the methods that had been called to get to the method where exception was occurred. This ordered list of the methods is called Call Stack.Now the following procedure will happen.

  • The run-time system searches the call stack to find the method that contains block of code that can handle the occurred exception. The block of the code is called Exception handler.
  • The run-time system starts searching from the method in which exception occurred, proceeds through call stack in the reverse order in which methods were called.
  • If it finds  appropriate handler then it passes the occurred exception to it. Appropriate handler means the type of the exception object thrown matches the type of the exception object it can handle.
  • If run-time system searches all the methods on call stack and couldn’t have found the appropriate handler then run-time system handover the Exception Object to default exception handler , which is part of run-time system. This handler prints the exception information in the following format and terminates program abnormally.
    Exception in thread "xxx" Name of Exception : Description
        ... ...... ..  // Call Stack
        

class ThrowsExecp{

    public static void main(String args[]){

        String str = null;
        System.out.println(str.length());

    }
}


class ExceptionThrown
{
    // It throws the Exception(ArithmeticException).
    // Appropriate Exception handler is not found within this method.
    static int divideByZero(int a, int b){

        // this statement will cause ArithmeticException(/ by zero)
        int i = a/b;

        return i;
    }

    // The runTime System searches the appropriate Exception handler
    // in this method also but couldn't have found. So looking forward
    // on the call stack.
    static int computeDivision(int a, int b) {

        int res =0;

        try
        {
          res = divideByZero(a,b);
        }
        // doesn't matches with ArithmeticException
        catch(NumberFormatException ex)
        {
           System.out.println("NumberFormatException is occured");
        }
        return res;
    }

    // In this method found appropriate Exception handler.
    // i.e. matching catch block.
    public static void main(String args[]){

        int a = 1;
        int b = 0;

        try
        {
            int i = computeDivision(a,b);

        }

        // matching ArithmeticException
        catch(ArithmeticException ex)
        {
            // getMessage will print description of exception(here / by zero)
            System.out.println(ex.getMessage());
        }
   



Jagged Array in Java

Jagged array is a multidimensional array where member arrays are of different size. For example, we can create a 2D array where first array is of 3 elements, and is of 4 elements. Following is the example demonstrating the concept of jagged array.

public class Tester {
   public static void main(String[] args){
      int[][] twoDimenArray = new int[2][];

      //first row has 3 columns
      twoDimenArray[0] = new int[3];

      //second row has 4 columns
      twoDimenArray[1] = new int[4];

      int counter = 0;
      //initializing array
      for(int row=0; row < twoDimenArray.length; row++){

         for(int col=0; col < twoDimenArray[row].length; col++){
            twoDimenArray[row][col] = counter++;
         }
      }

      //printing array
      for(int row=0; row < twoDimenArray.length; row++){
         System.out.println();
         for(int col=0; col < twoDimenArray[row].length; col++){
            System.out.print(twoDimenArray[row][col] + " ");
         }
      }
   }
}



StringBuffer class in Java

StringBuffer is a peer class of String that provides much of the functionality of strings. The string represents fixed-length, immutable character sequences while StringBuffer represents growable and writable character sequences. StringBuffer may have characters and substrings inserted in the middle or appended to the end. It will automatically grow to make room for such additions and often has more characters preallocated than are actually needed, to allow room for growth.

  • java.lang.StringBuffer extends (or inherits from) Object class.
  • All Implemented Interfaces of StringBuffer class: Serializable, Appendable, CharSequence.
  • public final class StringBuffer extends Object implements Serializable, CharSequence, Appendable.
  • String buffers are safe for use by multiple threads. The methods can be synchronized wherever necessary so that all the operations on any particular instance behave as if they occur in some serial order.
  • Whenever an operation occurs involving a source sequence (such as appending or inserting from a source sequence) this class synchronizes only on the string buffer performing the operation, not on the source.
  • It inherits some of the methods from the Object class which such as clone(), equals(), finalize(), getClass(), hashCode(), notifies(), notifyAll().

Constructors of StringBuffer class

  • StringBuffer(): It reserves room for 16 characters without reallocation
  • StringBuffer s = new StringBuffer();
  • StringBuffer( int size): It accepts an integer argument that explicitly sets the size of the buffer.



StringBuilder Class

The StringBuilder in Java represents a mutable sequence of characters. Since the String Class in Java creates an immutable sequence of characters, the StringBuilder class provides an alternative to String Class, as it creates a mutable sequence of characters. The function of StringBuilder is very much similar to the StringBuffer class, as both of them provide an alternative to String Class by making a mutable sequence of characters. However the StringBuilder class differs from the StringBuffer class on the basis of synchronization. The StringBuilder class provides no guarantee of synchronization whereas the StringBuffer class does. Therefore this class is designed for use as a drop-in replacement for StringBuffer in places where the StringBuffer was being used by a single thread (as is generally the case). Where possible, it is recommended that this class be used in preference to StringBuffer as it will be faster under most implementations. Instances of StringBuilder are not safe for use by multiple threads. If such synchronization is required then it is recommended that StringBuffer be used.

public final class StringBuilder
  extends Object
     implements Serializable, CharSequence

Class constructors

Sr.No. Constructor & Description
1

StringBuilder()

This constructs a string builder with no characters in it and an initial capacity of 16 characters.

2

StringBuilder(CharSequence seq)

This constructs a string builder that contains the same characters as the specified CharSequence.

3

StringBuilder(int capacity)

This constructs a string builder with no characters in it and an initial capacity specified by the capacity argument.

4

StringBuilder(String str)

This constructs a string builder initialized to the contents of the specified string.




Class methods

Sr.No. Method & Description
1 StringBuilder append(boolean b)

This method appends the string representation of the boolean argument to the sequence.

2 StringBuilder append(char c)

This method appends the string representation of the char argument to this sequence.

3 StringBuilder append(char[] str)

This method appends the string representation of the char array argument to this sequence.

4 StringBuilder append(char[] str, int offset, int len)

This method appends the string representation of a subarray of the char array argument to this sequence.

5 StringBuilder append(CharSequence s)

This method appends the specified character sequence to this Appendable.

6 StringBuilder append(CharSequence s, int start, int end)

This method appends a subsequence of the specified CharSequence to this sequence.

7 StringBuilder append(double d)

This method appends the string representation of the double argument to this sequence.

8 StringBuilder append(float f)

This method appends the string representation of the float argument to this sequence.

9 StringBuilder append(int i)

This method appends the string representation of the int argument to this sequence.

10 StringBuilder append(long lng)

This method appends the string representation of the long argument to this sequence.

11 StringBuilder append(Object obj)

This method appends the string representation of the Object argument.

12 StringBuilder append(String str)

This method appends the specified string to this character sequence.

13 StringBuilder append(StringBuffer sb)

This method appends the specified StringBuffer to this sequence.

14 StringBuilder appendCodePoint(int codePoint)

This method appends the string representation of the codePoint argument to this sequence.

15 int capacity()

This method returns the current capacity.

16 char charAt(int index)

This method returns the char value in this sequence at the specified index.

17 int codePointAt(int index)

This method returns the character (Unicode code point) at the specified index.

18 int codePointBefore(int index)

This method returns the character (Unicode code point) before the specified index.

19 int codePointCount(int beginIndex, int endIndex)

This method returns the number of Unicode code points in the specified text range of this sequence.

20 StringBuilder delete(int start, int end)

This method removes the characters in a substring of this sequence.

21 StringBuilder deleteCharAt(int index)

This method removes the char at the specified position in this sequence.

22 void ensureCapacity(int minimumCapacity)

This method ensures that the capacity is at least equal to the specified minimum.

23 void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)

Characters are copied from this sequence into the destination character array dst.

24 int indexOf(String str)

This method returns the index within this string of the first occurrence of the specified substring.

25 int indexOf(String str, int fromIndex)

This method returns the index within this string of the first occurrence of the specified substring, starting at the specified index.

26 StringBuilder insert(int offset, boolean b)

This method inserts the string representation of the boolean argument into this sequence.

27 StringBuilder insert(int offset, char c)

This method inserts the string representation of the char argument into this sequence.

28 StringBuilder insert(int offset, char[] str)

This method inserts the string representation of the char array argument into this sequence.

29 StringBuilder insert(int index, char[] str, int offset, int len)

This method inserts the string representation of a subarray of the str array argument into this sequence.

30 StringBuilder insert(int dstOffset, CharSequence s)

This method inserts the specified CharSequence into this sequence.

31 StringBuilder insert(int dstOffset, CharSequence s, int start, int end)

This method inserts a subsequence of the specified CharSequence into this sequence.

32 StringBuilder insert(int offset, double d)

This method inserts the string representation of the double argument into this sequence.

33 StringBuilder insert(int offset, float f)

This method inserts the string representation of the float argument into this sequence.

34 StringBuilder insert(int offset, int i)

This method inserts the string representation of the second int argument into this sequence.

35 StringBuilder insert(int offset, long l)

This method inserts the string representation of the long argument into this sequence.

36 StringBuilder insert(int offset, Object obj)

This method inserts the string representation of the Object argument into this character sequence.

37 StringBuilder insert(int offset, String str)

This method inserts the string into this character sequence.

38 int lastIndexOf(String str)

This method returns the index within this string of the rightmost occurrence of the specified substring.

39 int lastIndexOf(String str, int fromIndex)

This method returns the index within this string of the last occurrence of the specified substring.

40 int length()

This method returns the length (character count).

41 int offsetByCodePoints(int index, int codePointOffset)

This method returns the index within this sequence that is offset from the given index by codePointOffset code points.

42 StringBuilder replace(int start, int end, String str)

This method replaces the characters in a substring of this sequence with characters in the specified String.

43 StringBuilder reverse()

This method causes this character sequence to be replaced by the reverse of the sequence.

44 void setCharAt(int index, char ch)

Character at the specified index is set to ch.

45 void setLength(int newLength)

This method sets the length of the character sequence.

46 CharSequence subSequence(int start, int end)

This method returns a new character sequence that is a subsequence of this sequence.

47 String substring(int start)

This method returns a new String that contains a subsequence of characters currently contained in this character sequence.

48 String substring(int start, int end)

This method returns a new String that contains a subsequence of characters currently contained in this sequence.

49 String toString()

This method returns a string representing the data in this sequence.

50 void trimToSize()

This method attempts to reduce storage used for the character sequence.




Different ways of Method Overloading in Java

Method overloading in java is based on the number and type of the parameters passed as an argument to the methods. We can not define more than one method with the same name, Order, and type of the arguments. It would be a compiler error. The compiler does not consider the return type while differentiating the overloaded method. But you cannot declare two methods with the same signature and different return types. It will throw a compile-time error. If both methods have the same parameter types, but different return types, then it is not possible.

Java can distinguish the methods with different method signatures. i.e. the methods can have the same name but with different parameters list (i.e. the number of the parameters, the order of the parameters, and data types of the parameters) within the same class.



Ways of Overloading Methods

  1. The number of parameters in two methods.
  2. The data types of the parameters of methods.
  3. The Order of the parameters of methods.

// Java Program to Illustrate Method Overloading
// By Changing the Number of Parameters

// Importing required classes
import java.io.*;

// Class 1
// Helper class
class Addition {

	// Method 1
	// Adding two integer values
	public int add(int a, int b)
	{

		int sum = a + b;
		return sum;
	}

	// Method 2
	// Adding three integer values
	public int add(int a, int b, int c)
	{

		int sum = a + b + c;
		return sum;
	}
}

// Class 2
// Main class
class Codolearn {

	// Main driver method
	public static void main(String[] args)
	{

		// Creating object of above class inside main()
		// method
		Addition ob = new Addition();

		// Calling method to add 3 numbers
		int sum1 = ob.add(1, 2);

		// Printing sum of 2 numbers
		System.out.println("sum of the two integer value :"
						+ sum1);

		// Calling method to add 3 numbers
		int sum2 = ob.add(1, 2, 3);

		// Printing sum of 3 numbers
		System.out.println(
			"sum of the three integer value :" + sum2);
	}
}



Overriding in Java

In any object-oriented programming language, Overriding is a feature that allows a subclass or child class to provide a specific implementation of a method that is already provided by one of its super-classes or parent classes. When a method in a subclass has the same name, same parameters or signature, and same return type(or sub-type) as a method in its super-class, then the method in the subclass is said to override the method in the super-class.




Method overriding is one of the way by which java achieve Run Time Polymorphism.The version of a method that is executed will be determined by the object that is used to invoke it. If an object of a parent class is used to invoke the method, then the version in the parent class will be executed, but if an object of the subclass is used to invoke the method, then the version in the child class will be executed. In other words, it is the type of the object being referred to (not the type of the reference variable) that determines which version of an overridden method will be executed.

// A Simple Java program to demonstrate
// method overriding in java

// Base Class
class Parent {
	void show()
	{
		System.out.println("Parent's show()");
	}
}

// Inherited class
class Child extends Parent {
	// This method overrides show() of Parent
	@Override
	void show()
	{
		System.out.println("Child's show()");
	}
}

// Driver class
class Main {
	public static void main(String[] args)
	{
		// If a Parent type reference refers
		// to a Parent object, then Parent's
		// show is called
		Parent obj1 = new Parent();
		obj1.show();

		// If a Parent type reference refers
		// to a Child object Child's show()
		// is called. This is called RUN TIME
		// POLYMORPHISM.
		Parent obj2 = new Child();
		obj2.show();
	}
}



Rules for method overriding:

  • Overriding and Access-Modifiers : The access modifier for an overriding method can allow more, but not less, access than the overridden method. For example, a protected instance method in the super-class can be made public, but not private, in the subclass. Doing so, will generate compile-time error.
  • // A Simple Java program to demonstrate
    // Overriding and Access-Modifiers
    
    class Parent {
    	// private methods are not overridden
    	private void m1()
    	{
    		System.out.println("From parent m1()");
    	}
    
    	protected void m2()
    	{
    		System.out.println("From parent m2()");
    	}
    }
    
    class Child extends Parent {
    	// new m1() method
    	// unique to Child class
    	private void m1()
    	{
    		System.out.println("From child m1()");
    	}
    
    	// overriding method
    	// with more accessibility
    	@Override
    	public void m2()
    	{
    		System.out.println("From child m2()");
    	}
    }
    
    // Driver class
    class Main {
    	public static void main(String[] args)
    	{
    		Parent obj1 = new Parent();
    		obj1.m2();
    		Parent obj2 = new Child();
    		obj2.m2();
    	}
    }
    
  • Final methods can not be overridden : If we don’t want a method to be overridden, we declare it as final. Please see Using final with Inheritance .
  • // A Java program to demonstrate that
    // final methods cannot be overridden
    
    class Parent {
    	// Can't be overridden
    	final void show() {}
    }
    
    class Child extends Parent {
    	// This would produce error
    	void show() {}
    }
    
  • Static methods can not be overridden(Method Overriding vs Method Hiding) : When you define a static method with same signature as a static method in base class, it is known as method hiding. The following table summarizes what happens when you define a method with the same signature as a method in a super-class.
  • // Java program to show that
    // if the static method is redefined by
    // a derived class, then it is not
    // overriding, it is hiding
    
    class Parent {
    	// Static method in base class
    	// which will be hidden in subclass
    	static void m1()
    	{
    		System.out.println("From parent "
    						+ "static m1()");
    	}
    
    	// Non-static method which will
    	// be overridden in derived class
    	void m2()
    	{
    		System.out.println("From parent "
    						+ "non-static(instance) m2()");
    	}
    }
    
    class Child extends Parent {
    	// This method hides m1() in Parent
    	static void m1()
    	{
    		System.out.println("From child static m1()");
    	}
    
    	// This method overrides m2() in Parent
    	@Override
    	public void m2()
    	{
    		System.out.println("From child "
    						+ "non-static(instance) m2()");
    	}
    }
    
    // Driver class
    class Main {
    	public static void main(String[] args)
    	{
    		Parent obj1 = new Child();
    
    		// As per overriding rules this
    		// should call to class Child static
    		// overridden method. Since static
    		// method can not be overridden, it
    		// calls Parent's m1()
    		obj1.m1();
    
    		// Here overriding works
    		// and Child's m2() is called
    		obj1.m2();
    	}
    }
    



Why Method Overriding ?

As stated earlier, overridden methods allow Java to support run-time polymorphism. Polymorphism is essential to object-oriented programming for one reason: it allows a general class to specify methods that will be common to all of its derivatives while allowing subclasses to define the specific implementation of some or all of those methods. Overridden methods are another way that Java implements the “one interface, multiple methods” aspect of polymorphism.

Dynamic Method Dispatch is one of the most powerful mechanisms that object-oriented design brings to bear on code reuse and robustness. The ability to exist code libraries to call methods on instances of new classes without recompiling while maintaining a clean abstract interface is a profoundly powerful tool. Overridden methods allow us to call methods of any of the derived classes without even knowing the type of derived class object.



When to apply Method Overriding ?

Overriding and Inheritance : Part of the key to successfully applying polymorphism is understanding that the superclasses and subclasses form a hierarchy which moves from lesser to greater specialization. Used correctly, the superclass provides all elements that a subclass can use directly. It also defines those methods that the derived class must implement on its own. This allows the subclass the flexibility to define its methods, yet still enforces a consistent interface. Thus, by combining inheritance with overridden methods, a superclass can define the general form of the methods that will be used by all of its subclasses.




Nested Interface in Java

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.

Points to remember for nested interfaces

  • The nested interface must be public if it is declared inside the interface, but it can have any access modifier if declared within the class.
  • Nested interfaces are declared static
interface Showable{
  void show();
  interface Message{
   void msg();
  }
}
class TestNestedInterface1 implements Showable.Message{
 public void msg(){System.out.println("Hello nested interface");}

 public static void main(String args[]){
  Showable.Message message=new TestNestedInterface1();//upcasting here
  message.msg();
 }
}  



Functional Interfaces in Java

Java has forever remained an Object-Oriented Programming language. By object-oriented programming language, we can declare that everything present in the Java programming language rotates throughout the Objects, except for some of the primitive data types and primitive methods for integrity and simplicity. There are no solely functions present in a programming language called Java. Functions in the Java programming language are part of a class, and if someone wants to use them, they have to use the class or object of the class to call any function.

A functional interface is an interface that contains only one abstract method. They can have only one functionality to exhibit. From Java 8 onwards, lambda expressions can be used to represent the instance of a functional interface. A functional interface can have any number of default methods. Runnable, ActionListener, Comparable are some of the examples of functional interfaces.



Functional Interface is additionally recognized as Single Abstract Method Interfaces. In short, they are also known as SAM interfaces. Functional interfaces in Java are the new feature that provides users with the approach of fundamental programming. Functional interfaces are included in Java SE 8 with Lambda expressions and Method references in order to make code more readable, clean, and straightforward. Functional interfaces are interfaces that ensure that they include precisely only one abstract method. Functional interfaces are used and executed by representing the interface with an annotation called @FunctionalInterface. As described earlier, functional interfaces can contain only one abstract method. However, they can include any quantity of default and static methods. In Functional interfaces, there is no need to use the abstract keyword as it is optional to use the abstract keyword because, by default, the method defined inside the interface is abstract only. We can also call Lambda expressions as the instance of functional interface.

// Java program to demonstrate functional interface

class Test {
	public static void main(String args[])
	{
		// create anonymous inner class object
		new Thread(new Runnable() {
			@Override public void run()
			{
				System.out.println("New thread created");
			}
		}).start();
	}
}






Super Keyword in Java

The super keyword in java is a reference variable that is used to refer parent class objects. The keyword “super” came into the picture with the concept of Inheritance. It is majorly used in the following contexts:

/* Base class vehicle */
class Vehicle
{
	int maxSpeed = 120;
}

/* sub class Car extending vehicle */
class Car extends Vehicle
{
	int maxSpeed = 180;

	void display()
	{
		/* print maxSpeed of base class (vehicle) */
		System.out.println("Maximum Speed: " + super.maxSpeed);
	}
}

/* Driver program to test */
class Test
{
	public static void main(String[] args)
	{
		Car small = new Car();
		small.display();
	}
}




© 2021 Created By "KARTIK A DIGITAL INFLUENCER" || All Rights Reserved