Learn Java for Android App development- Complete Guide


Android is based on the Linux operating system and open source software. Android used to build mobile applications. It is developed by Open Handset Alliance, led by Google, and other companies. Google launched the first beta version of the Android Software Development Kit (SDK) in 2007 while Android 1.0, the first commercial version, was unveiled in September 2008.

Android applications are mainly built in Java language using Android Software Tool Kit. Android applications can be downloaded from stores like Google Play, SlideME, Opera Mobile Store, Mobango, F-droid , and the Amazon Appstore for end users.

What is Java?

To facilitate the crafting and implementation of an excellent high-end programming option,Sun Microsystems(now headed by Oracle)'s development team conceptualized java.Java boasts complete propagation amongst OSs,such as Windows,Linux ,and MacOS-architectural facts that crystallize java being platform independent.Indispensable for java program execution are functionalities inherent in the JVM,which include loading,verification and code execution.The successful creation of java builds it upon an object-centered foundation,supporting vital OO concepts like encapsulation,polymorphism,and inheritance.Java's failure to support multiple inheritance restrains the category of being purely OO.

Java for Android app development

This article contains all the topics that you require to learn for Android app development in Java. And these are as follows.

  • Environment setup.

  • OOP’s concept

  • Java Syntax

  • Java identifiers

  • Data types in Java

  • What is variable and its scope

  • Decision-Making statement in Java

  • Typecasting in Java

  • Operators in Java

  • Strings in Java

  • Methods in Java

  • Exception handling in Java

  • Abstract class and interfaces in Java

Environment setup

Writing a Java program requires JDK(Java development kit). This toolkit includes JRE(Java runtime environment) and development tools. To install JDK follow thses steps given below −

  • Make sure to procure the newest version of JDK from its official website and take note of your said computer's OS - be it Mac OS X, Windows or Linux- to make certain you download accordingly for maximised usefulness.

  • Install JDK.

    • Run the installer after locating the file in your download folder.

  • Set path for JDK

    • Define the path where executable and class files will be located.

OOPs Concept

The basic building blocks of object-oriented programming are classes and objects. And this structure makes code more reusable and readable. The main concepts of object-oriented programming are as follows −

  • Objects

  • Classes

  • Abstraction

  • Inheritance 

  • Polymorphism

  • Encapsulation

Objects

The instances of a class are known as objects. They have states and behavior.

For example, an object animal has a state like color and behavior such as eating.

When working with programming languages, everyday objects like chairs, tables or pens can be translated into code as objects. To assign memory to these code representations of physical entities, programmers utilize the new() method located within the heap.

Classes

Class is a collection of objects any memory. To create a class always use the keyword class.

Abstraction

In abstraction, implementation i.e. internal information will be hidden and the needed information will be displayed only. It reduces the complexity and effort of the programming. To implement abstraction we use abstract class and interface in a program.

Inheritance

Acquiring the properties from parent class to child class is known as inheritance. It supports the reusability of the methods.

Polymorphism

In polymorphism, a single method can operate on different types of objects.  It occurs when we have many classes related to each other by inheritance. Method overloading and overriding is the example of polymorphism. Polymorphism is mainly two different types −

  • Runtime Polymorphism −

    It can be achieved by method overriding. And it is resolved at run time

  • Compile time polymorphism −

    It can be achieved by method overloading. And it is resolved at compile time.

Encapsulation

The process of binding data and code together is known as encapsulation. It prevents unauthorized access to the users.

Java Syntax

There are some rules that should be followed by the programmer in writing the syntax of the java code. These are as follows

  • Every line of code must be inside the class.

  • The first letter of the class name must be in capital

  • The main method is mandatory.

  • Print method will be inside the main method.

Java Identifiers

A variable, function, class, interface, or other program element may be identified by a name, known as an identifier, in Java.

Data Types in Java

When it comes to computer programming languages and the like it's common to encounter one of two primary classifications for data - namely; primitive or non primitive. Amongst the members belonging to the former group are byte ,short,int . Long. Float,double,boolean,and char according to definition .

What are Variable and Scope

Variables are used to store data values. There are mainly five types of variables as given below −

  • Int − Contains integer value.

  • Foat − Contains floating numbers with decimals.

  • String − Contains text.

  • Char − Contains single character values.

  • Boolean − True/False.

Decision-Making Statement in Java

  • Control Statements (if-else, if, switch, break, continue, jump) −

    These statements work on a certain condition to control the flow of program execution.

If Statement

If the condition is true then only the code will execute.

Syntax

if(condition){  
   //Code
}

Example

public class Student {  
   public static void main(String[] args) {  
      int marks=20;  
      if(marks>13){  
         System.out.print("Pass");  
      }  
   }  
}

Output

Pass

If-else statement

if the condition is true then code of if block will be executed otherwise code of else block will executed.

Syntax

if(condition){  
   //if the condition is true this code will executed
}else{  
   // if the condition is false this code will executed 
}  

Example

public class IfElseExample {  
   public static void main(String[] args) {  
      int number=15; 
      if(number%2==0){  
         System.out.println("Even Number");  
      }else{  
         System.out.println("Odd Number");  
      }  
   }  
}  

Output

Odd Number

Switch statement in Java

Depending on the value of the expression, a switch statement forces control to go to one labeled statement in its statement body.

Rules for switch statement −

  • Any number of cases can be applied by simply applying the condition check, but keep in mind that duplicate case/s values are not permitted.

  • A case's value must be of the same data type as the switch's variable.

  • A case's value must be either constant or literal. There is no room for variables.

  • The default statement can be placed anywhere in the switch block and is optional. Keeping a break statement after the default statement will prevent the execution of the following case statement in the event that it is not at the end.

  • Break statements are not required. Execution will move on to the following case if it is left out.

  • To end a series of statements, use the break statement inside the switch.

