OOPLect 1
OOPLect 1
OOPLect 1
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.
arrayRefVar=new datatype[size];
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
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
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);
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:
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:
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
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:
Output: 8
Output: 8
Output: 8
A Method with Conditional Statements
(If..else)
public class MyClass {
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;
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 {
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
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.
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;
}
class GFG
{
public static void main(String[] args)
{
// Creating an instance of the class
Test obj = new Test();
} }
Local/Instance/Class Variables
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.
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
String make;
String color;
boolean engineState;
void startEngine() {
if (engineState == true){
}else {
engineState = true;
}
}
void showAtts() {
if (engineState == true){
}else{
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.
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
return geekAge;
return geekName;
return geekRoll;
geekAge = newAge;
{
geekName = newName;
geekRoll = newRoll;
obj.setName("Harsh");
obj.setAge(19);
obj.setRoll(51);
// due to encapsulation
Output:
Geek's age: 19
Geek's roll: 51
Another Example:
class motorcycle{
return name;
return color;
}
public String getyear(){
return year;
name = newname;
color = newcolor;
year = newyear;
void mAttributes(){
if(engine == true){
}else{
System.out.println("Engine is off");
}
void mEngine(){
if(engine == false){
System.out.println("Engine is on");
engine = true;
m.setname("Yamaha");
m.setcolor("Red");
m.setyear("2007");
m.mAttributes();
System.out.println("---------------------");
m.mEngine();
System.out.println("---------------------");
System.out.println("Calling Motorcycle Attributes");
m.mAttributes();
Output:
Engine is off
---------------------
Engine is on
---------------------
Engine is already on