Download as pdf or txt
Download as pdf or txt
You are on page 1of 23

Java Arrays

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.

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.

There are two types of array.

o Single Dimensional Array


o Multidimensional Array

Single Dimensional Array in Java


Instantiation of an Array in Java

arrayRefVar=new datatype[size];

Example: int arr[] = new int[5];

Example code:

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
70
40
50

Declaration, Instantiation and Initialization of


Java Array

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

Multidimensional Array in Java


In such case, data is stored in row and column based index (also known as matrix form).

Instantiate Multidimensional Array

//3 row and 3 column


int[][] arr=new int[3][3];
Initialize Multidimensional Array

arr[0][0]=1;
arr[0][1]=2;
arr[0][2]=3;
arr[1][0]=4;
arr[1][1]=5;
arr[1][2]=6;
arr[2][0]=7;
arr[2][1]=8;
arr[2][2]=9;

Example:

class Testarray3{
public static void main(String args[]){
//declaring and initializing 2D array
int arr[][]={{1,2,3},{2,4,5},{4,4,5}};
//printing 2D array
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
System.out.print(arr[i][j]+" ");
}
System.out.println();
}
}
}
Output:
1 2 3
2 4 5
4 4 5

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:

char[] ch={'j','a','v','a','t','p','o','i','n','t'};
String s=new String(ch);

Is the same as:

String s="javatpoint";
Java String class provides a lot of methods to perform operations on string such as compare(),
concat(), equals(), split(), length(), replace(), compareTo(), intern(), substring() etc.

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);
}
}
Output:
Java
Strings
Example

Java Methods
Primitive types are the most basic data types available within the Java
language. There are 8: boolean , byte , char , short , int , long , float and
double . These types serve as the building blocks of data manipulation in
Java. Such types serve only one purpose — containing pure, simple values of a
kind.

Example:

public class MyClass {


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

public static void main(String[] args) {


myMethod();
}
}

Output: Hello World!


 myMethod() is the name of the method
 static means that the method belongs to the MyClass class and not an object
of the MyClass class.
 void means that this method does not have a return value.

Method Parameters
Information can be passed to functions as parameter. Parameters act as variables
inside the method. Parameters are specified after the method name, inside the
parentheses. You can add as many parameters as you want, just separate them with a
comma.

Example

public class MyClass {


static void myMethod(String fname) {
System.out.println(fname + " Rere");
}

public static void main(String[] args) {


myMethod("Liam");
myMethod("Jenny");
myMethod("Anja");
}
}

Output:

Liam Rere

Jenny Rere

Anja Rere

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

public class MyClass {


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

public static void main(String[] args) {


System.out.println(myMethod(3));
}
}

Output: 8

Another Example with 2 parameter

public class MyClass {


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

public static void main(String[] args) {


System.out.println(myMethod(5, 3));
}
}

Output: 8

Or You can do something like this:

public class MyClass {


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

public static void main(String[] args) {


int z = myMethod(5, 3);
System.out.println(z);
}
}

Output: 8
A Method with Conditional Statements
(If..else)
public class MyClass {

// Create a checkAge() method with an integer variable called age


static void checkAge(int age) {

// If age is less than 18, print "access denied"


if (age < 18) {
System.out.println("Access denied - You are not old enough!");

// If age is greater than 18, print "access granted"


} else {
System.out.println("Access granted - You are old enough!");
}

public static void main(String[] args) {


checkAge(20); // Call the checkAge method and pass along an age of 20
}
}

Output: Access granted - You are old enough!

Static vs Non- Static Method


 In static method, the method can only access only static data members and
static methods of another class or same class but cannot access non-
static methods and variables. Also a static method can rewrite the values
of any static data member.

class example {

// static method
public static int sum(int a, int b)
{
return a + b;
}
}
public class exampleMain {
public static void main(String[] args)
{
int n = 3, m = 6;

// call the static method


int s = example.sum(n, m);

System.out.print("sum is = " + s);


}
}

