ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel

Java Tutorial for Beginners: A Beginners Guide on Learning Java Programming

Updated on October 31, 2013

Get A Website Plus a Free Domain Name in Just 1 Hour!

Bring the new technology in your hands! Share your skills, improve and impress. Get Your Own Website and a Free Domain Name Here!

Java Programming for Beginners: A Tutorial and guide of the beginners on Java Programming

Based on the comments I have got, I realized that my previous hubs are not enough to guide beginners on their learning about the language. So I decided to make another hub on what should a real beginner must do. May this hub would help the beginners on their path to Java language.

The following are the most basic that a beginner must learn

1. Data types and Declaration of variables

What are the data types on Java and how to use it on the declaration of variables?

The most commonly used data types in Java are int for integers, double for decimal numbers, char for a character, string for group of charaters and Boolean for true or false variable. Data

types are used to declare variables so that a certain a variable can be used to hold string of characters or numbers. You can declare any variable name you want, however, the variable must describe what it should meant to be. For example, num1 is a variable that will hold the first input number and num2 for the second number.

How to declare a variable? The syntax is this,

DataType variableName;

Example:

int num1;

int num2;

Java Source Code Example:

package declationofvariable;


public class Main {

       public static void main(String[] args) {
        
        int num1;
        int num2;

	double num3;
	String name;
    }

}


2. Input and Output in Java

Knowing the input and output in Java is essential on your learning about the language. Before we know about how to input in Java, we must know how to output first the characters or strings in Java.

There is two common ways on how to output in Java:

1.Using System.out.print () – For single line output.

2.Using System.out.println() – For new line output.

Java Source Code Example 1:


package javasample;


public class Main {


    public static void main(String[] args) {

        System.out.println("Hi! This Is It How It Works!!!");
        System.out.print("Is it exciting? :)");
    }

}
Java Source Code "Example1" Output
Java Source Code "Example1" Output

To input in Java you must declare an object using the Scanner pre-defined function. Object is what you call to access any function in Java. Pre-defined functions are those built in functions of the language. You can name your own Object as well as you can also make your own function.

Java Source Code Example2:


package javasample;

import java.util.Scanner;


public class Main {


    public static void main(String[] args) {

        System.out.println("This Is How to Input in an integer and string in Java");

            int num1; //declare variable to hold first input
            String string = " "; // variable for sting input

       Scanner input = new Scanner(System.in);
       System.out.print("Please Enter Your Name: ");
       string = input.next();// input for string
       System.out.print("Please Enter a Number: ");
       num1 = input.nextInt(); // input for integer
       
        System.out.println(string + " You enter a number " + num1 + " :D");

    }

}
Java Source Code "Example2" Output
Java Source Code "Example2" Output

3. Java Operators

There are 4 kinds of operators in Java, the arithmetic operators, assignment operators, comparison operators and logical operators.

Arithmetic Operators:

+ - Add
- - Subtract
* - Multiply
/ - Divide
% - Remainder for Division

Assignment Operators:

 Assignment Operators      Example	      Elaboration
 =  			     X=Y	     X is equal to Y
*= 			     X*=Y                X=X*Y
+=			     X+=Y                X=X+Y
/=			     X/=Y                X=X/Y
-=			     X-=Y		 X=X-Y
%=			     X%=Y		 X=X%Y

Comparison Operators:

== equal for comparison
!= not equal
>  greater than
<  less than
>= greater than equal
<= less than equal

Logical Operators:

&& and
!  not
|| or

4. If-else Statement

If and else statement is use to execute a code that has 2 or more conditions.

Syntax:

if(true condition here)
{
	If true Code here
}
else
{
	If false Code here
}

Java Source Code Example3:

package javasample;

import java.util.Scanner;


public class Main {


    public static void main(String[] args) {

        System.out.println("This Is How to Input an integer and string in Java");

            int num1; //declare variable to hold first input
            String string = " "; // variable for sting input

       Scanner input = new Scanner(System.in);
       System.out.print("Please Enter Your Name: ");
       string = input.next();// input for string
       System.out.print("Please Enter a Number: ");
       num1 = input.nextInt(); // input for integer
       
       if(num1 < 500)
       {
            System.out.println(string + " You enter a number that is less than 500 :D");
       }
       else
       {
            System.out.println(string + " You enter a number that is greater than 500 :D");
       }
       
    }

}

Sample Output:

Java Source Code "Example3" Output
Java Source Code "Example3" Output

5. Looping

Looping is use to execute a code multiple times. Loop can be finite or infinite. There are 3 kinds of looping in Java. The for loop, do-while loop and while loop.

For Loop Syntax:

for(initialization; condition; increment )
{
	Codes here
}

For Loop Example:

package javasample;

import java.util.Scanner;


public class Main {


    public static void main(String[] args) {

            int num1; //declare variable to hold first input
            String string = " "; // variable for sting input

       Scanner input = new Scanner(System.in);
       System.out.print("Please Enter Your Name: ");
       string = input.next();// input for string
       System.out.print("Please Enter a Number: ");
       num1 = input.nextInt(); // input for integer

       System.out.println(string + " the even numbers of number " + num1 + " are:");
       

       for(int i = 1; i <= num1; i++)
       {
           int x = 1;
           System.out.print((i+=x) + " ");
       }
       
    }

}

Sample Output:

Do-While Loop Syntax:

do
{
	
  Code to repeat multiple times till the condition is met...

}while(condition to met);

Do While Loop Example and Character Input Example:


package javasample;

import java.io.IOException;
import java.util.Scanner;


