You are on page 1of 13

Basic Java Code Examples for Beginners

May 19, 2014 by usman_malik

Java is an object-oriented language used to


develop variety of applications ranging from simple desktop address books, enterprise level ERP
systems, and complex dynamic websites to mobile based applications for android. Learning Java
is essential for stepping up in the path of software development owing to its major market share.
Java is portable and can run on variety of platforms including Linux, Windows and Mac.
Developed on the principle of Write Once Run Anywhere (WORA), Java is often considered the
best place to jump into the exciting world of programming. This article contains some basic and
interesting Java code examples for beginners. These examples are good enough to understand the
basic feature of any Java application.

For in-depth Java tutorials, take a course at Udemy.com.

1- A Basic Java Calculator

The following code example is a simple calculator application in Java that takes input from a
user through console along with one of the four mathematical operations i.e. Add, Subtract,
Multiple and Divide and then display the output on the console.

The application makes use of a Maths class which contains four functions that perform four
mathematical operations and return the result to the calling function. The definition of the Maths
class looks like this:

public class Maths {


public int Add (int num1, int num2)

return num1 + num2;

public int Subtract (int num1, int num2)

return num1 - num2;

public int Multiply (int num1, int num2)

return num1 * num2;

public int Divide (int num1, int num2)

return num1 / num2;

You can see from the above code that all the methods in the above code return integer values and
all of them take two integer type parameters. To make use of the Maths class for performing
mathematical function, its object has to be created and then the methods can be called from that
object. The following code snippet demonstrates that how a calculator application actually
performs.

import java.util.Scanner;

public class MyClass {

public static void main(String[] args) {

Maths math = new Maths();

Scanner userinput = new Scanner(System.in);

System.out.println("Welcome to Java Calculator");


System.out.println("===========================");

System.out.print("Enter First Number:");

int num1 = userinput.nextInt();

System.out.print("Enter Second Number:");

int num2= userinput.nextInt();

System.out.print("Enter operation to perform (+,-,x,/):");

String operation= userinput.next();

if (operation.equals("+"))

System.out.println(math.Add(num1, num2));

else if (operation.equals("-"))

System.out.println(math.Subtract(num1, num2));

else if (operation.equals("x"))

System.out.println(math.Multiply(num1, num2));

else if (operation.equals("/"))

System.out.println(math.Divide(num1, num2));

else

System.out.println("The operation is not valid.");

If you look closely at the above code snippet, a package named java.util.Scanner has been
imported at the beginning of the code. This Scanner class allows scanning console input. In the
main method of the class, the object of Maths class has been declared. Then, using the Scanner
class object, the first number, second number and operation to be performed has been obtained
from the user. Finally, the string comparison of the operation has been performed using equals
method. This is to decide which method of the Maths class has to be called. If the matched string
is +, the Add method of the Maths class would be called. The numbers taken as input from the
users will be passed to this method. One instance of the output of the above code is as follows:
Welcome to Java Calculator

===========================

Enter First Number:500

Enter Second Number:10

Enter operation to perform (+,-,x,/):/

50

The division of 500 by 10 yields 50 that have been displayed on the console output.

To learn Java concepts in detail, take a course at Udemy.com.

2- Calculating Factorial using recursive functions in Java

The second code example demonstrates that how factorial of any number can be calculated via
recursive functions in Java. A recursive function in Java is a function that keeps calling itself
until a particular condition becomes valid in which case, the function executes. The following
code snipped demonstrates the usage of recursive function for calculating factorial of a number:

import java.util.Scanner;

public class MyClass {

public int fact(int n)

if (n==1)

return n;

else

n = n * fact(n-1);

return n;

public static void main(String[] args) {


MyClass test = new MyClass();

Scanner userinput = new Scanner(System.in);

System.out.print("Enter the number to find factorial: ");

int num = userinput.nextInt();

System.out.println("The factorial of " +num+" is: "+test.fact(num));

In the above code, the fact function in class MyClass is the recursive function that keeps on
calling itself. The terminating condition in the fact function is that when the passed parameter
which is integer type n, becomes 1. In that case, the function executes. The output instance of the
above code is as follows:

Enter the number to find factorial: 6

The factorial of 6 is: 720

3- Displaying first n Prime Numbers

The last code example of this article demonstrates how first n prime numbers can be calculated
where n is any number. For instance, if the user specifies n as 5, the first 5 prime numbers
starting from 2 and ending at 11 would be displayed. The code of the application is as follows:

import java.util.Scanner;

public class MyClass {

public boolean numberIsPrime(int n)

for(int i = 2; i<n; i++)

if ( n%i == 0)

returnfalse;

returntrue;

public static void main(String[] args) {

MyClass test = new MyClass();


Scanner userinput = new Scanner(System.in);

System.out.print("Enter the number of primes to be displayed: ");

int num = userinput.nextInt();

int count = 0;

for( int i =2; i>0; i++)

if (test.numberIsPrime(i) && count<num)

System.out.print(i +" ");

count++;

A method named numberIsPrime has been defined which takes an integer type number and
checks if it is prime or not. If the number is note prime, it returns false and if number is prime, it
returns true. In the main function, a number is obtained from the user and every time a prime
number is displayed another variable count is incremented. The numbers are displayed until
count is becomes equal to the number specified by the user. The output of the above application
is as follows:

Enter the number of primes to be displayed: 5

2 3 5 7 11

_______________________________________part2________________

The Basic Structure of a Simple Java


program
Let us see now how the simple java program will look like.

You can use any editor like notepad or any Java IDE for writing java programs.

/*

This is a sample java program


Save this file as Welcome.java

*/
class Welcome

// A java program will start from here.

public static void main(String args[])

System.out.println(" Welcome to Java-Samples!!! ");

For those who are using the IDE, you can follow the instructions have given by there.

Suppose if you are entering your program in notepad, then save this file as Welcome.java

Compiling the program

After we have written our program we need to compile and run the program. For that we need to use the
compiler called javac which is provided by java.

Go to the command prompt and type the file name as shown here.

c:\>javac Welcome.java

The javac compiler will create a class file called Welcome.class that contains only bytecodes. These
bytecodes have to be interpreted by a Java Virtual Machine(JVM) that will convert the bytecodes into
machine codes. Once we successfully compiled the program, we need to run the program in order to get
the output. So this can be done by the java interpreter called java. In the command line type as shown
here.

c:\>java Welcome

So the output will be displayed as

Welcome to Java-Samples!!!

As we had seen above, when the source code has been compiled , it creates a class file with a extension
of .class. Since this class file contains the bytecodes that can be interpreted by the JVM which can be
resided at any platform. Remember that while running the program we are using only .class file but not
the .java file. So once you got the class file you can run the same java program at any platform instead of
writing the program again and again. This is the very special feature about java that 'Write once and Run
anywhere'

Looking into the program line by line

Let us closely examine each part of the program.

/*

This is a sample java program


Save this file as Welcome.java

*/
This is called comment. This is for us to enter the comments about the program for our own convenience.
The contents of a comment will be ignored by the compiler. Actually java supports three styles of
comments. The above one is called multi-line comment which may contain several lines. This type of
comment must begin with /* and end with */.

The next line of the code in a program is

class Welcome

The word class is a keyword to define a new class and Welcome is a name of the class. The class
definition must begins with opening curly brace ({) and ends with closing curly brace (}). The rest of the
things defined inside these braces are called member of the class. And note that all the program activities
are defined inside the class.

// A java program will start from here.

This is another type of comment. This is called single line comment starts with // and ends with end of the
line. Generally we use it for brief comments.

The next line of the code in a program is

public static void main(String args[])

This line begins with main method as like functions or subroutines in other languages. The program will
start execute by calling this main method. Let us see briefly about the other attributes declared in main
method. However we are going to discuss in detail about this in later chapters.

The keyword public is an access specifier. The keyword static is a kind of modifier. The keyword void
means that the method main() does not return any value. As we had seen before all the java program will
start execute by calling the main method. If we want to pass any information to a method will be received
by the variables declared within the parenthesis is called parameters. In a main() method there is only
one parameter ,String args[] . args[] is a name of the parameter that is an array of the objects of data type
String. String store sequences of characters and args will receive the command line arguments.

All the method in java must be start with opening curly brace ({) and ends with closing curly brace (}).

The next line of the program is

System.out.println(" Welcome to Java-Samples!!! ");

Understanding of each keyword used here will be difficult now, so just take it as this System.out.println
helps to display the output in the command line. As you have probably noticed, the System.out.println
statement ends with ;. All statements in java must end with semicolon. And remember that java is case
sensitive. So we should be very careful about cases while coding the program. Otherwise it will lead to
the serious problems.

Now that you know how a basic program in Java looks like, you can proceed to learn Basics of Java
through Sample Programs

______________________________________part3_______________________________

Java - Basic Syntax

Advertisements
Previous Page

Next Page

When we consider a Java program it can be defined as a collection of objects that communicate
via invoking each other's methods. Let us now briefly look into what do class, object, methods
and instance variables mean.

Object - Objects have states and behaviours. Example: A dog has states - colour, name,
breed as well as behaviours -wagging, barking, eating. An object is an instance of a class.

Class - A class can be defined as a template/ blue print that describes the
behaviours/states that object of its type support.

Methods - A method is basically a behaviour. A class can contain many methods. It is in


methods where the logics are written, data is manipulated and all the actions are
executed.

Instance Variables - Each object has its unique set of instance variables. An object's state
is created by the values assigned to these instance variables.

First Java Program:

Let us look at a simple code that would print the words Hello World.

public class MyFirstJavaProgram {

/* This is my first java program.


* This will print 'Hello World' as the output
*/

public static void main(String []args) {


System.out.println("Hello World"); // prints Hello World
}
}

Let's look at how to save the file, compile and run the program. Please follow the steps given
below:

Open notepad and add the code as above.

Save the file as: MyFirstJavaProgram.java.

Open a command prompt window and go to the directory where you saved the class.
Assume it's C:\.

Type ' javac MyFirstJavaProgram.java' and press enter to compile your code. If there are
no errors in your code, the command prompt will take you to the next line (Assumption :
The path variable is set).

Now, type ' java MyFirstJavaProgram ' to run your program.


You will be able to see ' Hello World ' printed on the window.

C:\> javac MyFirstJavaProgram.java


C:\> java MyFirstJavaProgram
Hello World

Basic Syntax:

About Java programs, it is very important to keep in mind the following points.

Case Sensitivity - Java is case sensitive, which means identifier Hello and hello would
have different meaning in Java.

Class Names - For all class names the first letter should be in Upper Case.

If several words are used to form a name of the class, each inner word's first letter should
be in Upper Case.

Example class MyFirstJavaClass

Method Names - All method names should start with a Lower Case letter.

If several words are used to form the name of the method, then each inner word's first
letter should be in Upper Case.

Example public void myMethodName()

Program File Name - Name of the program file should exactly match the class name.

When saving the file, you should save it using the class name (Remember Java is case
sensitive) and append '.java' to the end of the name (if the file name and the class name
do not match your program will not compile).

Example: Assume 'MyFirstJavaProgram' is the class name. Then the file should be saved
as 'MyFirstJavaProgram.java'

public static void main(String args[]) - Java program processing starts from the main()
method which is a mandatory part of every Java program.

Java Identifiers:

All Java components require names. Names used for classes, variables and methods are called
identifiers.

In Java, there are several points to remember about identifiers. They are as follows:

All identifiers should begin with a letter (A to Z or a to z), currency character ($) or an
underscore (_).

After the first character identifiers can have any combination of characters.

A key word cannot be used as an identifier.


Most importantly identifiers are case sensitive.

Examples of legal identifiers: age, $salary, _value, __1_value

Examples of illegal identifiers: 123abc, -salary

Java Modifiers:

Like other languages, it is possible to modify classes, methods, etc., by using modifiers. There
are two categories of modifiers:

Access Modifiers: default, public , protected, private

Non-access Modifiers: final, abstract, strictfp

We will be looking into more details about modifiers in the next section.

Java Variables:

We would see following type of variables in Java:

Local Variables

Class Variables (Static Variables)

Instance Variables (Non-static variables)

Java Arrays:

Arrays are objects that store multiple variables of the same type. However, an array itself is an
object on the heap. We will look into how to declare, construct and initialize in the upcoming
chapters.

Java Enums:

Enums were introduced in java 5.0. Enums restrict a variable to have one of only a few
predefined values. The values in this enumerated list are called enums.

With the use of enums it is possible to reduce the number of bugs in your code.

For example, if we consider an application for a fresh juice shop, it would be possible to restrict
the glass size to small, medium and large. This would make sure that it would not allow anyone
to order any size other than the small, medium or large.

Example:
class FreshJuice {

enum FreshJuiceSize{ SMALL, MEDIUM, LARGE }


FreshJuiceSize size;
}

public class FreshJuiceTest {


public static void main(String args[]){
FreshJuice juice = new FreshJuice();
juice.size = FreshJuice.FreshJuiceSize.MEDIUM ;
System.out.println("Size: " + juice.size);
}
}

Above example will produce the following result:

Size: MEDIUM

Note: enums can be declared as their own or inside a class. Methods, variables, constructors can
be defined inside enums as well.

Java Keywords:

The following list shows the reserved words in Java. These reserved words may not be used as
constant or variable or any other identifier names.

Comments in Java

Java supports single-line and multi-line comments very similar to c and c++. All characters
available inside any comment are ignored by Java compiler.

public class MyFirstJavaProgram{

/* This is my first java program.


* This will print 'Hello World' as the output
* This is an example of multi-line comments.
*/

public static void main(String []args){


// This is an example of single line comment
/* This is also an example of single line comment. */
System.out.println("Hello World");
}
}

Using Blank Lines:

A line containing only white space, possibly with a comment, is known as a blank line, and Java
totally ignores it.

Inheritance:

In Java, classes can be derived from classes. Basically if you need to create a new class and here
is already a class that has some of the code you require, then it is possible to derive your new
class from the already existing code.

This concept allows you to reuse the fields and methods of the existing class without having to
rewrite the code in a new class. In this scenario the existing class is called the superclass and the
derived class is called the subclass.

Interfaces:

In Java language, an interface can be defined as a contract between objects on how to


communicate with each other. Interfaces play a vital role when it comes to the concept of
inheritance.

An interface defines the methods, a deriving class(subclass) should use. But the implementation
of the methods is totally up to the subclass.

What is Next?

The next section explains about Objects and classes in Java programming. At the end of the
session you will be able to get a clear picture as to what are objects and what are classes in Java.

You might also like