Module 1 - OOPS CONCEPTS AND JAVA PROGRAMMING - LectureNotes
Module 1 - OOPS CONCEPTS AND JAVA PROGRAMMING - LectureNotes
Object means a real-world entity such as a pen, chair, table, computer, watch, etc. Object-Oriented
Programming is a methodology or paradigm to design a program using classes and objects. It
simplifies software development and maintenance by providing some concepts:
Object
Class
Abstraction
Encapsulation
Inheritance
Polymorphism
i. Object: Object is an important runtime entity in object oriented method which has state and
behavior. For example, a chair, pen, table, keyboard, bike, etc. It can be physical or logical.
An Object can be defined as an instance of a class. An object contains an address and takes up
some space in memory. Each object holds data and code to operate the data. Object can interact
without having to identify the details of each other‘s data or code. It is sufficient to identify the
type of message received and the type of reply returned by the objects.
Example: A dog is an object because it has states like color, name, breed, etc. as well as
behaviors like wagging the tail, barking, eating, etc.
ii. Classes: A class is a set of objects with similar properties (attributes), common behavior
(operations), and common link to other objects. A class can also be defined as a blueprint from
which you can create an individual object. Class doesn't consume any space. The complete set
of data and code of an object can be made a user defined data type with the help of class. The
objects are variable of type class.
Once the class has been defined, we can make any number of objects belonging to that class.
Each object is related with the data of type class with which they are formed. As we learned
that, the classification of objects into various classes is based on its properties (States) and
behavior (methods). Classes are used to distinguish are type of object from another. The
important thing about the class is to identify the properties and procedures and applicability to
its instances
iii. Data Abstraction: Data abstraction refers to the act of representing important description
without including the background details or explanations (Hiding internal details and showing
functionality). Classes use the concept of abstraction and are defined as a list of abstract
attributes such as size, cost and functions operate on these attributes. They summarize all the
important properties of the objects that are to be created.
Classes use the concepts of data abstraction and it is called as Abstract Data Type (ADT). In
Java, we use abstract class and interface to achieve abstraction.
iv. Data Encapsulation: Data Encapsulation means wrapping of data and functions into a single
unit (i.e. class). It is most useful feature of class. The data is not easy to get to the outside world
and only those functions which are enclosed in the class can access it.
These functions provide the boundary between Object‘s data and program. This insulation of
data from direct access by the program is called as Data hiding.
v. Inheritance: Inheritance is the process by which objects of one class can get the properties of
objects of another class. Inheritance means one class of objects inherits the data and behaviors
from another class. Inheritance maintains the hierarchical classification in which a class inherits
from its parents. Inheritance provides the important feature of OOP that is reusability. That
means we can include additional characteristics to an existing class without modification. This
is possible deriving a new class from existing one. It is used to achieve runtime polymorphism.
Benefits of Inheritance:
Inheritance helps in code reuse. The child class may use the code defined in the parent class
without re-writing it.
Inheritance can save time and effort as the main code need not be written again.
Inheritance provides a clear model structure which is easy to understand.
An inheritance leads to less development and maintenance costs.
With inheritance, we will be able to override the methods of the base class so that the meaningful
implementation of the base class method can be designed in the derived class. An inheritance
leads to less development and maintenance costs.
vi. Polymorphism: It is derived from 2 Greek words: “poly” and “morphs”. The word “poly”
means many and “morphs” means forms. So polymorphism means the ability to take more than
one form. Polymorphism plays a main role in allocate objects having different internal
structures to share the same external interface. It is defined as that allows one interface to access
a general class of actions or same name different operations.
4. Adding new data and functions is not easy. 4. Adding new data and function is easy.
10. Procedural programming is used for 10. Object-oriented programming is used for
designing medium-sized programs. designing large and complex programs.
11. Procedural programming uses the concept 11. Object-oriented programming uses the
of procedure abstraction. concept of data abstraction.
12. Code reusability absent in procedural 12. Code reusability present in object-
programming, oriented programming.
13. Examples: C, FORTRAN, Pascal, Basic, 13. Examples: C++, Java, Python, C#, etc.
etc.
Java is a widely-used programming language for coding web applications. It has been a popular choice
among developers for over two decades, with millions of Java applications in use today. Java is a multi-
platform, object-oriented, and network-centric language that can be used as a platform in itself.
It is used for:
History of JAVA:
1. In 1990, James Gosling was given a task of creating projects to control consumer electronics.
Gosling and his team Mike Sheridan, and Patrick Naughton at Sun Microsystems started designing
their software using C++ because of its Object-oriented nature. Gosling, however, quickly found
that C++ was not suitable for this project. They faced problems due to program bugs like memory
leak, dangling pointer, multiple inheritance and platform dependent.
2. Gosling decided that he would develop his own, simplified computer language to avoid all the
problems faced in C++.
3. Gosling kept the basic syntax and object oriented features of the C++ language to designing a new
language.
4. He completed and named “OAK” in 1991 at Sun Microsystems.
5. Later Sun Microsystems was discovered that the name “OAK” was already claimed, they changed
the name to “JAVA” in 1995.
6. The Java team realized that the language they had developed would be perfect for web programming
because the World Wide Web had transformed the text-based internet into a graphic rich
environment. Then team came up with the concept of web applets, small programs that could be
included in web pages, and even went so far as to create a complete web browser that demonstrate
the language’s power.
7. The new language was quickly embraced as a powerful tool for developing internet applications.
Support for java was added in the Netscape (Web Browser on UNIX) and in the Internet Explorer.
Java programming language is very simple and object oriented. It is easy to learn and taught in
many colleges and universities.
Java applications run inside JVM, and now all major operating systems are able to run Java
including Windows, Mac and UNIX.
Write once, run anywhere: A Java application runs on all Java platforms.
Java is very secure. Only Java applications that have permission can access the resources of the
main computer. Thus, the main computer is protected from virus attackers and hackers.
Java technologies have been improved by community involvement. It is suitable for most types
of applications, especially complex systems that are used widely in network and distributed
computing.
6. Dynamic:
Java loads in classes as they are needed.
JVM is capable of linking dynamic new classes, methods and objects.
7. Compiled and Interpreted:
Java code is compiled to byte code.
Byte code are interpreted on any platform by JVM.
Java programs can be shared over the internet.
8. High Performance:
Byte code are highly optimized.
JVM execute Byte code much faster.
class Example{
public static void main(String[] args)
{
System.out.println("Welcome to JAVA Class!!!");
}
}
Where,
class: class keyword is used to declare classes in Java
public: It is an access specifier. Public means this function is visible to all.
static: static is again a keyword used to make a method static. To execute a static function
you do not have to create an Object of the class. The main() method here is called by JVM,
without creating any object for class.
void: It is the return type, meaning this method will not return anything.
main: main() method is the most important method in a Java program. This is the method
which is executed, hence all the logic must be inside the main() method. If a java class is not
having a main() method, it causes compilation error. Multiple main() methods in the same
class not allowed .
String[] args: This represents an array whose type is String and name is args.
System.out.println: This is used to print anything on the console like printf in C language.
Single-line Comments
Any text between // and the end of the line is ignored by Java (will not be executed).
System.out.println("Hello World");
This example uses a multi-line comment (a comment block) to explain the code:
Example: /* The code below will print the words Hello World
System.out.println("Hello World");
Data types specify the different sizes and values that can be stored in the variable. There are two
types of data types in Java:
1. Primitive data types: The primitive data types include boolean, char, byte, short, int, long,
float and double.
2. Non-primitive data types: The non-primitive data types include Classes, Interfaces,
and Arrays.
1.9 Variable:
A variable is a container which holds the value while the Java program is executed. A variable is
assigned with a data type.
Variable is a name of memory location. There are three types of variables in java: local, instance
and static.
Syntax: type var_name;
Initializing a Variable:
A variable must be declared before to their use. This is necessary because the compiler must know
what type of data or value that can contains it use.
At the time of declaration, we can initialize the value to the variable by using assignment
operator as shownhere:
type var_name = value;
Where, value - is the value that is to var when var is created. Value is known at compile time
Example: int count = 10;
char ch = ‘x’;
flaot f = 1.2F;int a,b = 8;
System.out.println ( y ); // OK
}
enum Color {
RED,
GREEN,
BLUE;
}
public class Test {
// Driver method
public static void main(String[] args)
{
Color c1 = Color.RED;
System.out.println(c1);
}
}
// Driver method
public static void main(String[] args)
{
Color c1 = Color.RED;
System.out.println(c1);
}
}
Output: RED
A Java program to demonstrate working on enum in switch case (Filename Test. Java)
import java.util.Scanner;
// An Enum class
enum Day {
SUNDAY,
MONDAY,
TUESDAY,
WEDNESDAY,
THURSDAY,
FRIDAY,
SATURDAY;
}
// Constructor
public Test(Day day) { this.day = day; }
// Driver method
public static void main(String[] args)
{
String str = "MONDAY";
Test t1 = new Test(Day.valueOf(str));
t1.dayIsLike();
}
}
Output
Mondays are bad.
1.12 Operators:
An operators is a symbol that tells the compiler to perform a specific mathematical, logical or
othermanipulations.
Table: List of operators and example
++ Increment
-- decrement dresult=10.0/3.0;
drem=10.0%3.0;
System.out.println("Result&remainder:"
+iresult + "\t" +irem);
System.out.println("Result&remainder:"
+dresult + "\t" +drem);
}
}
Greater than
System.out.println("NotEqual");
< Less than }
}
>= Greater
thanor
equal to
<= Less than or
equal to
& AND class RelDemo{
public static void main(String[] args){int i=10, j=11;
| OR
XOR(exclusi if(i= =j)
^
veOR) System.out.println("Equal");
Logical
Short- else
|
circuitOR System.out.println("NotEqual");
|
}
Short-circuit }
& AND
&
! NOT
Short Circuit Operator:
Provides Short-Circuit for AND & OR Logical Operators
In AND (&&) – if the first operand is false, the outcome is false no matter what value the second
operand has.
In OR ( | | ) – if the first operand is true, the outcome is true no matter what value the second operand
has.
Example:
class ShrtCirDemo{
public static void main(String[] args){
int n=10, Both expressions are
if(d!=0 &&d=2;
(n%d) == 0) evaluated
System.out.println("Modulus is performed ");
• A short circuit operator is one that doesn't necessarily evaluate all of its operands.
• expr1 && expr2 represents a logical AND operation that employs short-circuiting behavior. That is,
expr2 is not evaluated if expr1 is logical 0 (false).
Note: The difference between the normal (&, |) and short-circuit (&&, ||) versions
The normal operands will always evaluated each operand
The short-circuit version will evaluate the second operand only when necessary.
Shorthand Assignments:
Shorthand assignment operators that simplify the coding of certain assignment statements.
Example: x = x + y; equivalent to x += y;
The operator pair += tells the compiler to assign x the value of x plus 10.
Bitwise Operator:
Bitwise operators are used to test, set, or shift the individual bits that make up a value.
Bitwise operator can be applied to values of type long, int, short, char, or byte.
Bitwise operations cannot be used on Boolean, float or double or class type.
Table: List of Operators and example (continued)
Operators &
Categor Description Example
y Meaning
& class UpLwDemo{
Bit by bit evaluated
Bitwise AND public static void main(String[]args)
| {
Bit by bit evaluated
Bitwise OR char ch;
^ for(int i=0; i<10; i++)
Bit by bit evaluated
Exclusive OR {
>> sign bit is shifted in ch=(char) ('A' + i);
Signed Shift high-order
Bitwise
System.out.print(ch);
right positions.
>>> Zero’s are shifted in
ch=(char) ((int) ch | 32);
Unsigned high-order
System.out.print(ch + " ");
Shift right positions.
Zero’s are shifted in
<< }
Low-order
Left shift }
positions.
}//Uppercase to LowercaseOutput:
~
One’s One’s complement Aa Bb Cc Dd Ee Ff Gg Hh Ii Ji
complement
?: Ternary or
Miscellaneous
b = (a == 1) ? 20: 30;
conditional
instanceof The operator checks
whether the object is String name = "James";
of a particular type boolean result=name instanceof String;
System.out.println( result );
Implicit Type
Explicit Type
Implicit Type:
An implicit conversion means that a value of one type is changed to a value of another type
automatically. Automatic type casting take place when,
The two types are compatible
The target type is larger than the source type.
The lower size is widened to higher size. This is also named as automatic type conversion or
widening.
Explicit Type:
Explicit conversions are done via casting. When you are assigning a larger type value to a variable of
smaller type, then you need to perform explicit type casting. It is called as explicit conversion or
narrowing conversionand there may be data loss in this process because the conversion is forceful.
Syntax: (target-type)expression;
Here, target-type specifies the desired type to convert the specified expression to.
1.14 Expressions
Operators, variables, and literals are components of expressions. Type Conversion in expressions:
• Possible to mix 2 or more compatible different data types.
• they are all converted to the same type.
• Java’s type promotion rules can be used for the conversion in an expression.
Example: 2 + (5.0*2.0) -3;
char ch= (char) (ch1 + ch2);
class ExprDemo{
public static void main(String[] args)
{
byte b;
int i;
b=10;
i = b * b; //No cast needed
b=10;
b=(byte) (b * b); // cast is needed
System.out.println("i= " + i + "b= " +b);
}
}
}
}
Output:
Reading string:
1. InputStreamReader class:
a. Can be used to read data from keyboard.
b. Converts Byte stream to character stream.
Syntax:
InputStreamReader ir=new InputStreamReader(System.in);
2. BufferedReader class:
can be used to read data line by line
Syntax:
3. Scanner class:
The Java Scanner class breaks the input into tokens using a delimiter that is whitespace by default.
It provides many methods to read and parse various primitive values.
Syntax:
class ScannerTest {
public static void main(String args[]){
Output:
At times we want the output of a program to be printed in a given specific format. In the
C programming language this is possible using the printf( ) function. In java there are two methods
that can be used to format the output in Java:
The implementation of this method is very easy as it is similar to the printf( ) function in C
programming.
Example:
import java.text.DecimalFormat ;
// definition of the class
public class FormattedOutput2
{
public static void main( String args[ ] )
{
double x = 123.4567 ;
// printing the number
System.out.printf( " \n The number is : %f \n ", x ) ;
// printing only the numeric part of the floating number
DecimalFormat ft = new DecimalFormat( " #### " ) ;
System.out.println( " \n Without fraction part the number is : " + ft.format( x ) ) ;
// printing the number only upto 2 decimal places
ft = new DecimalFormat( " #.## " ) ;
System.out.println( " \n Formatted number with the specified precision is = " + ft.format( x ) ) ;
// automatically appends zero to the rightmost part of decimal, instead of #, we use digit 0
ft = new DecimalFormat( " #.000000 " ) ;
System.out.println( " \n Appending the zeroes to the right of the number = " + ft.format( x ) ) ;
// automatically appends zero to the leftmost of decimal number instead of #, we use digit 0
ft = new DecimalFormat( " 00000.00 " ) ;
System.out.println( " \n Appending the zeroes to the left of the number = "+ ft.format( x ) ) ;
// formatting money in dollars
double income = 550000.789 ;
ft = new DecimalFormat( " $###,###.## " ) ;
System.out.println( " \n Your Formatted Income in Dollars : " + ft.format( income ) ) ;
}
}
Output:
The number is : 123.456700
Without fraction part the number is : 123
Formatted number with the specified precision is = 123.46
Appending the zeroes to the right of the number = 123.456700
Appending the zeroes to the left of the number = 00123.46
Your Formatted Income in Dollars : $550,000.79
//Statements if(age>18){
}
The Java if statement tests the System.out.print("Age is greater than 18");
condition. It executes if block if }
condition is true.
if(condition){
//Statements int number=13;
if(number%2==0){
2. if-else
}else{
//Statements System.out.println("even number");
} }else{
It executes the if block if condition is System.out.println("odd number");
true otherwise else block is executed.
}
if(condition1){ int age=25,basic=4000,tax = 200;
Statements;
if (age>18) {
3. if-else-if ladder
}else if(condition2){
Statements; System.out.println(“greater”);
} }
... else if (basic > 5000)
else{ sal = basic – tax;
Statements;
else
}
The if-else-if ladder statement executes sal = basic;
one condition from multiple statements.
if (condition){ if Int a=15, b=20, c=18, big;if (a>b){
(condition){ if (a>c) {
4. nested if
Statements; big = a;
} }
} }
You can use one if or else if statement
inside another if or else if statement(s).
switch(expression){
int number=20;
case value1:Statements;
break; switch(number){
5. switch or multiway
} System.out.println(i);i++;
Repeats a statement or group of statements while
}
a given condition is true. It tests the condition
Output: 1 2 3 4 5 6 7 8 9 10
before executing the loop body.
}while(condition); }while(i<=10);
Like a while statement, except that it tests the Output: 1 2 3 4 5 6 7 8 9 10
condition at the end of the loop body.
Statements; }
}
Output: 1 2
Execute a sequence of statements multiple times
and 345678
System.out.println(i);
It continues the current flow of the program }
and skips the remaining code at specified
condition. Output: 1 2 3 4 6 7 8 9 10
In case of inner loop, it continues only inner
loop
Element is: 2
Element is: 3
Element is: 3
return value; boolean isOdd( int num ) { if (
num/2 == 0 )
The return statement exits from the current
method, and control flow returns to where the return false; return true;
method was invoked.
return
}
The return statement has two forms: one that
returns a value, and one that doesn't.
for(int i=1;i<=5;i++){
for(int j=1;j<=i;j++){
System.out.print(j+" ");
}
}
1.19 Java Arrays
Normally, an array is a collection of similar type of elements which has contiguous memory location.
Java array is an object which contains elements of a similar data type. Additionally, The elements of an
array are stored in a contiguous memory location. It is a data structure where we store similar elements.
We can store only a fixed set of elements in a Java array.
Array in Java is index-based, the first element of the array is stored at the 0th index, 2nd element is stored
on 1st index and so on.
Unlike C/C++, we can get the length of the array using the length member. In C/C++, we need to use the
sizeof operator.
Advantages
o Code Optimization: It makes the code optimized, we can retrieve or sort the data efficiently.
o Random access: We can get any data located at an index position.
Disadvantages
o Size Limit: We can store only the fixed size of elements in the array. It doesn't grow its size at runtime. To
solve this problem, collection framework is used in Java which grows automatically.
arrayRefVar=new datatype[size];
Example:
//Java Program to illustrate how to declare, instantiate, initialize and traverse the Java array.
class Testarray{
public static void main(String args[]){
int a[]=new int[5];//declaration and instantiation
a[0]=10;//initialization
a[1]=20;
a[2]=70;
a[3]=40;
a[4]=50;
//traversing array
for(int i=0;i<a.length;i++)//length is the property of array
System.out.println(a[i]);
}}
Output: 10
20
30
40
50
We can declare, instantiate and initialize the java array together by:
Example:
Java Program to illustrate the use of declaration, instantiation and initialization of Java array in a
single line
class Testarray1{
public static void main(String args[]){
int a[]={33,3,4,5};//declaration, instantiation and initialization
//printing array
for(int i=0;i<a.length;i++)//length is the property of array
System.out.println(a[i]);
}
}
Output:
33
3
4
5
We can also print the Java array using for-each loop. The Java for-each loop prints the array elements
one by one. It holds an array element in a variable, then executes the body of the loop.
for(data_type variable:array){
//body of the loop
}
Example: Java Program to print the array elements using for-each loop
class Testarray1{
public static void main(String args[]){
int arr[]={33,3,4,5};
//printing array using for-each loop
for(int i:arr)
System.out.println(i);
}}
Output:
33
3
4
5
We can pass the java array to method so that we can reuse the same logic on any array.
Let's see the simple example to get the minimum number of an array using a method.
class Testarray2{
//creating a method which receives an array as a parameter
static void min(int arr[]){
int min=arr[0];
for(int i=1;i<arr.length;i++)
if(min>arr[i])
min=arr[i];
System.out.println(min);
}
public static void main(String args[]){
int a[]={33,3,4,5};//declaring and initializing an array
min(a);//passing array to method
}}
Output: 3
ArrayIndexOutOfBoundsException
The Java Virtual Machine (JVM) throws an ArrayIndexOutOfBoundsException if length of the array in
negative, equal to the array size or greater than the array size while traversing the array.
Multidimensional Arrays:
Multidimensional arrays are arrays of arrays with each element of the array holding the reference of
other arrays. These are also known as Jagged Arrays. A multidimensional array is created by appending
one set of square brackets ([]) per dimension.
Syntax :
datatype [][] arrayrefvariable;
or
datatype arrayrefvariable[][];
Example: int[][] intArray = new int[10][20]; //a 2D array or matrix
int[][][] intArray = new int[10][20][10]; //a 3D array
Example:
// printing 2D array
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++)
System.out.print(arr[i][j] + " ");
System.out.println();
}
}
}
Output
279
361
742
1.20 Constructors:
In Java, Constructor is a block of codes similar to the method. It is called when an instance of the
class is created. At the time of calling the constructor, memory for the object is allocated in the memory.
It is a special type of method that is used to initialize the object. Every time an object is created using
the new() keyword, at least one constructor is called.
Types of Constructor
In Java, constructors can be divided into 4 types:
1. No-Arg Constructor: If a constructor does not accept any parameters, it is known as a no-
argument constructor.
For example, (ABOVE Program)
2. Parameterized Constructor: A Java constructor can also accept one or more parameters.
Such constructors are known as parameterized constructors (constructor with parameters).
Example:
class Main {
String languages;
// constructor accepting single value
Main(String lang) {
languages = lang;
System.out.println(languages + " Programming Language");
}
public static void main(String[] args) {
// call constructor by passing a single value
Main obj1 = new Main("Java");
Main obj2 = new Main("Python");
Main obj3 = new Main("C");
}
}
Output: Java Programming Language
Python Programming Language
C Programming Language
3. Default Constructor: If we do not create any constructor, the Java compiler automatically create a
no-arg constructor during the execution of the program. This constructor is called default constructor.
Example:
class Main {
int a;
boolean b;
public static void main(String[] args) {
// A default constructor is called
Main obj = new Main();
System.out.println("Default Value:");
System.out.println("a = " + obj.a);
System.out.println("b = " + obj.b);
}
}
Output: Default Value:
a=0
b = false
4. Copy Constructor: In Java, a copy constructor is a special type of constructor that creates an
object using another object of the same Java class. It returns a duplicate copy of an existing object
of the class.
Example:
import java.util.Scanner;
public class EvenOdd
{
public static void main (String args[])
{
//creating Scanner class object
Scanner scan=new Scanner(System.in);
System.out.print("Enter the number: ");
//reading value from user
int num=scan.nextInt();
//method calling
findEvenOdd(num);
}
//user defined method
public static void findEvenOdd(int num)
{
//method body
if(num%2==0)
System.out.println(num+" is even");
else
System.out.println(num+" is odd");
}
}
Static Method
A method that has static keyword is known as static method. In other words, a method that belongs
to a class rather than an instance of a class is known as a static method. We can also create a static method
by using the keyword static before the method name.
The main advantage of a static method is that we can call it without creating an object. It can access
static data members and also change the value of it. It is used to create an instance method. It is invoked
by using the class name. The best example of a static method is the main() method.
Example:
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.
Example:
class Student{
int rollno;
String name;
float fee;
Student(int rollno,String name,float fee){
this.rollno=rollno;
this.name=name;
this.fee=fee;
}
void display(){System.out.println(rollno+" "+name+" "+fee);}
}
class TestThis2{
public static void main(String args[]){
Student s1=new Student(111,"ankit",5000f);
Student s2=new Student(112,"sumit",6000f);
s1.display();
s2.display();
}}
class Adder{
static int add(int a,int b)
{
return a+b;
}
static int add(int a,int b,int c)
{
return a+b+c;
}
}
class TestOverloading1{
public static void main(String[] args){
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(11,11,11));
}}
In Java, we can overload constructors like methods. The constructor overloading can be defined
as the concept of having more than one constructor with different parameters so that every constructor
can perform a different task.
Example:
class Main {
String language;
// constructor with no parameter
Main() {
this.language = "Java";
}
// constructor with a single parameter
Main(String language) {
this.language = language;
}
public void getName() {
System.out.println("Programming Langauage: " + this.language);
}
public static void main(String[] args) {
// call constructor with no parameter
Main obj1 = new Main();
// call constructor with a single parameter
Main obj2 = new Main("Python");
obj1.getName();
obj2.getName();
}
}
Output: Programming Language: Java
Programming Language: Python
Constructors are special methods in Java that Methods are normal functions in Java
are called when an object is created. that can be called on an object or class.
Constructor Overloading Method Overloading
1.25 Recursion:
Example:
public class RecursionExample3 {
static int factorial(int n){
if (n == 1)
return 1;
else
return(n * factorial(n-1));
}
Example:
public class StringExample{
public static void main(String args[]){
String s1="java";//creating string by Java string literal
char ch[]={'s','t','r','i','n','g','s'};
String s2=new String(ch);//converting char array to string
String s3=new String("example");//creating Java string by new keyword
System.out.println(s1);
System.out.println(s2);
System.out.println(s3);
}}
Java String class methods
1 char charAt(int index) It returns char value for the particular index
4 static String format(Locale l, String format, Object... It returns formatted string with given locale.
args)
6 String substring(int beginIndex, int endIndex) It returns substring for given begin index and end
index.
10 boolean equals(Object another) It checks the equality of string with the given
object.
13 String replace(char old, char new) It replaces all occurrences of the specified char
value.
14 String replace(CharSequence old, CharSequence new) It replaces all occurrences of the specified
CharSequence.
15 static String equalsIgnoreCase(String another) It compares another string. It doesn't check case.
17 String[] split(String regex, int limit) It returns a split string matching regex and limit.
20 int indexOf(int ch, int fromIndex) It returns the specified char value index starting
with given index.
22 int indexOf(String substring, int fromIndex) It returns the specified substring index starting with
given index.
28 static String valueOf(int value) It converts given type into string. It is an overloaded
method.