Unit-2[Oop Using Java]-Dh Sirs Classroom
Unit-2[Oop Using Java]-Dh Sirs Classroom
LEARNING MATERIALS
Department : Computer Science & Technology Semester : Fourth (4 th )
__________________________________________________________________________
Content:
2.1 Primitive Data Types: Integers, Floating Point type, Characters, Booleans etc
2.12 Creation, concatenation and conversion of a string, changing case of string, character extraction, String Comparison, String Buffer
2.13 Different Operators: Arithmetic, Bitwise, Rational, Logical, Assignment, Conditional, Ternary, Increment and Decrement, Mathematical Functions
2.14 Decision & Control Statements: Selection Statement (if, if...else, switch), Loops(while, do-while, for), Jump statements (break,
continue, return & exit)
OOP Concepts
o Object
Object
Any entity that has state and behavior is known as an object. For example: chair, pen, table,
keyboard, bike etc. It can be physical and logical.
Class
Inheritance
When one object acquires all the properties and behaviours of parent objecti.e. known as
inheritance. It provides code reusability. It is used to achieve runtime polymorphism.
Polymorphism
When one task is performed by different ways i.e. known as polymorphism. For example: to
convince the customer differently, to draw something e.g. shape or rectangle etc.
Another example can be to speak something e.g. cat speaks meaw, dog barks woof etc.
Abstraction
Hiding internal details and showing functionalityis known as abstraction. For example: phone
call, we don't know the internal processing.
Encapsulation
Binding (or wrapping) code and data together into a single unit is known as encapsulation.
For example: capsule, it is wrapped with different medicines.
A java class is the example of encapsulation. Java bean is the fully encapsulated class because all the
data members are private here.
code exists in two related classes, the hierarchy can usually be refactored to move the
Inheritance can also make application code more flexible to change because
classesthat inherit from a common superclass can be used interchangeably. If the return type of a
method issuperclass
Reusability- facility to use public methods of base class without rewriting thesame.
Extensibility- extending the base class logic as per business logic of the derivedclass.
Data hiding- base class can decide to keep some data private so that it cannotbe
altered by the derived class
The history of java starts from Green Team. Java team members (also known
as Green Team), initiated a revolutionary task to develop a language for digital
devices such as set-top boxes, televisionsetc.
For the green team members, it was an advance concept at that time. But, it was
suited for internet programming. Later, Java technology as incorporated by
Netscape.
3) Firstly, it was called "Greentalk" by James Gosling and file extension was.gt.
4) After that, it was called Oak and was developed as a part of the Green
project.
There are many java versions that has been released. Current stable release of Java is Java SE 8.
1. Simple
2. Object-Oriented
3. Portable
4. Platform independent
5. Secured
6. Robust
7. Architecture neutral
8. Dynamic
9. Interpreted
10.High Performance
11.Multithreaded
12.Distributed
What is Java?
Java is a high-level, general-purpose, object-oriented, and secure programming language developed by James
Gosling at Sun Microsystems, Inc. in 1991. It is formally known as OAK. In 1995, Sun Microsystem changed
the name to Java. In 2009, Sun Microsystem takeover by Oracle Corporation.
Editions of Java
Each edition of Java has different capabilities. There are three editions of Java:
Java Standard Editions (JSE): It is used to create programs for a desktop computer.
Java Enterprise Edition (JEE): It is used to create large programs that run on the server and manages
heavy traffic and complex transactions.
Java Micro Edition (JME): It is used to develop applications for small devices such as set-top boxes,
phone, and appliances.
Web Applications: An applications that run on the server is called web applications. We use JSP,
Servlet, Spring, and Hibernate technologies for creating web applications.
Mobile Applications: Java ME is a cross-platform to develop mobile applications which run across
smartphones. Java is a platform for App Development in Android.
Java Comments
The java comments are statements that are not executed by the compiler and interpreter. The
comments can be used to provide information or explanation about the variable, method, class
or any statement. It can also be used to hide program code for specific time.
1. Single LineComment
2. Multi LineComment
3. DocumentationComment
Syntax:
Example:
public classCommentExample1 {
public static voidmain(String[] args)
{inti=10;//Here, i is a
variableSystem.out.println(i);
}
}
Output:
10
Syntax:
/*
This
is
multi line
comment
*/
Example:
public classCommentExample2 {
public static voidmain(String[] args) {
/* Let's declare and print
variable in java.*/
inti=10;
System.out.println(i);
}}
Output:
10
Java Documentation Comment
The documentation comment is used to create documentation API. To create documentation API, you
need to usejavadoc tool.
Syntax:
/**
This
is
documentatio
n comment
*/
Example:
/** The Calculator class provides methods to get addition and subtraction of given 2 numbers.*/
public classCalculator {
/** The add() method returns addition of given numbers.*/
public static int add(int a,int b){return a+b;}
/** The sub() method returns subtraction of given numbers.*/
public static int sub(int a,int b){return a-b;}
}
javac Calculator.java
javadoc Calculator.java
Now, there will be HTML files created for your Calculator class in the current directory. Open the HTML
files and see the explanation of Calculator class provided through documentation comment.
Data Types
Data types represent the different values to be stored in the variable. In java, there are two types of data types:
o Primitive datatypes
o Non-primitive datatypes
float f1 = 234.5f
1. double d1 = 12.3
byte 0 1 byte
short 0 2 byte
int 0 4 byte
long 0L 8 byte
}}
Output:20
Variable is a name of memory location. There are three types of variables in java: local, instance and
static.
There are two types of data types in java: primitive and non-primitive.
Types of Variable
o local variable
o instance variable
o static variable
1) Local Variable
A variable which is declared inside the class but outside the method, is called instance variable . It is not
declared as static.
3) Static variable
A variable that is declared as static is called static variable. It cannot be local.
classA{
int data=50;//instance variable
static int m=100;//static variable
voidmethod(){
intn=90;//local variable
}//end of class
Constants in Java
A constant is a variable which cannot have its value changed after declaration. It uses the'final' keyword.
Syntax
modifierfinaldataType variableName = value;//global constant
Java Variables
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.
There are two types of data types in Java
: primitive and non-primitive.
Variable
A variable is the name of a reserved area allocated in memory. In other words, it is a name of the memory
location. It is a combination of "vary + able" which means its value can be changed.
int data=50;//Here data is variable
Types of Variables
There are three types of variables in Java
:
local variable
instance variable
static variable
1) Local Variable
A variable declared inside the body of the method is called local variable. You can use this variable only within
that method and the other methods in the class aren't even aware that the variable exists.
A local variable cannot be defined with "static" keyword.
2) Instance Variable
A variable declared inside the class but outside the body of the method, is called an instance variable. It is not
declared as static
.
It is called an instance variable because its value is instance-specific and is not shared among instances.
3) Static variable
A variable that is declared as static is called a static variable. It cannot be local. You can create a single copy of
the static variable and share it among all the instances of the class. Memory allocation for static variables
happens only once when the class is loaded in the memory.
Example to understand the types of variables in java
public class A
{
static int m=100;//static variable
void method()
{
int n=90;//local variable
}
public static void main(String args[])
{
int data=50;//instance variable
}
}//end of class
1.abstract
: Java abstract keyword is used to declare an abstract class. An abstract class can provide the
implementation of the interface. It can have abstract and non-abstract methods.
2.boolean:
Java boolean keyword is used to declare a variable as a boolean type. It can hold True and False
values only.
3.break
: Java break keyword is used to break the loop or switch statement. It breaks the current flow of
the program at specified conditions.
4.byte
: Java byte keyword is used to declare a variable that can hold 8-bit data values.
5.case
: Java case keyword is used with the switch statements to mark blocks of text.
6.catch
: Java catch keyword is used to catch the exceptions generated by try statements. It must be used
after the try block only.
7.char
: Java char keyword is used to declare a variable that can hold unsigned 16-bit Unicode characters
8.class
9.continue
: Java continue keyword is used to continue the loop. It continues the current flow of the program
and skips the remaining code at the specified condition.
10.default
: Java default keyword is used to specify the default block of code in a switch statement.
11.do
: Java do keyword is used in the control statement to declare a loop. It can iterate a part of the
program several times.
12.double
: Java double keyword is used to declare a variable that can hold 64-bit floating-point number.
13.else
14.enum
: Java enum keyword is used to define a fixed set of constants. Enum constructors are always
private or default.
15.extends
: Java extends keyword is used to indicate that a class is derived from another class or interface.
16.final
: Java final keyword is used to indicate that a variable holds a constant value. It is used with a
variable. It is used to restrict the user from updating the value of the variable.
17.finally
: Java finally keyword indicates a block of code in a try-catch structure. This block is always
executed whether an exception is handled or not.
18.float
: Java float keyword is used to declare a variable that can hold a 32-bit floating-point number.
19.for
: Java for keyword is used to start a for loop. It is used to execute a set of instructions/functions
repeatedly when some condition becomes true. If the number of iteration is fixed, it is
recommended to use for loop.
20.if
: Java if keyword tests the condition. It executes the if block if the condition is true.
21.implements
: Java import keyword makes classes and interfaces available and accessible to the current source
code.
23.instanceof
: Java instanceof keyword is used to test whether the object is an instance of the specified class or
implements an interface.
24.int
: Java int keyword is used to declare a variable that can hold a 32-bit signed integer.
25.interface
: Java interface keyword is used to declare an interface. It can have only abstract methods.
26.long
: Java long keyword is used to declare a variable that can hold a 64-bit integer.
27.native: Java native keyword is used to specify that a method is implemented in native code
using JNI (Java Native Interface).
28.new
29.null
: Java null keyword is used to indicate that a reference does not refer to anything. It removes the
garbage value.
30.package
: Java package keyword is used to declare a Java package that includes the classes.
31.private
: Java private keyword is an access modifier. It is used to indicate that a method or variable may
be accessed only in the class in which it is declared.
32.protected
: Java protected keyword is an access modifier. It can be accessible within the package and
outside the package but through inheritance only. It can't be applied with the class.
33.public
: Java public keyword is an access modifier. It is used to indicate that an item is accessible
anywhere. It has the widest scope among all other modifiers.
34.return
: Java return keyword is used to return from a method when its execution is complete.
35.short
: Java short keyword is used to declare a variable that can hold a 16-bit integer.
36.static
: Java static keyword is used to indicate that a variable or method is a class method. The static
keyword in Java is mainly used for memory management.
37.strictfp
38.super
: Java super keyword is a reference variable that is used to refer to parent class objects. It can be
used to invoke the immediate parent class method.
39.switch
: The Java switch keyword contains a switch statement that executes code based on test value. The
switch statement tests the equality of a variable against multiple values.
40.synchronized
: Java synchronized keyword is used to specify the critical sections or methods in multithreaded
code.
41.this
: Java this keyword can be used to refer the current object in a method or constructor.
42.throw
: The Java throw keyword is used to explicitly throw an exception. The throw keyword is mainly
used to throw custom exceptions. It is followed by an instance.
43.throws
: The Java throws keyword is used to declare an exception. Checked exceptions can be propagated
with throws.
44.transient
: Java transient keyword is used in serialization. If you define any data member as transient, it will
not be serialized.
45.try
: Java try keyword is used to start a block of code that will be tested for exceptions. The try block
must be followed by either catch or finally block.
46.void: Java void keyword is used to specify that a method does not have a return value.
47.volatile
: Java volatile keyword is used to indicate that a variable may change asynchronously.
48.while
: Java while keyword is used to start a while loop. This loop iterates a part of the program several
times. If the number of iteration is not fixed, it is recommended to use the while loop.
operators in java
Operatorin 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 UnaryOperator,
o ArithmeticOperator,
o shiftOperator,
o RelationalOperator,
o BitwiseOperator,
o LogicalOperator,
o Ternary Operatorand
o AssignmentOperator.
Operators Hierarchy
Java Unary Operator
The Java unary operators require only one operand. Unary operators are used to perform various
operations i.e.:
incrementing/decrementing a value by one
negating an expression
50
2
1. public OperatorExample{
2. public static void main(String args[]){
3. System.out.println(10>>2);//10/2^2=10/4=2
4. System.out.println(20>>2);//20/2^2=20/4=5
5. System.out.println(20>>3);//20/2^3=20/8=2
6. }}
Output:
2
5
2
true
true
10
true
11
Expressions
Expressions are essential building blocks of any Java program, usually created to produce a new
value, although sometimes an expression simply assigns a value to a variable. Expressions are built
using values,variables, operators and method calls.
Types of Expressions
While an expression frequently produces a result, it doesn't always. There are three types of
expressions in Java:
For Example, in java the numeric data types are compatible with each other but no automatic
conversion is supported from numeric type to char or boolean. Also, char and boolean are not
compatible with each other.
This is useful for incompatible data types where automatic conversion cannot bedone.
Here, target-type specifies the desired type to convert the specified valueto.
Java Enum
It can be used for days of the week (SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY
and SATURDAY) , directions (NORTH, SOUTH, EAST and WEST)
etc. The java enum constants are static and final implicitly. It is available from JDK 1.5. Java
Output:
WINTER
SPRINGSUMMER
FALL
The control flow statements in Java allow you to run or skip blocks of code when special
conditions are met.
if(condition) {
// execute this code
}
The condition is Boolean. Boolean means it may be true or false. For example you may put a
mathematical equation as condition. Look at this full example:
Java Control Statements | Control Flow in Java
Java compiler executes the code from top to bottom. The statements in the code are executed according to
the order in which they appear. However, Java provides statements that can be used to control the flow of
Java code. Such statements are called control flow statements. It is one of the fundamental features of Java,
which provides a smooth flow of program.
Java provides three types of control flow statements.
if statements
switch statement
2.Loop statements
while loop
for loop
for-each loop
3.Jump statements
break statement
continue statement
Decision-Making statements:
As the name suggests, decision-making statements decide which statement to execute and when. Decision-
making statements evaluate the Boolean expression and control the program flow depending upon the result
of the condition provided. There are two types of decision-making statements in Java, i.e., If statement and
switch statement.
1) If Statement:
In Java, the "if" statement is used to evaluate a condition. The control of the program is diverted depending
upon the specific condition. The condition of the If statement gives a Boolean value, either true or false. In
Java, there are four types of if-statements given below:
1.Simple if statement
2.if-else statement
3.if-else-if ladder
4.Nested if-statement
Let's understand the if-statements one by one.
1) Simple if statement:
It is the most basic statement among all control flow statements in Java. It evaluates a Boolean expression
and enables the program to enter a block of code if the expression evaluates to true.
Syntax of if statement is given below.
1. if(condition) {
2. statement 1; //executes when condition is true
3. }
Consider the following example in which we have used the if statement in the java code.
Student.java
Student.java
2) if-else statement
The if-else statement is an extension to the if-statement, which uses another block of code, i.e., else block.
The else block is executed if the condition of the if-block is evaluated as false.
Syntax:
1. if(condition) {
2. statement 1; //executes when condition is true
3. }
4. else{
5. statement 2; //executes when condition is false
6. }
Consider the following example.
Student.java
1. public class Student {
2. public static void main(String[] args) {
3. int x = 10;
4. int y = 12;
5. if(x+y < 10) {
6. System.out.println("x + y is less than 10");
7. } else {
8. System.out.println("x + y is greater than 20");
9. }
10. }
11. }
Output:
x + y is greater than 20
3) if-else-if ladder:
The if-else-if statement contains the if-statement followed by multiple else-if statements. In other words, we
can say that it is the chain of if-else statements that create a decision tree where the program may enter in the
block of code where the condition is true. We can also define an else statement at the end of the chain.
Syntax of if-else-if statement is given below.
1. if(condition 1) {
2. statement 1; //executes when condition 1 is true
3. }
4. else if(condition 2) {
5. statement 2; //executes when condition 2 is true
6. }
7. else {
8. statement 2; //executes when all the conditions are false
9. }
Consider the following example.
Student.java
4. Nested if-statement
In nested if-statements, the if statement can contain a if or if-else statement inside another if or else-if
statement.
Syntax of Nested if-statement is given below.
1. if(condition 1) {
2. statement 1; //executes when condition 1 is true
3. if(condition 2) {
4. statement 2; //executes when condition 2 is true
5. }
6. else{
7. statement 2; //executes when condition 2 is false
8. }
9. }
Consider the following example.
Student.java
Switch Statement:
In Java, Switch statements are similar to if-else-if statements. The switch statement contains multiple blocks
of code called cases and a single case is executed based on the variable which is being switched. The switch
statement is easier to use instead of if-else-if statements. It also enhances the readability of the program.
Points to be noted about switch statement:
The case variables can be int, short, byte, char, or enumeration. String type is also supported since
version 7 of Java
Default statement is executed when any of the case doesn't match the value of expression. It is
optional.
Break statement terminates the switch block when the condition is satisfied.
It is optional, if not used, next case is executed.
While using switch statements, we must notice that the case expression will be of the same type as
the variable. However, it will also be a constant value.
The syntax to use the switch statement is given below.
1. switch (expression){
2. case value1:
3. statement1;
4. break;
5. .
6. .
7. .
8. case valueN:
9. statementN;
10. break;
11. default:
12. default statement;
13. }
Consider the following example to understand the flow of the switch statement.
Student.java
Loop Statements
In programming, sometimes we need to execute the block of code repeatedly while some condition evaluates
to true. However, loop statements are used to execute the set of instructions in a repeated order. The
execution of the set of instructions depends upon a particular condition.
In Java, we have three types of loops that execute similarly. However, there are differences in their syntax
and condition checking time.
1.for loop
2.while loop
3.do-while loop
Let's understand the loop statements one by one.
Consider the following example to understand the proper functioning of the for loop in java.
Calculation.java
Java
C
C++
Python
JavaScript
1. while(condition){
2. //looping statements
3. }
0
2
4
6
8
10
1. do
2. {
3. //statements
4. } while (condition);
Consider the following example to understand the functioning of the do-while loop in Java.
Calculation.java
Game.play();
}}
2. Make sure your code is compiled, and that you have tested it thoroughly.
3. If you're using Windows, you will need to set your path to include
Java, if you haven't done so already. This is a delicate operation. Open
Explorer, and look inside C:\ProgramFiles\Java, and you should see some
version of the JDK. Open this folder, and then open the bin folder. Select
the complete path from the top of the Explorer window, and press Ctrl-C
to copyit.
Next, find the "My Computer" icon (on your Start menu or desktop), right-click it, and select
properties. Click on the Advanced tab, and then click on the Environment variables button. Look
at the variables listed for all users, and click on the Path variable. Do not delete the contents of
this variable! Instead, edit the contents by moving the cursor to the right end, entering a
semicolon (;), and pressing Ctrl-V to paste the path you copied earlier. Then go ahead and save
your changes. (If you have any Cmd windows open, you will need to close them.)
cd Desktop
cd ..
Every time you change to a new directory, list the contents of that directory to see where to go
next. Continue listing and changing directories until you reach the directory that contains
9. If you compiled your program using Java 1.6, but plan to run it on a Mac, you'll
needto recompile your code from the command line, bytyping:
10. Now we'll create a single JAR file containing all of the files needed to run yourprogram.
1. class DemoFile
2. {
3. public static void main(String args[])
4. {
5. System.out.println("Hello!");
6. System.out.println("Java");
7. }
8. }
Step 2:
Step 4:
Use the following command to compile the Java program. It generates a .class file in the same folder. It
also shows an error if any.
1. javac DemoFile.java
Step 5:
Use the following command to run the Java program:
1. java DemoFile
Java vs JavaScript
Java is an object-oriented, general purpose programming language (though it is not entirely object-
oriented as it contains primitive types). Java codes are platform-independent, meaning java codes can run
on any platform which is supporting Java. There is no need for re-compilation of code. Java has become
one of the most used languages for client-server applications. Java code are converted to bytecode which
runs on the Java Virtual Machine (JVM) irrespective of the computer architecture.
Java was initially developed by James Gosling. He developed it at Sun Microsystems which got later
acquired by Oracle. Java was first released in 1995. The latest versions in use are java 11 and Java 12.
Features of Java
The main reason why Java came into existence was that the previously used C++ was a bit cumbersome
and not very feasible for client-server applications.
Following are the features of Java:
Memory allocation takes place at run-time that is why a java program can be compiled even
without the main function.
It is platform independent, which is one of the most significant features of Java. The Java codes
are not compiled directly, they are first converted to a bytecode which can be run on any platform
which has JVM.
Java is an interpreted language which means that the Java code compiles and runs simultaneously.
Features of JavaScript
JavaScript is a versatile scripting language used in both server-side as well as client-side
technologies.
It forms basis to many web frameworks like Node.JS, Angular.JS, and React.JS etc.
JavaScript is a case-sensitive language that means, if it has two members with same name but
different case, then they will be considered different and also there is a special schema for declaring
variable names.
Java is a standalone language which means it does JavaScript is contained in web pages and is
not require any other thing to be embedded in. embedded in HTML content.
When facing concurrency, then Java uses thread JavaScript uses event based approach to tackle
based approach to solve it. concurrency.
Java is vividly used for Android application JavaScript is vividly used for web
development development.
The Java IDE or Integrated Development Environment provides considerable support for the application development process.
Through using them, we can save time and effort and set up a standard development process for the team or company. Eclipse,
NetBeans, IntelliJ IDEA, and many other IDE's are most popular in the Java IDE's that can be used according to our
requirements. In this topic, we will discuss the best Java IDE's that are used by the users.
Eclipse
NetBeans
IntelliJ IDEA
BlueJ
JCreator
JDeveloper
MyEclipse
Greenfoot
DrJava
Xcode
Codenvy
Difference between JDK, JRE, and JVM
We must understand the differences between JDK, JRE, and JVM before proceeding further to Java. See
the brief overview of JVM here.
If you want to get the detailed knowledge of Java Virtual Machine, move to the next page. Firstly, let's see
the differences between the JDK, JRE, and JVM.
JVM
JVM (Java Virtual Machine) is an abstract machine. It is called a virtual machine because it doesn't
physically exist. It is a specification that provides a runtime environment in which Java bytecode can be
executed. It can also run those programs which are written in other languages and compiled to Java
bytecode.
JVMs are available for many hardware and software platforms. JVM, JRE, and JDK are platform
dependent because the configuration of each OS is different from each other. However, Java is platform
independent. There are three notions of the JVM: specification, implementation, and instance.
The JVM performs the following main tasks:
Loads code
Verifies code
Executes code
JRE
JRE is an acronym for Java Runtime Environment. It is also written as Java RTE. The Java Runtime
Environment is a set of software tools which are used for developing Java applications. It is used to
provide the runtime environment. It is the implementation of JVM. It physically exists. It contains a set of
libraries + other files that JVM uses at runtime.
The implementation of JVM is also actively released by other companies besides Sun Micro Systems.
JDK
JDK is an acronym for Java Development Kit. The Java Development Kit (JDK) is a software
development environment which is used to develop Java applications and applets. It physically exists. It
contains JRE + development tools.
JDK is an implementation of any one of the below given Java Platforms released by Oracle Corporation:
C++ vs Java
There are many differences and similarities between the C++ programming language and Java. A list of
top differences between C++ and Java are given below:
Call by Value and Call by C++ supports both call by Java supports call by value only.
reference value and call by reference. There is no call by reference in java.
Note
Java does not support header files like C++. Java uses the import keyword to include different
classes and methods.
JVM (Java Virtual Machine) Architecture
JVM (Java Virtual Machine) is an abstract machine. It is a specification that provides runtime environment
in which java bytecode can be executed.
JVMs are available for many hardware and software platforms (i.e. JVM is platform dependent).
What is JVM
It is:
1.A specification where working of Java Virtual Machine is specified. But implementation
provider is independent to choose the algorithm. Its implementation has been provided by Oracle
and other companies.
3.Runtime Instance Whenever you write java command on the command prompt to run the java
class, an instance of JVM is created.
What it does
The JVM performs following operation:
Loads code
Verifies code
Executes code
Memory area
Register set
Garbage-collected heap
JVM Architecture
Let's understand the internal architecture of JVM. It contains classloader, memory area, execution engine
etc.
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.
In Java, array is an object of a dynamically generated class. Java array inherits the Object class, and
implements the Serializable as well as Cloneable interfaces. We can store primitive values or objects in an
array in Java. Like C/C++, we can also create single dimentional or multidimentional arrays in Java.
Moreover, Java provides the feature of anonymous arrays which is not available in C/C++.
Advantages
Code Optimization: It makes the code optimized, we can retrieve or sort the data efficiently.
Disadvantages
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.
Multidimensional Array
1. arrayRefVar=new datatype[size];
1. for(data_type variable:array){
2. //body of the loop
3. }
Let us see the example of print the elements of Java array using the for-each loop.
1. //Java Program to print the array elements using for-each loop
2. class Testarray1{
3. public static void main(String args[]){
4. int arr[]={33,3,4,5};
5. //printing array using for-each loop
6. for(int i:arr)
7. System.out.println(i);
8. }}
Output:
33
3
4
5
Output:
3
Anonymous Array in Java
Java supports the feature of an anonymous array, so you don't need to declare the array while passing an
array to the method.
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.
Output:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4
at TestArrayException.main(TestArrayException.java:5)
50
60
70
80
1. arr[0][0]=1;
2. arr[0][1]=2;
3. arr[0][2]=3;
4. arr[1][0]=4;
5. arr[1][1]=5;
6. arr[1][2]=6;
7. arr[2][0]=7;
8. arr[2][1]=8;
9. arr[2][2]=9;
Output:
1 2 3
2 4 5
4 4 5
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
PROGRAMMING PROBLEMS
1. ARRAY 1
2. 1 2 3 4 5
3.
4. ARRAY 2
5. 1 2 3 4 5
Algorithm
STEP 1: START
Program:
1. public class CopyArray {
2. public static void main(String[] args) {
3. //Initialize array
4. int [] arr1 = new int [] {1, 2, 3, 4, 5};
5. //Create another array arr2 with size of arr1
6. int arr2[] = new int[arr1.length];
7. //Copying all elements of one array into another
8. for (int i = 0; i < arr1.length; i++) {
9. arr2[i] = arr1[i];
10. }
11. //Displaying elements of array arr1
12. System.out.println("Elements of original array: ");
13. for (int i = 0; i < arr1.length; i++) {
14. System.out.print(arr1[i] + " ");
15. }
16.
17. System.out.println();
18.
19. //Displaying elements of array arr2
20. System.out.println("Elements of new array: ");
21. for (int i = 0; i < arr2.length; i++) {
22. System.out.print(arr2[i] + " ");
23. }
24. }
25. }
Output:
Elements of original array
1 2 3 4 5
Elements of new array:
1 2 3 4 5
1. 1 2 8 3 2 2 2 5 1
In the given array, 1 has appeared two times so its frequency be 2 and 2 has appeared four times so have
frequency 4 and so on.
Algorithm
STEP 1: START
Program:
1. public class Frequency {
2. public static void main(String[] args) {
3. //Initialize array
4. int [] arr = new int [] {1, 2, 8, 3, 2, 2, 2, 5, 1};
5. //Array fr will store frequencies of element
6. int [] fr = new int [arr.length];
7. int visited = -1;
8. for(int i = 0; i < arr.length; i++){
9. int count = 1;
10. for(int j = i+1; j < arr.length; j++){
11. if(arr[i] == arr[j]){
12. count++;
13. //To avoid counting same element again
14. fr[j] = visited;
15. }
16. }
17. if(fr[i] != visited)
18. fr[i] = count;
19. }
20.
21. //Displays the frequency of each element present in array
22. System.out.println("---------------------------------------");
23. System.out.println(" Element | Frequency");
24. System.out.println("---------------------------------------");
25. for(int i = 0; i < fr.length; i++){
26. if(fr[i] != visited)
27. System.out.println(" " + arr[i] + " | " + fr[i]);
28. }
29. System.out.println("----------------------------------------");
30. }}
Output:
----------------------------------------
Element | Frequency
----------------------------------------
1 | 2
2 | 4
8 | 1
3 | 1
5 | 1
----------------------------------------
In the above array, the first duplicate will be found at the index 4 which is the duplicate of the element (2)
present at index 1. So, duplicate elements in the above array are 2, 3 and 8.
Algorithm
STEP 1: START
STEP 8: END
Program:
1. public class DuplicateElement {
2. public static void main(String[] args) {
3. //Initialize array
4. int [] arr = new int [] {1, 2, 3, 4, 2, 7, 8, 8, 3};
5. System.out.println("Duplicate elements in given array: ");
6. //Searches for duplicate element
7. for(int i = 0; i < arr.length; i++) {
8. for(int j = i + 1; j < arr.length; j++) {
9. if(arr[i] == arr[j])
10. System.out.println(arr[j]);
11. }
12. }
13. }
14. }
Output:
Duplicate elements in given array:
2
3
8
In the above array, initially, max will hold the value 25. In the 1st iteration, max will be compared with 11,
since 11 is less than max. Max will retain its value. In the next iteration, it will be compared to 7, 7 is also
less than max, no change will be made to the max. Now, max will be compared to 75. 75 is greater than max
so that max will hold the value of 75. Continue this process until the end of the array is reached. At the end
of the loop, max will hold the largest element in the array.
Algorithm
1.STEP 1: START
8.STEP 8: END
Program:
1. public class LargestElement_array {
2. public static void main(String[] args) {
3.
4. //Initialize array
5. int [] arr = new int [] {25, 11, 7, 75, 56};
6. //Initialize max with first element of array.
7. int max = arr[0];
8. //Loop through the array
9. for (int i = 0; i < arr.length; i++) {
10. //Compare elements of array with max
11. if(arr[i] > max)
12. max = arr[i];
13. }
14. System.out.println("Largest element present in given array: " + max);
15. }
16. }
Output:
Largest element present in given array: 75
Algorithm
STEP 1: START
Program:
1. public class SortAsc {
2. public static void main(String[] args) {
3.
4. //Initialize array
5. int [] arr = new int [] {5, 2, 8, 7, 1};
6. int temp = 0;
7.
8. //Displaying elements of original array
9. System.out.println("Elements of original array: ");
10. for (int i = 0; i < arr.length; i++) {
11. System.out.print(arr[i] + " ");
12. }
13.
14. //Sort the array in ascending order
15. for (int i = 0; i < arr.length; i++) {
16. for (int j = i+1; j < arr.length; j++) {
17. if(arr[i] > arr[j]) {
18. temp = arr[i];
19. arr[i] = arr[j];
20. arr[j] = temp;
21. }
22. }
23. }
24.
25. System.out.println();
26.
27. //Displaying elements of array after sorting
28. System.out.println("Elements of array sorted in ascending order: ");
29. for (int i = 0; i < arr.length; i++) {
30. System.out.print(arr[i] + " ");
31. }
32. }
33. }
Output:
Elements of original array:
5 2 8 7 1
Elements of array sorted in ascending order:
1 2 5 7 8
Subtraction of two matrices can be performed by looping through the first and second matrix. Calculating
the difference between their corresponding elements and store the result in the third matrix.
Algorithm
STEP 1: START
Program:
1. public class Sub_Matrix
2. {
3. public static void main(String[] args) {
4. int rows, cols;
5.
6. //Initialize matrix a
7. int a[][] = {
8. {4, 5, 6},
9. {3, 4, 1},
10. {1, 2, 3}
11. };
12.
13. //Initialize matrix b
14. int b[][] = {
15. {2, 0, 3},
16. {2, 3, 1},
17. {1, 1, 1}
18. };
19.
20. //Calculates number of rows and columns present in given matrix
21. rows = a.length;
22. cols = a[0].length;
23.
24. //Array diff will hold the result
25. int diff[][] = new int[rows][cols];
26.
27. //Performs subtraction of matrices a and b. Store the result in matrix diff
28. for(int i = 0; i < rows; i++){
29. for(int j = 0; j < cols; j++){
30. diff[i][j] = a[i][j] - b[i][j];
31. }
32. }
33.
34. System.out.println("Subtraction of two matrices: ");
35. for(int i = 0; i < rows; i++){
36. for(int j = 0; j < cols; j++){
37. System.out.print(diff[i][j] + " ");
38. }
39. System.out.println();
40. }
41. }
42. }
Output:
Subtraction of two matrices:
1 5 3
1 1 0
0 1 2
Java String
In Java, string is basically an object that represents sequence of char values. An array of characters works same as
Java string. For example:
1. char[] ch={'j','a','v','a','t','p','o','i','n','t'};
2. String s=new String(ch);
is same as:
1. String s="javatpoint";
Java String class provides a lot of methods to perform operations on strings such as compare(), concat(),
equals(), split(), length(), replace(), compareTo(), intern(), substring() etc.
The java.lang.String class implements Serializable, Comparable and CharSequence interfaces
.
CharSequence Interface
The CharSequence interface is used to represent the sequence of characters. String, StringBuffer
and StringBuilder
classes implement it. It means, we can create strings in Java by using these three classes.
The Java String is immutable which means it cannot be changed. Whenever we change any string, a new
instance is created. For mutable strings, you can use StringBuffer and StringBuilder classes.
We will discuss immutable string later. Let's first understand what String in Java is and how to create the
String object.
1) String Literal
Java String literal is created by using double quotes. For Example:
1. String s="welcome";
Each time you create a string literal, the JVM checks the "string constant pool" first. If the string already
exists in the pool, a reference to the pooled instance is returned. If the string doesn't exist in the pool, a new
string instance is created and placed in the pool. For example:
1. String s1="Welcome";
2. String s2="Welcome";//It doesn't create a new instance
In the above example, only one object will be created. Firstly, JVM will not find any string object with the
value "Welcome" in string constant pool that is why it will create a new object. After that it will find the
string with the value "Welcome" in the pool, it will not create a new object but will return the reference to
the same instance.
Note: String objects are stored in a special memory area known as the "string constant pool".
2) By new keyword
1. String s=new String("Welcome");//creates two objects and one reference variable
In such case, JVM
will create a new string object in normal (non-pool) heap memory, and the literal "Welcome" will be placed in the
string constant pool. The variable s will refer to the object in a heap (non-pool).
Java String Example
StringExample.java
4 static String format(Locale l, String format, Object... args) It returns formatted string with given locale.
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.
Syntax
Internal implementation
Let's see the example of the charAt() method where we are passing a greater index value. In such a case, it
throws StringIndexOutOfBoundsException at run time.
FileName: CharAtExample.java
1. // import statement
2. import java.util.*;
3.
4. public class CharAtExample6
5. {
6. ArrayList<Character> al;
7.
8. // constructor for creating and
9. // assigning values to the ArrayList al
10. CharAtExample6()
11. {
12. al = new ArrayList<Character>();
13. al.add('A'); al.add('E');
14. al.add('a'); al.add('e');
15. al.add('I'); al.add('O');
16. al.add('i'); al.add('o');
17. al.add('U'); al.add('u');
18. }
19.
20. // a method that checks whether the character c is a vowel or not
21. private boolean isVowel(char c)
22. {
23. for(int i = 0; i < al.size(); i++)
24. {
25. if(c == al.get(i))
26. {
27. return true;
28. }
29. }
30. return false;
31. }
32. // a method that calculates vowels in the String s
33. public int countVowels(String s)
34. {
35. int countVowel = 0; // store total number of vowels
36. int size = s.length(); // size of string
37. for(int j = 0; j < size; j++)
38. {
39. char c = s.charAt(j);
40. if(isVowel(c))
41. {
42. // vowel found!
43. // increase the count by 1
44. countVowel = countVowel + 1;
45. }
46. }
47.
48. return countVowel;
49. }
50.
51. // main method
52. public static void main(String argvs[])
53. {
54. // creating an object of the class CharAtExample6
55. CharAtExample6 obj = new CharAtExample6();
56.
57. String str = "Javatpoint is a great site for learning Java.";
58.
59. int noOfVowel = obj.countVowels(str);
60.
61. System.out.println("String: " + str);
62.
63. System.out.println("Total number of vowels in the string are: "+ noOfVowel + "\n");
64.
65. str = "One apple in a day keeps doctor away.";
66.
67. System.out.println("String: " + str);
68.
69. noOfVowel = obj.countVowels(str);
70.
71. System.out.println("Total number of vowels in the string are: "+ noOfVowel);
72. }
73. }
Output:
String: Javatpoint is a great site for learning Java.
Total number of vowels in the string are: 16
Specified by
CharSequence interface
Returns
Length of characters. In other words, the total number of characters present in the string.
Internal implementation
1. class LengthExample3
2. {
3. // main method
4. public static void main(String argvs[])
5. {
6. String str = "Welcome To JavaTpoint";
7. int size = str.length();
8.
9. System.out.println("Reverse of the string: " + "'" + str + "'" + " is");
10.
11. for(int i = 0; i < size; i++)
12. {
13. // printing in reverse order
14. System.out.print(str.charAt(str.length() - i - 1));
15. }
16.
17. }
18. }
Output:
Reverse of the string: 'Welcome To JavaTpoint' is
tniopTavaJ oT emocleW
Parameters
startIndex : starting index is inclusive
endIndex : ending index is exclusive
Returns
specified string
Exception Throws
StringIndexOutOfBoundsException is thrown when any one of the following conditions is met.
Either starting or ending index is greater than the total number of characters present in the
string.
Signature
Parameters
startIndex : starting index is inclusive
endIndex : ending index is exclusive
Returns
specified string
Exception Throws
StringIndexOutOfBoundsException is thrown when any one of the following conditions is met.
Either starting or ending index is greater than the total number of characters present in the
string.
Output:
va
vatpoint
Signature
The signature of the string concat() method is given below:
Parameter
anotherString : another string i.e., to be combined at the end of this string.
Returns
combined string
Internal implementation
Signature
There are two types of replace() methods in Java String class.
Parameters
oldChar : old character
newChar : new character
target : target sequence of characters
replacement : replacement sequence of characters
Returns
replaced string
Exception Throws
NullPointerException: if the replacement or target is equal to null.
Internal implementation
Output:
my name was khan my name was java
Signature
There are four overloaded indexOf() method in Java. The signature of indexOf() methods are given
below:
2 int indexOf(int ch, int fromIndex) It returns the index position for the given char value and from index
3 int indexOf(String substring) It returns the index position for the given substring
4 int indexOf(String substring, int fromIndex) It returns the index position for the given substring and from index
Parameters
ch: It is a character value, e.g. 'a'
fromIndex: The index position from where the index of the char value or substring is returned.
substring: A substring to be searched in this string.
Returns
Index of the searched string or character.
Internal Implementation
Signature
There are two variant of toLowerCase() method. The signature or syntax of string toLowerCase()
method is given below:
Returns
string in lowercase letter.
Signature
There are two variant of toUpperCase() method. The signature or syntax of string toUpperCase()
method is given below:
Returns
string in uppercase letter.
Output:
HELLO STRING
Signature
The signature or syntax of the String class trim() method is given below:
Returns
string with omitted leading and trailing spaces
Signature
The signature of string contains() method is given below:
Parameter
sequence : specifies the sequence of characters to be searched.
Returns
true if the sequence of char value exists, otherwise false.
Exception
NullPointerException : if the sequence is null.
1. class ContainsExample{
2. public static void main(String args[]){
3. String name="what do you know about me";
4. System.out.println(name.contains("do you know"));
5. System.out.println(name.contains("about"));
6. System.out.println(name.contains("hello"));
7. }}
Output:
true
true
false