 In non-static method, the method can access static data members and
static methods as well as non-static members and method of another class
or same class, but cannot change the values of any static data member.

class example {

//non static method


public int sum(int a, int b)
{
return a + b;
}
}

class exampleMain {
public static void main(String[] args)
{
int n = 3, m = 6;
//instantiation
example g = new example();
int s = g.sum(n, m);
// call the non-static method

System.out.print("sum is = " + s);


}
}
Class
A class is a user defined blueprint or prototype from which objects are created. It represents the
set of properties or methods that are common to all objects of one type. In general, class
declarations can include these components, in order:
1. Modifiers : A class can be public or has default access (Refer this for details).
2. Class name: The name should begin with a initial letter (capitalized by convention).
3. Superclass(if any): The name of the class’s parent (superclass), if any, preceded by the
keyword extends. A class can only extend (subclass) one parent.
4. Interfaces(if any): A comma-separated list of interfaces implemented by the class, if any,
preceded by the keyword implements. A class can implement more than one interface.
5. Body: The class body surrounded by braces, { }.

Object

It is a basic unit of Object Oriented Programming and represents the real life entities. A typical
Java program creates many objects, which as you know, interact by invoking methods. An
object consists of :
1. State : It is represented by attributes of an object. It also reflects the properties of an
object.
2. Behavior : It is represented by methods of an object. It also reflects the response of an
object with other objects.
3. Identity : It gives a unique name to an object and enables one object to interact with other
objects.

Java program to illustrate different ways of calling a method


import java.io.*;

class Test
{
public static int i = 0;
// constructor of class which counts
//the number of the objects of the class.
Test()
{
i++;
}
// static method is used to access static members of the class
// and for getting total no of objects
// of the same class created so far
public static int get()
{
// statements to be executed....
return i;
}

// Instance method calling object directly


// that is created inside another class 'GFG'.
// Can also be called by object directly created in the same class
// and from another method defined in the same class
// and return integer value as return type is int.
public int m1()
{
System.out.println("Inside the method m1 by object of GFG
class");

// calling m2() method within the same class.


this.m2();

// statements to be executed if any


return 1;
}

// It doesn't return anything as


// return type is 'void'.
public void m2()
{

System.out.println("In method m2 came from method m1");


}
}

class GFG
{
public static void main(String[] args)
{
// Creating an instance of the class
Test obj = new Test();

// Calling the m1() method by the object created in above step.


//non static
int i = obj.m1();
System.out.println("Control returned after method m1 :" + i);

// Call m2() method is on m1() method


//static method calling using classname.method()
int no_of_objects = Test.get();

System.out.print("No of instances created till now : ");


System.out.println(no_of_objects);

} }

Local/Instance/Class Variables

There are three kinds of Java variables:


1. Local variables are declared in a method, constructor, or block. When a
method is entered, an area is pushed onto the call stack. This area contains
slots for each local variable and parameter. When the method is called, the
parameter slots are initialized to the parameter values. When the method
exits, this area is popped off the stack and the memory becomes available
for the next called method. Parameters are essentially local variables which
are initialized from the actual parameters. Local variables are not visible
outside the method.
2. Instance variables are declared in a class, but outside a method. They are
also called member or field variables. When an object is allocated in
the heap, there is a slot in it for each instance variable value. Therefore an
instance variable is created when an object is created and destroyed when
the object is destroyed. Visible in all methods and constructors of the
defining class, should generally be declared private, but may be given
greater visibility.
3. Class/static variables are declared with the static keyword in a class, but
outside a method. There is only one copy per class, regardless of how many
objects are created from it. They are stored in static memory. It is rare to
use static variables other than declared final and used as either public or
private constants.

characteristic Local variable Instance variable Class variable


Where In a method, In a class, but outside a method. In a class, but
declared constructor, or Typically private. outside a
block. method. Must be
declaredstatic.
Typically
also final.
Use Local variables Instance variables hold values Class variables
hold values used that must be referenced by more are mostly used
in computations than one method (for example, for constants,
in a method. components that hold values like variables that
text fields, variables that control never change
drawing, etc), or that are from their initial
essential parts of an object's state value.
that must exist from one method
invocation to another.
Lifetime Created when Created when instance of class is Created when
method or created with new. the program
constructor is Destroyed when there are no starts.
entered. more references to enclosing Destroyed when
object (made available for the program
Destroyed on
garbage collection). stops.
exit.

Scope/Visibility Local variables Instance (field) variables can Same as instance


(including formal been seen by all methods in the variable, but are
parameters) are class. Which other classes can see often
visible only in the them is determined by their declared public to
method, declared access: make constants
constructor, or available to users
private should be your default
block in which of the class.
choice in declaring them. No other
they are declared.
class can see private instance
Access modifiers
variables. This is regarded as the
(private, public,
best choice.
...) can not be
Define getter and settermethods
used with local
if the value has to be gotten or
variables. All local
set from outside so that data
variables are
consistency can be enforced, and
effectively private
to preserve internal
to the block in
representation flexibility.
which they are
declared. No part Default (also
of the program called package visibility) allows
outside of the a variable to be seen by any class
method / block in the same package.private is
can see them. A preferable.
special case is public. Can be seen from any
that local class. Generally a bad idea.
variables declared
in the initializer protected variables are only
part of visible from any descendant
a for statement classes. Uncommon, and probably
have a scope of a bad choice.
the for statement.
Declaration Declare before Declare anywhere at class level Declare
use anywhere in (before or after use). anywhere at
a method or class level
block. with static.
Initial value None. Must be Zero for numbers, false for Same as instance
assigned a value booleans, or null for object variable, and it
before the first references. May be assigned value addition can be
use. at declaration or in constructor. assigned value in
special static
initializer block.
Access from Impossible. Local Instance variables should be Class variables
outside variable names declared private to promote are qualified with
are known only information hiding, so should not the class name
within the be accessed from outside a class. (eg, Color.BLUE).
method. However, in the few cases where They can also be
there are accessed from outside qualified with an
the class, they must be qualified object, but this is
by an object (eg, myPoint.x). a deceptive style.
Name syntax Standard rules. Standard rules, but are often static public
prefixed to clarify difference from final variables
local variables, eg with my, m, (constants) are
or m_ (for member) as all uppercase,
in myLength, or this as otherwise normal
in this.length. naming
conventions.
Alternatively
prefix the
variable with "c_"
(for class) or
something
similar.

Thinking in Objects: An Analogy

Consider, if you will, Legos. Legos, for those who do not spend much time with
children, are small plastic building blocks in various colors and sizes. They have
small round bits on one side that fit into small round holes on other Legos so that
they fit together snugly to create larger shapes. With different Lego parts (Lego
wheels, Lego engines, Lego hinges, Lego pulleys), you can put together castles,
automobiles, giant robots that swallow cities, or just about anything else you can
imagine. Each Lego part is a small object that fits together with other small objects
in predefined ways to create other larger objects. That is roughly how object-
oriented programming works: putting together smaller elements to build larger
ones.

Here's another example. You can walk into a computer store and, with a little
background and often some help, assemble an entire pc computer system from
various components: a motherboard, a CPU chip, a video card, a hard disk, a
keyboard, and so on. Ideally, when you finish assembling all the various self-
contained units, you have a system in which all the units work together to create a
larger system with which you can solve the problems you bought the computer for
in the first place.

Internally, each of those components may be vastly complicated and engineered by


different companies with different methods of design. But you don't need to know
how the component works, what every chip on the board does, or how, when you
press the A key, an A gets sent to your computer. As the assembler of the overall
system, each component you use is a self-contained unit, and all you are interested
in is how the units interact with each other. Will this video card fit into the slots on
the motherboard, and will this monitor work with this video card? Will each
particular component speak the right commands to the other components it
interacts with so that each part of the computer is understood by every other part?
Once you know what the interactions are between the components and can match
the interactions, putting together the overall system is easy.

Behavior of Objects

To define an object's behavior, you create methods, a set of Java statements that
accomplish some task. Methods look and behave just like functions in other
languages but are defined and accessible solely inside a class. Java does not have
functions defined outside classes

public class Main {

String make;

String color;

boolean engineState;

void startEngine() {

if (engineState == true){

System.out.println("The engine is already on.");

}else {

engineState = true;

System.out.println("The engine is now on.");

}
}

void showAtts() {

System.out.println("This motorcycle is a "

+ color + " " + make);

if (engineState == true){

System.out.println("The engine is on.");

}else{

System.out.println("The engine is off.");

public static void main (String args[]) {

Main m = new Main();

m.make = "Yamaha RZ350";

m.color = "yellow";

System.out.println("Calling showAtts...");

m.showAtts();

System.out.println("------");

System.out.println("Starting engine...");

m.startEngine();

System.out.println("------");

System.out.println("Calling showAtts...");
m.showAtts();

System.out.println("------");

System.out.println("Starting engine...");

m.startEngine();

Output:

Calling showAtts...
This motorcycle is a yellow Yamaha RZ350
The engine is off.
--------
Starting engine...
The engine is now on.
--------
Calling showAtts...
This motorcycle is a yellow Yamaha RZ350
The engine is on.
--------
Starting engine...
The engine is already on.

Encapsulate
Encapsulation is one of the fundamental concepts in object-oriented
programming (OOP). It describes the idea of bundling data and methods that work
on that data within one unit, e.g., a class in Java.

This concept is also often used to hide the internal representation, or state, of an
object from the outside. This is called information hiding. The general idea of this
mechanism is simple. If you have an attribute that is not visible from the outside of
an object, and bundle it with methods that provide read or write access to it, then
you can hide specific information and control access to the internal state of the
object.

If you’re familiar with any object-oriented programming language, you probably


know that these methods as getter and setter methods. As the names indicate, a
getter method retrieves an attribute, and a setter method changes it. Depending on
the methods that you implement, you can decide if an attribute can be read and
changed, or if it’s read-only, or if it is not visible at all. As I will show you later, you
can also use the setter method to implement additional validation rules to ensure
that your object always has a valid state.
Let’s take a look at an example that shows the concept of encapsulation and how
you can use it to implement information hiding and apply additional validation
before changing the values of your object attributes.

Encapsulation in Java

It’s such a basic concept that most Java developers use it without thinking about it.
It’s simply how you design a Java class. You bundle a set of attributes that store
the current state of the object with a set of methods using these attributes.

class Encapsulate

// private variables declared

// these can only be accessed by

// public methods of class

private String geekName;

private int geekRoll;

private int geekAge;

// get method for age to access

// private variable geekAge

public int getAge()

return geekAge;

// get method for name to access


// private variable geekName

public String getName()

return geekName;

// get method for roll to access

// private variable geekRoll

public int getRoll()

return geekRoll;

// set method for age to access

// private variable geekage

public void setAge( int newAge)

geekAge = newAge;

// set method for name to access

// private variable geekName

public void setName(String newName)

{
geekName = newName;

// set method for roll to access

// private variable geekRoll

public void setRoll( int newRoll)

geekRoll = newRoll;

public class Main

public static void main (String[] args)

Encapsulate obj = new Encapsulate();

// setting values of the variables

obj.setName("Harsh");

obj.setAge(19);

obj.setRoll(51);

// Displaying values of the variables

System.out.println("Geek's name: " + obj.getName());

System.out.println("Geek's age: " + obj.getAge());


System.out.println("Geek's roll: " + obj.getRoll());

// Direct access of geekRoll is not possible

// due to encapsulation

Output:

Geek's name: Harsh

Geek's age: 19

Geek's roll: 51

Another Example:

class motorcycle{

private String name, color, year;

private boolean engine;

public String getname(){

return name;

public String getcolor(){

return color;

}
public String getyear(){

return year;

public void setname(String newname){

name = newname;

public void setcolor(String newcolor){

color = newcolor;

public void setyear(String newyear){

year = newyear;

void mAttributes(){

if(engine == true){

System.out.println("Engine is already on");

System.out.println(name+" "+color+" "+year);

}else{

System.out.println("Engine is off");

}
void mEngine(){

if(engine == false){

System.out.println("Engine is on");

System.out.println(name+" "+color+" "+year);

engine = true;

public class Main{

public static void main(String[] args) {

motorcycle m = new motorcycle();

m.setname("Yamaha");

m.setcolor("Red");

m.setyear("2007");

System.out.println("Calling Motorcycle Attributes");

m.mAttributes();

System.out.println("---------------------");

System.out.println("Calling Motorcycle Attributes");

m.mEngine();

System.out.println("---------------------");
System.out.println("Calling Motorcycle Attributes");

m.mAttributes();

Output:

Calling Motorcycle Attributes

Engine is off

---------------------

Calling Motorcycle Attributes

Engine is on

Yamaha Red 2007

---------------------

Calling Motorcycle Attributes

Engine is already on

Yamaha Red 2007

You might also like