Java Unit-1
Java Unit-1
CSE II-I
BY
Dr.N.Lingareddy
Associate professor
UNIT-I
A way of viewing world
A way of viewing the world is an idea to illustrate the object-oriented programming concept with an
example of a real-world situation.
Let us consider a situation, I am at my office and I wish to get food to my family members who are at
my home from a hotel. Because of the distance from my office to home, there is no possibility of
getting food from a hotel myself. So, how do we solve the issue?
To solve the problem, let me call zomato (an agent in food delevery community), tell them the
variety and quantity of food and the hotel name from which I wish to delever the food to my family
members. Look at the following image.
Agents and Communities
To solve my food delivery problem, I used a solution by finding an appropriate agent (Zomato) and
pass a message containing my request. It is the responsibility of the agent (Zomato) to satisfy my
request. Here, the agent uses some method to do this. I do not need to know the method that the
agent has used to solve my request. This is usually hidden from me.
So, in object-oriented programming, problem-solving is the solution to our problem which requires
the help of many individuals in the community. We may describe agents and communities as follows.
An object-oriented program is structured as a community of interacting agents, called
objects. Where each object provides a service (data and methods) that is used by other
members of the community.
In our example, the online food delivery system is a community in which the agents are zomato and
set of hotels. Each hotel provides a variety of services that can be used by other members like
zomato, myself, and my family in the community.
Responsibilities
In object-oriented programming, behaviors of an object described in terms of
responsibilities.
In our example, my request for action indicates only the desired outcome (food
delivered to my family). The agent (zomato) free to use any technique that solves
my problem. By discussing a problem in terms of responsibilities increases the level
of abstraction. This enables more independence between the objects in solving
complex problems.
Encapsulation
Inheritance
Polymorphism
Abstraction
The popular object-oriented programming languages are Smalltalk, C++, Java, PHP, C#, Python,
etc.
Encapsulation
Encapsulation is the process of combining data and code into a single unit (object / class). In OOP,
every object is associated with its data and code. In programming, data is defined as variables and
code is defined as methods. The java programming language uses the class concept to implement
encapsulation.
Inheritance
Inheritance is the process of acquiring properties and behaviors from one object to another object or
one class to another class. In inheritance, we derive a new class from the existing class. Here, the
new class acquires the properties and behaviors from the existing class. In the inheritance concept,
the class which provides properties is called as parent class and the class which recieves the
properties is called as child class. The parent class is also known as base class or supre class. The
child class is also known as derived class or sub class.
In the inheritance, the properties and behaviors of base class extended to its derived class, but the
base class never receive properties or behaviors from its derived class.
In java programming language the keyword extends is used to implement
inheritance.
Polymorphism
Method overriding - multiple methods with same name and same parameters.
Abstraction
Abstraction is hiding the internal details and showing only esential functionality. In the abstraction
concept, we do not show the actual implemention to the end user, instead we provide only esential
things. For example, if we want to drive a car, we does not need to know about the internal
functionality like how wheel system works? how brake system works? how music system works? etc.
Java Buzz Words
ava is the most popular object-oriented programming language. Java has many advanced features,
a list of key features is known as Java Buzz Words. The java team has listed the following terms as
java buzz words.
Simple
Secure
Portable
Object-oriented
Robust
Architecture-neutral (or) Platform Independent
Multi-threaded
Interpreted
High performance
Distributed
Dynamic
Simple
Java programming language is very simple and easy to learn, understand, and code. Most of the
syntaxes in java follow basic programming language C and object-oriented programming concepts
are similar to C++. In a java programming language, many complicated features like pointers,
operator overloading, structures, unions, etc. have been removed. One of the most useful features is
the garbage collector it makes java more simple.
Secure
Java is said to be more secure programming language because it does not have pointers concept,
java provides a feature "applet" which can be embedded into a web application. The applet in java
does not allow access to other parts of the computer, which keeps away from harmful programs like
viruses and unauthorized access.
Portable
Portability is one of the core features of java which enables the java programs to run on any
computer or operating system. For example, an applet developed using java runs on a wide variety
of CPUs, operating systems, and browsers connected to the Internet.
Object-oriented
Java is said to be a pure object-oriented programming language. In java, everything is an object. It
supports all the features of the object-oriented programming paradigm. The primitive data types java
also implemented as objects using wrapper classes, but still, it allows primitive data types to archive
high-performance.
Robust
Java is more robust because the java code can be executed on a variety of environments, java has
a strong memory management mechanism (garbage collector), java is a strictly typed language, it
has a strong set of exception handling mechanism, and many more.
Multi-threaded
Java supports multi-threading programming, which allows us to write programs that do multiple
operations simultaneously.
Interpreted
Java enables the creation of cross-platform programs by compiling into an intermediate
representation called Java bytecode. The byte code is interpreted to any machine code so that it
runs on the native machine.
High performance
Java provides high performance with the help of features like JVM, interpretation, and its simplicity.
Distributed
Java programming language supports TCP/IP protocols which enable the java to support the
distributed environment of the Internet. Java also supports Remote Method Invocation (RMI), this
feature enables a program to invoke methods across a network.
Dynamic
Java is said to be dynamic because the java byte code may be dynamically updated on a running
system and it has a dynamic memory allocation and deallocation (objects and garbage collector).
Overview of Java
Java is a computer programming language. Java was created based on C and C++. Java uses C
syntax and many of the object-oriented features are taken from C++. Before Java was invented
there were other languages like COBOL, FORTRAN, C, C++, Small Talk, etc. These languages had
few disadvantages which were corrected in Java. Java also innovated many new features to solve
the fundamental problems which the previous languages could not solve. Java was invented by a
team of 13 employees of Sun Microsystems, Inc. which is lead by James Gosling, in 1991. The team
includes persons like Patrick Naughton, Chris Warth, Ed Frank, and Mike Sheridan, etc., Java was
developed as a part of the Green project. Initially, it was called Oak, later it was changed to Java in
1995.
History of Java
The C language developed in 1972 by Dennis Ritchie had taken a decade to become the
most popular language.
In 1979, Bjarne Stroustrup developed C++, an enhancement to the C language with included
OOP fundamentals and features.
A project named “Green” was initiated in December of 1990, whose aim was to create a
programming tool that could render obsolete the C and C++ programming languages.
Finally in the year of 1991 the Green Team was created a new Programming language
named “OAK”.
After some time they found that there is already a programming language with the name
“OAK”.
So, the green team had a meeting to choose a new name. After so many discussions they
want to have a coffee. They went to a Coffee Shop which is just outside of the Gosling’s
office and there they have decided name as “JAVA”.
Let's look at the following example java program to illustrate primitive data types in java and their
default values.
Example
public class PrimitiveDataTypes {
byte i;
short j;
int k;
long l;
float m;
double n;
char ch;
boolean p;
System.out.println("i = " + obj.i + ", j = " + obj.j + ", k = " + obj.k + ", l =
" + obj.l);
System.out.println("m = " + obj.m + ", n = " + obj.n);
System.out.println("ch = " + obj.ch);
System.out.println("p = " + obj.p);
}
}
o/p
These are built-in data types These are created by the users
Java Variables
A variable is a named memory location used to store a data value. A variable can be defined as a
container that holds a data value.
In java, we use the following syntax to create variables.
Syntax
data_type variable_name;
(or)
data_type variable_name_1, variable_name_2,...;
(or)
data_type variable_name = value;
(or)
data_type variable_name_1 = value, variable_name_2 = value,...;
Local variables
Instance variables or Member variables or Global variables
Static variables or Class variables
Local variables
The variables declared inside a method or a block are known as local variables. A local variable is
visible within the method in which it is declared. The local variable is created when execution control
enters into the method or block and destroyed after the method or block execution completed.
Java Arrays
An array is a collection of similar data values with a single name. An array can also be defined as, a
special type of variable that holds multiple values of the same data type at a time.
In java, arrays are objects and they are created dynamically using new operator. Every array in java
is organized using index values. The index value of an array starts with '0' and ends with 'zise-1'. We
use the index value to access individual elements of an array.
In java, there are two types of arrays and they are as follows.
One Dimensional Array
Multi Dimensional Array
Creating an array
In the java programming language, an array must be created using new operator and with a specific
size. The size must be an integer value but not a byte, short, or long. We use the following syntax to
create an array.
Syntax
Example
list[0] = 10;
System.out.println("Value at index 0 - " + list[0]);
System.out.println("Length of the array - " + list.length);
o/p
In java, an array can also be initialized at the time of its declaration. When an array is initialized at
the time of its declaration, it need not specify the size of the array and use of the new operator. Here,
the size is automatically decided based on the number of values that are initialized.
Example
Example
list[0] = 10;
System.out.println("Value at index 0 - " + list[0]);
Multidimensional Array
In java, we can create an array with multiple dimensions. We can create 2-dimensional, 3-
dimensional, or any dimensional array.
In Java, multidimensional arrays are arrays of arrays. To create a multidimensional array variable,
specify each additional index using another set of square brackets. We use the following syntax to
create two-dimensional array.
Syntax
data_type array_name[ ][ ] = new data_type[rows][columns];
(or)
data_type[ ][ ] array_name = new data_type[rows][columns];
When we create a two-dimensional array, it created with a separate index for rows and columns.
The individual element is accessed using the respective row index followed by the column index. A
multidimensional array can be initialized while it has created using the following syntax.
Syntax
When an array is initialized at the time of declaration, it need not specify the size of the array and
use of the new operator. Here, the size is automatically decided based on the number of values that
are initialized.
Example
The above statement creates a two-dimensional array of three rows and two columns.
To subtract two matrices, use - operator. Let's see a simple example to add two matrices of 3 rows
and 3 columns.
Output:
2 6 8
4 8 6
4 6 9
In case of matrix multiplication, one row element of first matrix is multiplied by all
columns of second matrix.
Let's see a simple example to multiply two matrices of 3 rows and 3 columns.
Output:
6 6 6
12 12 12
18 18 18
Java Operators
Operator in Java is a symbol that is used to perform operations. For example: +, -, *, / etc.
There are many types of operators in Java which are given below:
o Unary Operator,
o Arithmetic Operator,
o Shift Operator,
o Relational Operator,
o Bitwise Operator,
o Logical Operator,
o Ternary Operator and
o Assignment Operator.
Arithmetic multiplicative * / %
additive + -
equality == !=
bitwise exclusive OR ^
bitwise inclusive OR |
Ternary ternary ? :
The Java unary operators require only one operand. Unary operators are used to perform various
operations i.e.:
Output:
10
12
12
10
Java arithmetic operators are used to perform addition, subtraction, multiplication, and division. They
act as basic mathematical operations.
Output:
15
5
50
2
0
The Java left shift operator << is used to shift all of the bits in a value to the left side of a specified
number of times.
Output:
40
80
80
240
Java Right Shift Operator
The Java right shift operator >> is used to move the value of the left operand to right by the number
of bits specified by the right operand.
Output:
2
5
2
Operato
r Meaning Example
< Returns TRUE if the first value is smaller than second value otherwise returns 10 < 5 is
FALSE FALSE
> Returns TRUE if the first value is larger than second value otherwise returns 10 > 5 is TRUE
FALSE
<= Returns TRUE if the first value is smaller than or equal to second value 10 <= 5 is
otherwise returns FALSE FALSE
>= Returns TRUE if the first value is larger than or equal to second value otherwise 10 >= 5 is
returns FALSE TRUE
FALSE
!= Returns TRUE if both values are not equal otherwise returns FALSE 10 != 5 is TRUE
Example
boolean a;
a = 10<5;
System.out.println("10 < 5 is " + a);
a = 10>5;
System.out.println("10 > 5 is " + a);
a = 10<=5;
System.out.println("10 <= 5 is " + a);
a = 10>=5;
System.out.println("10 >= 5 is " + a);
a = 10==5;
System.out.println("10 == 5 is " + a);
a = 10!=5;
System.out.println("10 != 5 is " + a);
}
}
o/p
Logical Operators
The logical operators are the symbols that are used to combine multiple conditions into one
condition. The following table provides information about logical operators.
Operato
r Meaning Example
& Logical AND - Returns TRUE if all conditions are TRUE otherwise returns false & true =>
FALSE false
| Logical OR - Returns FALSE if all conditions are FALSE otherwise returns false | true =>
TRUE true
^ Logical XOR - Returns FALSE if all conditions are same otherwise returns true ^ true =>
TRUE false
! Logical NOT - Returns TRUE if condition is FLASE and returns FALSE if it is !false => true
TRUE
&& short-circuit AND - Similar to Logical AND (&), but once a decision is finalized false & true =>
it does not evaluate remianing. false
|| short-circuit OR - Similar to Logical OR (|), but once a decision is finalized it false | true =>
does not evaluate remianing. true
Example
public class LogicalOperators {
public static void main(String[] args) {
o/p
Assignment Operators
The assignment operators are used to assign right-hand side value (Rvalue) to the left-hand side
variable (Lvalue). The assignment operator is used in different variants along with arithmetic
operators. The following table describes all the assignment operators in the java programming
language.
Operato
r Meaning Example
+= Add both left and right-hand side values and store the result into left-hand side variable A += 10
-= Subtract right-hand side value from left-hand side variable value and store the result A -= B
Operato
r Meaning Example
*= Multiply right-hand side value with left-hand side variable value and store the result into A *= B
left-hand side variable
/= Divide left-hand side variable value with right-hand side variable value and store the A /= B
result into the left-hand side variable
%= Divide left-hand side variable value with right-hand side variable value and store the A %= B
remainder into the left-hand side variable
|= Logical OR assignment -
Example
a += b;
System.out.println("a = " + a);
a -= b;
System.out.println("a = " + a);
a *= b;
System.out.println("a = " + a);
a /= b;
System.out.println("a = " + a);
a %= b;
System.out.println("a = " + a);
x |= (a>b);
System.out.println("x = " + x);
x &= (a>b);
System.out.println("x = " + x);
}
}
o/p
Bitwise Operators
The bitwise operators are used to perform bit-level operations in the java programming language.
When we use the bitwise operators, the operations are performed based on binary values. The
following table describes all the bitwise operators in the java programming language.
Let us consider two variables A and B as A = 25 (11001) and B = 20 (10100).
Operato
r Meaning Example
& the result of Bitwise AND is 1 if all the bits are 1 otherwise it is 0 A&B
⇒ 16 (10000)
Operato
r Meaning Example
^ the result of Bitwise XOR is 0 if all the bits are same otherwise it is 1 A^B
⇒ 13 (01101)
<< the Bitwise left shift operator shifts all the bits to the left by the specified number A << 2
of positions ⇒ 100
(1100100)
>> the Bitwise right shift operator shifts all the bits to the right by the specified A >> 2
number of positions ⇒ 6 (00110)
Example
o/p
Conditional Operators
The conditional operator is also called a ternary operator because it requires three operands. This
operator is used for decision making. In this operator, first, we verify a condition, then we perform
one operation out of the two operations based on the condition result. If the condition is TRUE the
first option is performed, if the condition is FALSE the second option is performed. The conditional
operator is used with the following syntax.
Syntax
Example
c = (a>b)? a : b;
o/p
Java Expressions
In any programming language, if we want to perform any calculation or to frame any condition etc.,
we use a set of symbols to perform the task. These set of symbols makes an expression.
In the java programming language, an expression is defined as follows.
An expression is a collection of operators and operands that represents a specific value.
In the above definition, an operator is a symbol that performs tasks like arithmetic operations,
logical operations, and conditional operations, etc.
Operands are the values on which the operators perform the task. Here operand can be a direct
value or variable or address of memory location.
Expression Types
In the java programming language, expressions are divided into THREE types. They are as follows.
Infix Expression
Postfix Expression
Prefix Expression
Infix Expression
The expression in which the operator is used between operands is called infix expression.
The infix expression has the following general structure.
Example
Postfix Expression
The expression in which the operator is used after operands is called postfix expression.
The postfix expression has the following general structure.
Example
Prefix Expression
The expression in which the operator is used before operands is called a prefix expression.
The prefix expression has the following general structure.
Example
Java Control Statements
In java, the default execution flow of a program is a sequential order. But the sequential order of
execution flow may not be suitable for all situations. Sometimes, we may want to jump from line to
another line, we may want to skip a part of the program, or sometimes we may want to execute a
part of the program again and again. To solve this problem, java provides control statements.
In java, the control statements are the statements which will tell us that in which order the
instructions are getting executed. The control statements are used to control the order of execution
according to our requirements. Java provides several control statements, and they are classified as
follows.
if statement
if-else statement
if-elif statement
nested if statement
switch statement
if statement in java
In java, we use the if statement to test a condition and decide the execution of a block of statements
based on that condition result. The if statement checks, the given condition then decides the
execution of a block of statements. If the condition is True, then the block of statements is executed
and if it is False, then the block of statements is ignored. The syntax and execution flow of if the
statement is as follows.
Java Program
import java.util.Scanner;
if((num % 5) == 0) {
System.out.println("We are inside the if-block!");
System.out.println("Given number is divisible by 5!!");
}
o/p
if((num % 2) == 0) {
System.out.println("We are inside the true-block!");
System.out.println("Given number is EVEN number!!");
}
else {
System.out.println("We are inside the false-block!");
System.out.println("Given number is ODD number!!");
}
o/p
Nested if statement in java
Writing an if statement inside another if-statement is called nested if statement. The general syntax
of the nested if-statement is as follows.
Syntax
if(condition_1){
if(condition_2){
inner if-block of statements;
...
}
...
}
Java Program
import java.util.Scanner;
o/p
Syntax
if(condition_1){
condition_1 true-block;
...
}
else if(condition_2){
condition_2 true-block;
condition_1 false-block too;
...
}
Java Program
import java.util.Scanner;
else
System.out.println("\nThe largest number is " + num3) ;
o/p
switch( value )
{
case 0: System.out.println("ZERO") ; break ;
case 1: System.out.println("ONE") ; break ;
case 2: System.out.println("TWO") ; break ;
case 3: System.out.println("THREE") ; break ;
case 4: System.out.println("FOUR") ; break ;
case 5: System.out.println("FIVE") ; break ;
case 6: System.out.println("SIX") ; break ;
case 7: System.out.println("SEVEN") ; break ;
case 8: System.out.println("EIGHT") ; break ;
case 9: System.out.println("NINE") ; break ;
default: System.out.println("Not a Digit") ;
}
o/p
while statement
do-while statement
for statement
for-each statement
int num = 1;
o/p
do-while statement in java
The do-while statement is used to execute a single statement or block of statements repeatedly as
long as given the condition is TRUE. The do-while statement is also known as the Exit control
looping statement. The do-while statement has the following syntax.
Java Program
public class DoWhileTest {
int num = 1;
do {
System.out.println(num);
num++;
}while(num <= 10);
o/p
In for-statement, the execution begins with the initialization statement. After the initialization
statement, it executes Condition. If the condition is evaluated to true, then the block of statements
executed otherwise it terminates the for-statement. After the block of statements execution,
the modification statement gets executed, followed by condition again.
Let's look at the following example java code.
Java Program
public class ForTest {
public static void main(String[] args) {
o/p
NestedForExample.java
Output:
1 1
1 2
1 3
2 1
2 2
2 3
3 1
3 2
3 3
Pyramid Example 1:
PyramidExample.java
Output:
*
* *
* * *
* * * *
* * * * *
break statement
continue statement
labelled break and continue statements
return statement
Java Program
for(int i : list) {
if(i == 30)
break;
System.out.println(i);
}
o/p
continue statement in java
The continue statement is used to move the execution control to the beginning of the looping
statement. When the continue statement is encountered in a looping statement, the execution
control skips the rest of the statements in the looping block and directly jumps to the beginning of the
loop. The continue statement can be used with looping statements like while, do-while, for, and for-
each.
When we use continue statement with while and do-while statements, the execution control directly
jumps to the condition. When we use continue statement with for statement the execution control
directly jumps to the modification portion (increment/decrement/any modification) of the for loop. The
continue statement flow of execution is as shown in the following figure.
Java Program
public class JavaContinueStatement {
for(int i : list) {
if(i == 30)
continue;
System.out.println(i);
}
o/p
Java Program
import java.util.Scanner;
verify: if (value % 2 == 0) {
System.out.println("\nYou won!!!");
System.out.println("Your score is " + i*10 + " out of 30.");
break reading;
} else {
System.out.println("\nSorry try again!!!");
System.out.println("You let with " + (3-i) + " more
options...");
continue reading;
}
}
}
}
o/p
In java, the return statement used with both methods with and without return type. In the case of a
method with the return type, the return statement is mandatory, and it is optional for a method
without return type.
When a return statement used with a return type, it carries a value of return type. But, when it is
used without a return type, it does not carry any value. Instead, simply transfers the execution
control.
Let's look at the following example java code.
Java Program
import java.util.Scanner;
public class JavaReturnStatementExample {
int value;
int readValue() {
Scanner read = new Scanner(System.in);
System.out.print("Enter any number: ");
return this.value=read.nextInt();
}
obj.showValue(obj.readValue());
}
}
o/p
Java Classes
Java is an object-oriented programming language, so everything in java program must be based on
the object concept. In a java programming language, the class concept defines the skeleton of an
object.
The java class is a template of an object. The class defines the blueprint of an object. Every class in
java forms a new data type. Once a class got created, we can generate as many objects as we
want. Every class defines the properties and behaviors of an object. All the objects of a class have
the same properties and behaviors that were defined in the class.
Every class of java programming language has the following characteristics.
Look at the following picture to understand the class and object concept.
Creating a Class
In java, we use the keyword class to create a class. A class in java contains
properties as variables and behaviors as methods. Following is the syntax of class in
the java.
Syntax
class <ClassName>{
data members declaration;
methods defination;
}
🔔 The ClassName must begin with an alphabet, and the Upper-case letter is
preferred.
🔔 The ClassName must follow all naming rules.
Creating an Object
In java, an object is an instance of a class. When an object of a class is created, the
class is said to be instantiated. All the objects that are created using a single class
have the same properties and methods. But the value of properties is different for
every object. Following is the syntax of class in the java.
Syntax
Java Methods
A method is a block of statements under a name that gets executes only when it is called. Every
method is used to perform a specific task. The major advantage of methods is code re-usability
(define the code once, and use it many times).
In a java programming language, a method defined as a behavior of an object. That means, every
method in java must belong to a class.
Every method in java must be declared inside a class.
Every method declaration has the following characteristics.
Syntax
class <ClassName>{
<accessSpecifier> <returnType> <methodName>( parameters ){
...
block of statements;
...
}
}
🔔 The methodName must begin with an alphabet, and the Lower-case letter is preferred.
🔔 The methodName must follow all naming rules.
🔔 If you don't want to pass parameters, we ignore it.
🔔 If a method defined with return type other than void, it must contain the return statement,
otherwise, it may be ignored.
Calling a method
In java, a method call precedes with the object name of the class to which it belongs and a dot
operator. It may call directly if the method defined with the static modifier. Every method call must be
made, as to the method name with parentheses (), and it must terminate with a semicolon.
Syntax
<objectName>.<methodName>( actualArguments );
Example
import java.util.Scanner;
public class JavaMethodsExample {
int sNo;
String name;
Scanner read = new Scanner(System.in);
void readData() {
System.out.print("Enter Serial Number: ");
sNo = read.nextInt();
System.out.print("Enter the Name: ");
name = read.next();
}
o/p
Constructor
A constructor is a special method of a class that has the same name as the class name. The
constructor gets executes automatically on object creation. It does not require the explicit method
call. A constructor may have parameters and access specifiers too. In java, if you do not provide any
constructor the compiler automatically creates a default constructor.
Let's look at the following example java code.
Example
ConstructorExample() {
System.out.println("Object created!");
}
public static void main(String[] args) {
o/p
When a class has two or more methods by the same name but different parameters, at the
time of calling based on the parameters passed respective method is called (or respective
method body will be bonded with the calling line dynamically). This mechanism is known as
method overloading.
Example of Method Overloading
If you observe the following example, here we have created a class called Sample and this
class has two methods with the same name (add) and return type, the only difference is the
parameters they accept (one method accepts two integer variables and other accepts three
integer variables).
When you invoke the add() method based on the parameters you pass respective method
body gets executed.
public class Sample {
public static void add(int a, int b) {
System.out.println(a+b);
}
public static void add(int a, int b, int c) {
System.out.println(a+b+c);
}
public static void main(String args[]) {
Sample obj = new Sample();
obj.add(20, 40);
obj.add(40, 50, 60);
}
}
Output
60
150
In method overriding, Super class and subclass have methods with the same name
including parameters. JVM calls the respective method based on the object used to call the
method. In overriding, the return types should also be same.
class SuperClass {
public static void sample() {
System.out.println("Method of the super class");
}
}
public class SubClass extends SuperClass {
public static void sample() {
System.out.println("Method of the sub class");
}
public static void main(String args[]) {
SuperClass obj1 = new SubClass();
SubClass obj2 = new SubClass();
obj1.sample();
obj2.sample();
}
}
Here we have a SuperClass and a SubClass. Both the classes have a method called
Sample() with the same signature. In the main class, we created obj1 for SuperClass and
obj2 for SubClass. The JVM calls the respective method based on the object used to call the
method.
Output
The following table highlights the major differences between Method Overloading and
Method Overriding −
The methods must have different Both the methods must have the same
number of parameters. If both the number of parameters with the same
methods have the same number of type.
parameters, then their type must be
different.
Consider the following Java program, in which we have used different constructors in
the class.
Example
1. public class Student {
2. //instance variables of the class
3. int id;
4. String name;
5.
6. Student(){
7. System.out.println("this a default constructor");
8. }
9.
10. Student(int i, String n){
11. id = i;
12. name = n;
13. }
14.
15. public static void main(String[] args) {
16. //object creation
17. Student s = new Student();
18. System.out.println("\nDefault Constructor values: \n");
19. System.out.println("Student Id : "+s.id + "\nStudent Name : "+s.name);
20.
21. System.out.println("\nParameterized Constructor values: \n");
22. Student student = new Student(10, "David");
23. System.out.println("Student Id : "+student.id + "\nStudent Name : "+student.name);
24. }
25. }
Output:
Student Id : 0
Student Name : null
Student Id : 10
Student Name : David
The access modifiers in Java specifies the accessibility or scope of a field, method, constructor, or
class. We can change the access level of fields, constructors, methods, and class by applying the
access modifier on it.
1. Private: The access level of a private modifier is only within the class. It cannot be accessed
from outside the class.
2. Default: The access level of a default modifier is only within the package. It cannot be
accessed from outside the package. If you do not specify any access level, it will be the
default.
3. Protected: The access level of a protected modifier is within the package and outside the
package through child class. If you do not make the child class, it cannot be accessed from
outside the package.
4. Public: The access level of a public modifier is everywhere. It can be accessed from within the
class, outside the class, within the package and outside the package.
There are many non-access modifiers, such as static, abstract, synchronized, native, volatile, transient,
etc. Here, we are going to learn the access modifiers only.
Private Y N N N
Default Y Y N N
Protected Y Y Y N
Public Y Y Y Y
Example
char[] name = {'J', 'a', 'v', 'a', ' ', 'T', 'u', 't', 'o', 'r', 'i', 'a', 'l', 's'};
//name[14] = '@'; //ArrayIndexOutOfBoundsException
name[5] = '-';
System.out.println(name);
The String class defined in the package java.lang package. The String class
implements Serializable, Comparable, and CharSequence interfaces.
The string created using the String class can be extended. It allows us to add more characters after
its definition, and also it can be modified.
Let's look at the following example java code.
Example
Example
String title = "Java Tutorials"; // Using literals
🔔 The String class constructor accepts both string and character array as an argument.
Return
Method Description Value
equalsIgnoreCase(String) Checks whether two strings are same, ignoring case boolean
Return
Method Description Value
startsWith(String) Checks whether a string starts with the specified string boolean
endsWith(String) Checks whether a string ends with the specified string boolean
indexOf(String) Finds the first index of argument string in object string int
lastIndexOf(String) Finds the last index of argument string in object string int
replace(String, String) Replaces the first string with second string String
replaceAll(String, String) Replaces the first string with second string at all occurrences. String
substring(int, int) Extracts a sub-string from specified start and end index String
values
join(String, String, ...) Joins all strings, first string as delimiter. String
Java Program
public class JavaStringExample {
o/p