Java array
Java array
Additionally, The
elements of an array are stored in a contiguous memory location.
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
Advertisement
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.
class Testarray{
public static void main(String args[]){
int a[]=new int[5];
a[0]=10;//initialization a[1]=20;
a[2]=70;
a[3]=40;
a[4]=50;
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}
for(int i=0;i<a.length;i++)//length is the property of array
System.out.println(a[i]);
}}
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;
class Testarray3{
public static void main(String args[]){
int arr[][]={{1,2,3},{2,4,5},{4,4,5}};
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
System.out.print(arr[i][j]+" ");
}
System.out.println();
}
Output:
123
245
445
Java Strings
In Java, a string is a sequence of characters. For example, "hello" is a
string containing a sequence of characters 'h' , 'e' , 'l' , 'l' , and 'o' .
Syntax
char charAt(int index)
example
String name="javatpoint";
char ch=name.charAt(4);//returns the char value at the 4th index
System.out.println(ch);
}}
Output:
System.out.println( first.equals(second));
output
true
System.out.println(str1.concat(str2));
String s1="javatpoint";
String s2="javatpoint";
System.out.println(s1.equals(s2));
Output
True
System.out.println(s1.indexOf("is"));
Output
String replaceString=s1.replace('a','e');
System.out.println(replaceString);
Output
String replaceString=s1.replaceAll("is","was");
System.out.println(replaceString);
Output
1. String s1="javatpoint";
2. System.out.println(s1.substring(2,4));
3. System.out.println(s1.substring(2));
Output
va
vatpoint
System.out.println(s1.toLowerCase());
Output
javatpoint hello string
System.out.println(s1.toUpperCase());
Output
HELLO STRING
hellojava
Output
Hello world
StringBuilder Example
BuilderTest.java
hellojava
An object in Java is the physical as well as a logical entity, whereas, a class in Java is a
logical entity only.
Advertisement
For Example, Pen is an object. Its name is Reynolds; color is white, known as its state. It
is used to write, so writing is its behavior.
Object Definitions:
o An object is a real-world entity.
o An object is a runtime entity.
o The object is an entity which has state and behavior.
o The object is an instance of a class.
o Fields
o Methods
o Constructors
o Blocks
o Nested class and interface
Syntax to declare a class:
1. class <class_name>{
2. field;
3. method;
4. }
int x = 5;
System.out.println(myObj.x);
Method in Java
A method is a block of code or collection of statements or a set of code grouped
together to perform a certain task or operation. It is used to achieve the reusability of
code.
Method Declaration
The method declaration provides information about method attributes, such as visibility,
return-type, name, and arguments. It has six components that are known as method
header, as we have shown in the following figure.
Method Signature: Every method has a method signature. It is a part of the method
declaration. It includes the method name and parameter list.
Access Specifier: Access specifier or modifier is the access type of the method. It
specifies the visibility of the method. Java provides four types of access specifier:
o Public: The method is accessible by all classes when we use public specifier in our
application.
o Private: When we use a private access specifier, the method is accessible only in
the classes in which it is defined.
o Protected: When we use protected access specifier, the method is accessible within
the same package or subclasses in a different package.
o Default: When we do not use any access specifier in the method declaration, Java
uses default access specifier by default. It is visible only from the same package only.
Return Type: Return type is a data type that the method returns. It may have a primitive
data type, object, collection, void, etc. If the method does not return anything, we use
void keyword.
Method Name: It is a unique name that is used to define the name of a method. It must
be corresponding to the functionality of the method. Suppose, if we are creating a
method for subtraction of two numbers, the method name must be subtraction(). A
method is invoked by its name.
Parameter List: It is the list of parameters separated by a comma and enclosed in the
pair of parentheses. It contains the data type and variable name. If the method has no
parameter, left the parentheses blank.
Method Body: It is a part of the method declaration. It contains all the actions to be
performed. It is enclosed within the pair of curly braces.
Naming a Method
remember that the method name must be start with a lowercase letter.
Types of Method
There are two types of methods in Java:
o Predefined Method
o User-defined Method
Predefined Method
In Java, predefined methods are the method that is already defined in the Java class
libraries is known as predefined methods. It is also known as the standard library
method or built-in method. We can directly use these methods just by calling them in
the program at any point. Some pre-defined methods are length(), equals(),
compareTo(), sqrt(), etc. When we call any of the predefined methods in our program, a
series of codes related to the corresponding method runs in the background that is
already stored in the library.
Each and every predefined method is defined inside a class. Such as print() method is
defined in the java.io.PrintStream class. It prints the statement that we write inside the
method. For example, print("Java"), it prints Java on the console.
Demo.java
User-defined Method
The method written by the user or programmer is known as a user-defined method.
These methods are modified according to the requirement.
For example:
Class Student
{
int sId;
String sname[30];
String course[];
}
o The static variable can be used to refer to the common property of all objects
(which is not unique for each object), for example, the company name of
employees, college name of students, etc.
o The static variable gets memory only once in the class area at the time of
class loading.
o A static method belongs to the class rather than the object of a class.
o A static method can be invoked without the need for creating an instance of a class.
o A static method can access static data member and can change the value of it.
When we assign a smaller value to another type of bigger value this type of type casting
is possible. Compiler is the responsible to perform this type casting.It is also called widening or
promotion or upcasting. In this type of typecasting there is no matter of data loss. This is also
know as automatic type casting. The following is possible in java
Example:
byte b=75;
int a =b;
are valid statements. Here the byte type is converting into integer type.
There may be situation where we assign a large variable type to small type. It is
the programmer responsibility to handle this type situation. Don't worry about this, Java provides
another way to cast large variable type to small type by using a cast operator. It looks like
following format
Examples:
int m=50;
byte n=(byte)m;
are valid statements in java. Here the int type is converting into byte type. In this process there
may be chance of losing data. The following are various possible conversions where explicit type
casting is required
super keyword in java
The process of inheriting or extending one class features into another class is called inheritance.
when a class extends another class, the newly created class is classed sub class and already
existing class is class super class. In inheritance process we are always create object to sub
class because the sub class contains both super class and sub class features.
If super class and sub class have same member functions, them the sub class object calls only
sub class version of the members.So, at this situation to call super class members we use "
super" keyword in java. There are three uses of super keyword
1. variable
2. method
3. class
The final keyword can be applied with the variables, a final variable that have no value it
is called blank final variable or uninitialized final variable. It can be initialized in the
constructor only. The blank final variable can be static also which will be initialized in the
static block only. We will have detailed learning of these. Let's first learn the basics of
final keyword.
1. class Bike9{
2. final int speedlimit=90;//final variable
3. void run(){
4. speedlimit=400;
5. }
6. public static void main(String args[]){
7. Bike9 obj=new Bike9();
8. obj.run();
9. }
10. }//end of class
Java constructors
In Java, a 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 constructor, memory for the object
is allocated in the memory.
Every time an object is created using the new() keyword, at least one constructor is
called.
It calls a default constructor if there is no constructor available in the class. In such case,
Java compiler provides a default constructor by default.
1. class Bike1{
2. //creating a default constructor
3. Bike1(){System.out.println("Bike is created");}
4. //main method
5. public static void main(String args[]){
6. //calling a default constructor
7. Bike1 b=new Bike1();
8. }
9. }
Output:
Bike is created
Java Parameterized Constructor
A constructor which has a specific number of parameters is called a parameterized
constructor.
1. class Student4{
2. int id;
3. String name;
4. //creating a parameterized constructor
5. Student4(int i,String n){
6. id = i;
7. name = n;
8. }
9. //method to display the values
10. void display(){System.out.println(id+" "+name);}
11.
12. public static void main(String args[]){
13. //creating objects and passing values
14. Student4 s1 = new Student4(111,"Karan");
15. Student4 s2 = new Student4(222,"Aryan");
16. //calling method to display the values of object
17. s1.display();
18. s2.display();
19. }
20. }
Test it Now
Output:
111 Karan
222 Aryan
In this example, we are going to copy the values of one object into another using Java
constructor.
class Student6{
1. int id;
2. String name;
3. //constructor to initialize integer and string
4. Student6(int i,String n){
5. id = i;
6. name = n;
7. }
8. Student6(Student6 s){
9. id = s.id;
10. name =s.name;
11. }
12. void display(){System.out.println(id+" "+name);}
13.
14. public static void main(String args[]){
15. Student6 s1 = new Student6(111,"Karan");
16. Student6 s2 = new Student6(s1);
17. s1.display();
18. s2.display();
19. }
20. }
Output:
111 Karan
111 Karan
The constructor name must be same as The method name may or may not be
the class name. same as the class name.
Constructor overloading in Java is a technique of having more than one constructor with
different parameter lists. They are arranged in a way that each constructor performs a
different task. They are differentiated by the compiler by the number of parameters in the
list and their types.
Polymorphism in java
Polymorphism in java is a concept by which we can perform a single action by different ways.
Polymorphism is derived from 2 greek words: poly and morphs. The word "poly" means many
and "morphs" means forms. So polymorphism means many forms.
In java there are two types of polymorphism: Runtime Polymorphism and compile time
Polymorphism. Compile time Polymorphism can achieved by overloading static methods and
Runtime Polymorphism can achieved by method overloading and method overriding.
Overloading: Overloading is a OOP's concept where a method or constructor takes more than
one form by changing its signature in terms of its parameters type and number of parameters it
have.
Overriding: Overriding is a situation where a sub class and super class have same method. But
in sub class the method will perform different tasks. OR the process of writing a super class
method in sub class with same signature to achieve different task is called overriding.
The answer is simple "NO", Because, when you define same static method in both sub class
and super class, the sub class version of static method hides super class version of method.
Runtime Polymorphism
Example:
return(a+b);
}
return( a+b+c)
}
public static void main( String args[])
{
Abstraction in Java
Abstraction is a process of hiding the implementation details and showing only
functionality to the user.
Ways to achieve Abstraction
There are two ways to achieve abstraction in java
1. Abstract class
2. Interface
running safely
Inheritance in Java
Inheritance in Java is a mechanism in which one object acquires all the properties and
behaviors of a parent object.
Or
The extends keyword indicates that you are making a new class that derives
from an existing class.
In java programming, multiple and hybrid inheritance is supported through interface only.
We will learn about interfaces later.
Single Inheritance Example
When a class inherits another class, it is known as a single inheritance. In the example
given below, Dog class inherits the Animal class, so there is the single inheritance.
File: TestInheritance.java
1. class Animal{
2. void eat(){System.out.println("eating...");}
3. }
4. class Dog extends Animal{
5. void bark(){System.out.println("barking...");}
6. }
7. class TestInheritance{
8. public static void main(String args[]){
9. Dog d=new Dog();
10. d.bark();
11. d.eat();
12. }}
Output:
barking...
eating...
File: TestInheritance2.java
1. class Animal{
2. void eat(){System.out.println("eating...");}
3. }
4. class Dog extends Animal{
5. void bark(){System.out.println("barking...");}
6. }
7. class BabyDog extends Dog{
8. void weep(){System.out.println("weeping...");}
9. }
10. class TestInheritance2{
11. public static void main(String args[]){
12. BabyDog d=new BabyDog();
13. d.weep();
14. d.bark();
15. d.eat();
16. }}
Output:
weeping...
barking...
eating...
File: TestInheritance3.java
1. class Animal{
2. void eat(){System.out.println("eating...");}
3. }
4. class Dog extends Animal{
5. void bark(){System.out.println("barking...");}
6. }
7. class Cat extends Animal{
8. void meow(){System.out.println("meowing...");}
9. }
10. class TestInheritance3{
11. public static void main(String args[]){
12. Cat c=new Cat();
13. c.meow();
14. c.eat();
15. //c.bark();//C.T.Error
16. }}
Output:
meowing...
eating...
Interface in Java
An interface in Java is a blueprint of a class. It has static constants and abstract
methods.
The interface in Java is a mechanism to achieve abstraction. There can be only abstract
methods in the Java interface, not method body. It is used to achieve abstraction and
multiple inheritance in Java.
Syntax:
1. interface <interface_name>{
2.
3. // declare constant fields
4. // declare methods that abstract
5. // by default.
6. }
1. nterface Printable{
2. void print();
3. }
4. interface Showable{
5. void show();
6. }
7. class A7 implements Printable,Showable{
8. public void print(){System.out.println("Hello");}
9. public void show(){System.out.println("Welcome");}
10.
11. public static void main(String args[]){
12. A7 obj = new A7();
13. obj.print();
14. obj.show();
15. }
16. }
Output:Hello
Welcome