public class Main {


    public static void main(String[] args) throws IOException {

     
            int num1; //declare variable to hold first input
            String string = " "; // variable for sting input
            char ans;
           

       Scanner input = new Scanner(System.in);

       
       System.out.print("Please Enter Your Name: ");
       string = input.next();// input for string

        do
       {
       System.out.print("Please Enter a Number: ");
       num1 = input.nextInt(); // input for integer

       System.out.println(string + " the even numbers of number " + num1 + " are:");
       

       for(int i = 1; i <= num1; i++)
       {
           int x = 1;
           System.out.print((i+=x) + " ");
       }
       System.out.println();
       System.out.print("Want to enter again?[Y/N]: ");

       ans = (char) System.in.read();// to read the input character

       }while(ans == 'y' || ans == 'Y');
    }

}

Sample Output:

Do while Loop and Character Input Example
Do while Loop and Character Input Example

While Loop Syntax:

While(condition to be met)
{
	Code to be executed if the condition is me
}

6. Java Arrays

Arrays are used to hold series of variable and input. Index is what you call to the variables that the array is holding. Index starts at 0. Example: if there are 5 numbers in an array, the index count would only be 4 because the first variable will be the index index 0, the second variable would be index 1 and so on.

To declare an array in Java is like this:

DataType[] arrayname = new DataType[size of the array];

Example:

int[] integers = new int[2];

This array hold two indexes, the index 0 and the index 1.

Example for Java Array:Selection Sort

working

This website uses cookies

As a user in the EEA, your approval is needed on a few things. To provide a better website experience, hubpages.com uses cookies (and other similar technologies) and may collect, process, and share personal data. Please choose which areas of our service you consent to our doing so.

For more information on managing or withdrawing consents and how we handle data, visit our Privacy Policy at: https://corp.maven.io/privacy-policy

Show Details
Necessary
HubPages Device IDThis is used to identify particular browsers or devices when the access the service, and is used for security reasons.
LoginThis is necessary to sign in to the HubPages Service.
Google RecaptchaThis is used to prevent bots and spam. (Privacy Policy)
AkismetThis is used to detect comment spam. (Privacy Policy)
HubPages Google AnalyticsThis is used to provide data on traffic to our website, all personally identifyable data is anonymized. (Privacy Policy)
HubPages Traffic PixelThis is used to collect data on traffic to articles and other pages on our site. Unless you are signed in to a HubPages account, all personally identifiable information is anonymized.
Amazon Web ServicesThis is a cloud services platform that we used to host our service. (Privacy Policy)
CloudflareThis is a cloud CDN service that we use to efficiently deliver files required for our service to operate such as javascript, cascading style sheets, images, and videos. (Privacy Policy)
Google Hosted LibrariesJavascript software libraries such as jQuery are loaded at endpoints on the googleapis.com or gstatic.com domains, for performance and efficiency reasons. (Privacy Policy)
Features
Google Custom SearchThis is feature allows you to search the site. (Privacy Policy)
Google MapsSome articles have Google Maps embedded in them. (Privacy Policy)
Google ChartsThis is used to display charts and graphs on articles and the author center. (Privacy Policy)
Google AdSense Host APIThis service allows you to sign up for or associate a Google AdSense account with HubPages, so that you can earn money from ads on your articles. No data is shared unless you engage with this feature. (Privacy Policy)
Google YouTubeSome articles have YouTube videos embedded in them. (Privacy Policy)
VimeoSome articles have Vimeo videos embedded in them. (Privacy Policy)
PaypalThis is used for a registered author who enrolls in the HubPages Earnings program and requests to be paid via PayPal. No data is shared with Paypal unless you engage with this feature. (Privacy Policy)
Facebook LoginYou can use this to streamline signing up for, or signing in to your Hubpages account. No data is shared with Facebook unless you engage with this feature. (Privacy Policy)
MavenThis supports the Maven widget and search functionality. (Privacy Policy)
Marketing
Google AdSenseThis is an ad network. (Privacy Policy)
Google DoubleClickGoogle provides ad serving technology and runs an ad network. (Privacy Policy)
Index ExchangeThis is an ad network. (Privacy Policy)
SovrnThis is an ad network. (Privacy Policy)
Facebook AdsThis is an ad network. (Privacy Policy)
Amazon Unified Ad MarketplaceThis is an ad network. (Privacy Policy)
AppNexusThis is an ad network. (Privacy Policy)
OpenxThis is an ad network. (Privacy Policy)
Rubicon ProjectThis is an ad network. (Privacy Policy)
TripleLiftThis is an ad network. (Privacy Policy)
Say MediaWe partner with Say Media to deliver ad campaigns on our sites. (Privacy Policy)
Remarketing PixelsWe may use remarketing pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to advertise the HubPages Service to people that have visited our sites.
Conversion Tracking PixelsWe may use conversion tracking pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to identify when an advertisement has successfully resulted in the desired action, such as signing up for the HubPages Service or publishing an article on the HubPages Service.
Statistics
Author Google AnalyticsThis is used to provide traffic data and reports to the authors of articles on the HubPages Service. (Privacy Policy)
ComscoreComScore is a media measurement and analytics company providing marketing data and analytics to enterprises, media and advertising agencies, and publishers. Non-consent will result in ComScore only processing obfuscated personal data. (Privacy Policy)
Amazon Tracking PixelSome articles display amazon products as part of the Amazon Affiliate program, this pixel provides traffic statistics for those products (Privacy Policy)
ClickscoThis is a data management platform studying reader behavior (Privacy Policy)