Welcome, Guest: Register On Nairaland / LOGIN! / Trending / Recent / New
Stats: 3,150,204 members, 7,807,687 topics. Date: Wednesday, 24 April 2024 at 05:28 PM

Introduction To Java - Programming - Nairaland

Nairaland Forum / Science/Technology / Programming / Introduction To Java (1579 Views)

I Want To Java / Introduction To Java / Solutions To Java How To Program By Deitel, 9th Edition (2) (3) (4)

(1) (Reply) (Go Down)

Introduction To Java by rexben(m): 2:03am On Mar 03, 2018
Source: https://rexandroid..com.ng/2018/02/introduction-to-java_22.html
Java is an object oriented Programming (OOP) developed by Sun MicroSystems and it was released in the year 1995. It was acquired by Oracle Corporation in 2009. Java runs on a variety of platforms that ranges from Mac OS, UNIX and Windows.

Features of Java
It is object oriented.
It is secured.
It runs on various platforms.
It is portable and dynamic.

Java programs is a collection of objects that communicate via invoking each other’s methods.
Objects is an instance of a class. It has states (fields) and behaviours (methods).
Class is a template that describes the behavior and state that the objects of its type supports.
Methods are where the logics are written, data is manipulated and all actions are executed.
Java Identifiers are names used for classes, methods and variables. Java Identifiers must begin with letter A to Z or a to z, currency character ($) or an underscore (_).
Constructor: Every class has at least one constructor. A constructor of a class must have the same name as the class. A class can have more than one constructor.

Basic Syntax of Java
Java is case sensitive. It means Song and song are not the same because the Song starts with an uppercase and the other with a lower case.

Methods in Java must start with a lower case. If several words are joined together to make a word, the first letter will be in lowercase and the first letter of subsequent words will be in upper case. Examples include: public void goToMarket(), private annualSalaryPayment(), protected void onCreate() etc.

Classes in Java must start with an upper case unlike methods. If several words are joined together to make a word, the first letter will be in uppercase and the first letter of subsequent words will be in uppercase. Examples include: public class BasicSalary, private static AggregateScore etc.

Variables are reserved memory locations

Java keywords are reserved words in Java. They are words that cannot be used as constant or variables.
Comments in Java
// example of single comment
/*another example of single comment */
/*
*Example of multi comment
*in Java
/




1. Package com.android.rexben.lagos is the package name of my Application Lagos. It is where all your java classes are stored. You can have as many classes as possible in a package. It is the way of categorizing classes and interfaces.
2. Import statement – In Android Studio and Java, you don’t need to write all the classes or methods. So, all you need to do is to import them. Any class you import will be listed in that spot.
3. Public class MainActivity extends AppcompatActivity – I will pick the term one after the other.
Public is an access modifier that determines whether a class or method can be accessed by other classes or methods class or method or only within its c. When a method is declared public, it means it can be accessed by any class or method. Other Access Modifiers include protected, private, default, abstract etc.
Class is where all your java codes are written. Where your methods are written and implemented. Class is a compartment that house methods and states.
MainActivity is the name of your java class.
Extends is used when you want to inherit some methods and fields from another class. You extend the features of another class (super class) to a new class (sub class).
AppCompatActivity is a class that the MainActivity is inheriting from. AppCompatActivity ….
4. This is the entry of your App as public static void main (Striing args[]) is the entry when use Netbeans or Eclipse.

Data Types in Java

There are two data types in Java
Primitive Data types
Reference or Object Data types
Primitive Data Types
There are eight primitive data types. They are usually in lower cases. They include byte, short, int, long, float, double, boolean and char. They are used to save memory.
Byte: Byte data type is an 8-bit signed two’s complement integer. The minimum value of byte is -128 (-27) and the maximum value is 127 (27 -1), the default value is 0.
Examples include: byte score = 99;
byte count = -3 etc.
Short: Short data types is a 16-bit signed two’s complement integer. The minimum value is -32, 768 (-215) and the maximum value is 32, 767 (215 -1), the default value is 0.
Examples include: short score = 32, 000;
short count = -20, 989 etc.
Int: Int data type is a 32-bit signed two’s complement integer. The minimum value of an int is -2,147, 483, 648 (-231) vand the maximum value is 2, 147, 483, 647 (231 -1), the default value is 0.
Examples include: int score = 1, 150, 000;
Int count = -2, 760, 444
Long: Long data type is a 64-bit signed two’s complement integer. The minimum value of (-263) and the maximum value is (263 -1), the default value is 0L
Examples include: long score = 200 000L;
Long count = -100 000L
Float: Float is a single-precision 32-bit IEEE 754 floating point used to save memory in large arrays of floating points number. Default value is 0.0f
Examples include: float score = 234.5f;
float count = -11.4f.
Double: Double is a double-precision 32-bit IEEE 754 floating point, used as the default data type for decimal values. Default value is 0.0d.
Examples include: double score = 123.4;
double count = -120.4.
Boolean: Boolean represents one bit of information. There are only two possible vaues: true and false. Default value is false.
Examples include: boolean isScore = true;
boolean isCount = false.
Char: Char is a single16-bit Unicode character. It is used to store any character.
Examples include: char letterA = “A”;
char letter = “V”

Reference Data Types
They are created using defined constructors of the classes. They are declared to be a specific type that cannot be changed. Class objects and various types of array are examples of reference data types. Default value is null.

Variable types
There are basic three types of variable in Java
Local Variables are variables that are declared and initialized inside methods or constructors.
Instance Variables are variables that are declared outside any methods or constructors but within a class. It can be accessed from inside any methods or constructors of that particular class. They are also referred to as fields.
Class Variables are variables declared outside any methods or constructors but within a class with the static keyword. The difference between a class variable and an instance variable is the static keyword.


Creating an object in the java
In Java, an object is created from a class and it created with the new keyword.
There are three steps when creating an object from a class.
Declaration: A variable name with an object type e.g. String score;
Instantiation: The new keyword is used to create a class.
Initialization: The new keyword is followed by a call to a constructor e.g. String score = new String(};
Re: Introduction To Java by tokzy205(m): 7:47am On Mar 03, 2018
Nice but I prefer kotlin

1 Like

Re: Introduction To Java by rexben(m): 2:14am On Mar 05, 2018
Methods are behaviors of a class. They are responsible for how a class interact with other classes or behave generally. Class is just a container that holds different methods. It is in methods that logic are written and all actions are executed.
Syntax of a java method.

protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}

A method must have an access modifier e.g. public, private, protected, default etc.
It must have a return type. If it is not meant to return anything, then you declare void as its return type. The example above has not return, thereby it is declared void.
Example of a method with return type

public String getMyLocation() {
return myLocation;
}

It must have a name. Your method must have a name. You are not permitted to use Java reserved words as a method name.
The first name or identifier must start with a lowercase. If there are concatenation of more than one name, the first name must be in lowercase and the first letter of the next word must be in upper case.

public String getMyLocation() {
return myLocation;
}

A method may have several numbers of arguments or no argument at all. The arguments are written in between the ( ). If a method contains more than one argument, the arguments should be separated by comma. If the arguments have the same data type, you must declare it separate as though they have different data types.

private int classGrades(int maths, int english){

return maths + english;
}
A java method is a collection of statements. Statements are written between two curly brackets {}.
protected void onCreate(Bundle savedInstanceState) {
//statements
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}

Method Overloading

Method Overloading is when a class have two or more methods with the same name but different parameters. The only thing that is different in this methods is the parameters they take.
This first method is not taking in any parameter

public String getMyLocation() {
return myLocation;
}
The second method is taking in a parameter
public String getMyLocation(String myLocation) {
return myLocation;
}

In the previous post, we worked on button clicks. I want to show you another way of how to implement button clicks (click listener) in our app.
In your activity_main.xml file, add android:onClick="addBtn"

<!--The button that is responsible for add numbers-->
<Button
android:id="@+id/add"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Add"
android:onClick="addBtn"/>

And in your MainActivity.java
Instead of this long process:

addButton.setOnClickListener(new View.OnClickListener() {

@Override

public void onClick(View view) {
//Anytime the button is clicked 1 is added to the screen
numberUpdate = numberUpdate + 1;

//Displays the numberUpdate to the screen
//if you don't set the text, nothing will be displayed to
//the screen
defaultText.setText("" + numberUpdate);
}
});

Just use this

//addBtn is the value of android:onClick value in the our xml
public void addBtn(View view) {
//Anytime the button is clicked 1 is added to the screen
numberUpdate = numberUpdate + 1;

//Displays the numberUpdate to the screen
//if you don't set the text, nothing will be displayed to
//the screen
defaultText.setText("" + numberUpdate);
}
Re: Introduction To Java by rexben(m): 2:16am On Mar 05, 2018
Making your App responds to button clicks

In this tutorial, we want to make our App interactive by making it to respond to button clicks. When the user clicks on the button, an event will occur.

Project: To display a number on the screen and a button. So, when the button is clicked, the number will be updated. Anytime you click on the button, the default number is increased by 1.
So, let’s get started.
First off, you will have to create a new project, give it any name you want. If you don’t know how to create a new project in Android Studio. Check this link, I explained explicitly on how create a new Android Studio project www.rexandroid..com

If you’ve launched Android Studio already and you are in project but want create another project.
Go to the top bar, Click on File > New Project and fill up the rest.

In activity_main, enter this following codes. Here is a link on how to understand the basics of XML, working with XML




<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="16dp"
tools:context="com.android.rexben.demomapp.MainActivity">


<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:text="Number"
android:textSize="20sp" />


<!--The text that will be updated when a button is clicked-->
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:text="0"
android:textSize="20sp"
android:id="@+id/textView"/>


<!--The button that is responsible for add numbers-->
<Button
android:id="@+id/add"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Add" />
</LinearLayout>



In your MainActivity.java, enter this following lines of code


package com.android.rexben.demoapp;


import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {
//This variable called field because it declared out a method
//It is variable where we store the values that are added
private int numberUpdate;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

//Casting views by resource IDs
final TextView defaultText = (TextView) findViewById(R.id.textView);
Button addButton = (Button) findViewById(R.id.add);


//setOnClickListener is responsible for happens when a button is clicked
//Any codes writing inside the setOnClickListener will be executed when the button is clicked
addButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {

//Anytime the button is clicked 1 is added to the screen
numberUpdate = numberUpdate + 1;


//Displays the numberUpdate to the screen
//if you don't set the text, nothing will be display to
//the screen
defaultText.setText("" + numberUpdate);
}
});
}

}
When you are done, test run your App on your
Android device. If you don’ know how to run the App on your mobile device,
check this link Getting familiar with Android Studio



numberUpdate = numberUpdate + 1;

To:
numberUpdate = numberUpdate - 1; to decrease the value by 1 anytime there is a click.
numberUpdate = numberUpdate * 5; to multiply the value by 5 anytime there is a click.
numberUpdate = numberUpdate / 2; to divide the value by 2 anytime there is a click.

Just add the default value of your choice
private int numberUpdate = 10;

If you don’t want only the number to show, if you want to display other texts. For instance, instead of displaying only “1”, you can add “Number 1”.
Just add the text you want and add a space so that the text and the number won’t be together. You can enter a long text but it must be in between "".
defaultText.setText("Number " + numberUpdate);
Re: Introduction To Java by rexben(m): 12:31am On Mar 12, 2018
Java Methods

Methods are behaviors of a class. They are responsible for how a class interact with other classes or behave generally. Class is just a container that holds different methods. It is in methods that logic are written and all actions are executed.
Syntax of a java method.

protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}


A method must have an access modifier e.g. public, private, protected, default etc.
It must have a return type. If it is not meant to return anything, then you declare void as its return type. The example above has not return, thereby it is declared void.
Example of a method with return type

public String getMyLocation() {
return myLocation;
}


It must have a name. Your method must have a name. You are not permitted to use Java reserved words as a method name.
The first name or identifier must start with a lowercase. If there are concatenation of more than one name, the first name must be in lowercase and the first letter of the next word must be in upper case.

public String getMyLocation() {
return myLocation;
}


A method may have several numbers of arguments or no argument at all. The arguments are written in between the ( ). If a method contains more than one argument, the arguments should be separated by comma. If the arguments have the same data type, you must declare it separate as though they have different data types.

private int classGrades(int maths, int english){

return maths + english;
}

A java method is a collection of statements. Statements are written between two curly brackets {}.
protected void onCreate(Bundle savedInstanceState) {
//statements
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}


Method Overloading

Method Overloading is when a class have two or more methods with the same name but different parameters. The only thing that is different in this methods is the parameters they take.
This first method is not taking in any parameter

public String getMyLocation() {
return myLocation;
}

The second method is taking in a parameter
public String getMyLocation(String myLocation) {
return myLocation;
}


In the previous post, we worked on button clicks. I want to show you another way of how to implement button clicks (click listener) in our app.
In your activity_main.xml file, add android:onClick="addBtn"

<!--The button that is responsible for add numbers-->
<Button
android:id="@+id/add"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Add"
android:onClick="addBtn"/>


And in your MainActivity.java
Instead of this long process:

addButton.setOnClickListener(new View.OnClickListener() {

@Override

public void onClick(View view) {
//Anytime the button is clicked 1 is added to the screen
numberUpdate = numberUpdate + 1;

//Displays the numberUpdate to the screen
//if you don't set the text, nothing will be displayed to
//the screen
defaultText.setText("" + numberUpdate);
}
});


Just use this
 
//addBtn is the value of android:onClick value in the our xml
public void addBtn(View view) {
//Anytime the button is clicked 1 is added to the screen
numberUpdate = numberUpdate + 1;

//Displays the numberUpdate to the screen
//if you don't set the text, nothing will be displayed to
//the screen
defaultText.setText("" + numberUpdate);
}
Re: Introduction To Java by rexben(m): 12:40am On Mar 12, 2018
Communicating between Activities


An Activity is a single screen that a user can interact with. There can be multiple activities in an App.
So, in this tutorial, I will show you how to move from one another to another activity.
Intent is used to communicate between activities; to link up two activities, you need Intent.
Intents is not limited to communicating between activities, you can also use Intent to communicate between Android components.

There are two types of Intents.
Explicit Intent: It is used when we want to communicate between activities.
Implicit Intent: It is used when we want to communicate between Android components.

In this tutorial, we will be making use of an explicit intent.
Steps:

Create a new Android Project.
Create another activity besides the one you have.
Modify your activity_main.xml by adding a button
Modify your MainActivity.java by writing the logic responsible for linking activities.
Modify your activity_main2.xml to differentiate it from the first activity

By now, you have been used to creating new Android project, if not, check out this link
Getting familiar with Android Studio

The second step, go to left side of your Android Studio, under your java folder, Right click on the first package.
Go to New > Activity > Empty Activity > Finish.






Step three: Go to your activity_main.xml and create a button. When the button is clicked, it will take us to the next Activity.

<!--Text to differentiate between the two activities-->
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="First Activity"
android:textSize="50sp"/>
<!--Button to take us to the next activity-->
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Next"
android:onClick="next"
android:textSize="30sp"/>

Step four: Go to your MainActivity.java and write logics

//Create an onClick listener method
//Create the intent that links the two activities
//@this means the current activity we are, i.e. the first activity
//@Main@Activity.class means the next activity we want to go when the next button is clicked
//@startActivity(activityIntent); starts the new activity
public void next (View view){
Intent activityIntent = new Intent(this, Main2Activity.class);
startActivity(activityIntent);
}

Step five: Go to your activity_main2.xml or whatever name you gave to the new activity you created and modify it by adding a TextView.

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="This is the Second Activity"
android:textSize="50sp"/>



Source: https://rexandroid..com.ng/2018/03/widgets-in-android.html
Re: Introduction To Java by CodeTemplar: 4:12pm On Mar 18, 2018
tokzy205:
Nice but I prefer kotlin
Is kotlin as good as java for web apps, enterprise app, etc ? I heard it is targetted at android.
Re: Introduction To Java by rexben(m): 9:32am On Apr 02, 2018
CodeTemplar:

Is kotlin as good as java for web apps, enterprise app, etc ? I heard it is targetted at android.
Sure, it is just an alternative to Java

(1) (Reply)

As A Techie What State Do You Live And How Is Electricity In Your Area / Php / I Need A Class Tha Can Transfer Files Using Webservice On Client Machines. Plz U

(Go Up)

Sections: politics (1) business autos (1) jobs (1) career education (1) romance computers phones travel sports fashion health
religion celebs tv-movies music-radio literature webmasters programming techmarket

Links: (1) (2) (3) (4) (5) (6) (7) (8) (9) (10)

Nairaland - Copyright © 2005 - 2024 Oluwaseun Osewa. All rights reserved. See How To Advertise. 63
Disclaimer: Every Nairaland member is solely responsible for anything that he/she posts or uploads on Nairaland.