Syntax

switch(expression){    
   case value1:    
      //code to be executed;    
      break;  //optional  
   case value2:    
      //code to be executed;    
      break;  //optional  
   ......        
   default:     
   code to be executed if all cases are not matched;  
}

Example

public class Switch {  
   public static void main(String[] args) {  
      int number=10;  
      switch(number){  
         case 10: System.out.println("10");  
            break;  
         case 20: System.out.println("20");  
            break;  
         case 30: System.out.println("30");  
            break;   
         default:System.out.println("Not in 10, 20 or 30");  
      }  
   }  
}  

Output

10

For-each in Java

It is used in traversing in a program like a while do-while loop.

Syntax

for(data_type var : array)
{  
   //code  
}

Example

public class ForEach{  
   public static void main(String args[]){  
      int arr[]={1,2,3,4};  
      for(int i:arr){  
         System.out.println(i);  
      }  
   }   
} 

Output

1
2
3
4

Type Casting in Java

It is the process of converting one data type into another data type. It is mainly two types −

  • Widening Casting − converting a smaller data type to a larger data type. For example byte->short

  • Narrowing Casting  − converting a larger data type to a smaller data type. For example double -> float. 

Operators in Java

Operators are used to performing operations on variables and values. These are mainly five different types as given below −

  • Arithmetic operators −

    These are used to perform mathematical operations.

  • Assignment operators −

    These operators are used to assign values to variables. For example addition(+), subtraction(-).

  • Comparison Operators −

    These operators are used to compare values or variables. For example less than(<) or grater than(>).

  • Logical Operator −

    This operator is used for true/false.

  • Bitwise operator −

    Bitwise operators are tools for executing operations on a number's component bits. They work with all integral types, including char, short, and int. They are employed in the updating and searching of binary-indexed trees.

Strings in Java

The Java String class offers a range of methods that allow manipulation of strings. These include compare() concat() equals() split() length() replace() compareTo() intern() and substring(). In essence. A string is an object that presents a sequence of characters. It can be created by two methods which are as follows −

String literal

It uses the double quote to create a string. The string will be stored in string constant pool memory.

For example −

String s = "SME"

New Keyword

It uses a new Keyword to create a string. It will allocate the string in heap memory.

For example −

String s = new String("SME")

Methods In java

Methods are blocks of code used to perform a function. There are mainly two types −

Pre-defined methods

These are defined in Java class libraries. For example length(), equals(), compareTo(), sqrt(), etc.

Example

public class Example{
   public static void main(String[] args)   {    
      System.out.print("The maximum number is: " + Math.min(5,8));  
   }  
}

Output

The maximum number is: 5

User Defined methods

These methods are defined by users and fulfils the user requirement.

Example

public class OddEven  {  
   public static void main (String args[])  
   {      
      Scanner find = new Scanner(System.in);  
      System.out.print("Enter the number: ");    
      int num = find.nextInt();  
      findOddEven(num);  
   }  
   public static void findOddEven(int num)  
   {  
      if(num%2==0)   
         System.out.println(num+" is even");   
      else   
         System.out.println(num+" is odd");  
   }  
} 

Output

Enter the number: 4
4 is even

Exception handling in Java

One effective method for handling runtime failures and preserving the application's regular flow is Java's exception handling.

Exception in Java

It is an unexpected error during the execution of program. The programme has the ability to detect and manage exceptions. An object is created when an exception occurs within a method. The exception object is the name of this item. It includes details about the exception, including its name, description, and the program's status at the time the exception occurred.

Types of exception

Java defines a number of exception kinds that are connected to its different class libraries. Java also gives users the option to create custom exceptions. All the exceptions and error are subclass of class Throwable.

Built-in Exception

  • Checked Exception −

    Compile-time exceptions are also known as checked exceptions since the compiler checks them while they are being built. For example ClassNotFoundException.

  • Unchecked Exception −

    These exceptions won't be checked by the compiler during compilation. For example ArithematicException.

User-defined Exception

These exceptions are created by user. It will complete the program execution by identifying the meaningful error.

Abstract class and Interface

Abstract Class

In Java, an abstract class is one that has the abstract keyword stated in its declaration. Both abstract and non-abstract methods (methods with bodies) are possible.

It needs to be extended and its method implemented. It cannot be instantiated.

Syntax

abstract class class-name
{
   Non-abstract methods
}
{
Abstract methods();
}

Example

abstract class Car{  
   abstract void run();  
}  
public class Dezire extends Car{  
   void run() {
      System.out.println("running safely");
   }  
   public static void main(String args[]){  
      Car obj = new Dezire();  
      obj.run();  
   }  
}  

Output

Running safely

Interface in Java

In Java, a class's blueprint is called an interface. It has abstract methods and static constants.

Java uses the interface as a tool to achieve abstraction. The Java interface can only include abstract methods; method bodies are not allowed. In Java, it is used to achieve multiple inheritance and abstraction.

Syntax

Interface interface_name
{
   Variable;
   Method;
}

Example

interface Animal {
   public void sound(); 
   public void eat(); 
}
public class Dog implements Animal {
   public void sound() {
      System.out.println("bark");
   }
   public void eat() {
      System.out.println("bhau");
   }
}interface Animal {
   public void sound(); 
   public void eat(); 
}

class Main {
   public static void main(String[] args) {
      Dog myDog = new Dog();  // Create a dog object
      myDog.animalSound();
      myDog.eat();
   }
}

Output

bark
bhau

Updated on: 28-Jul-2023

130 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements