Java Basics

Here you’ll learn the basics of java in 10 minutes that others take years to understand thoroughly. I’ve covered all the concepts a beginner needs to learn.

● Introduction:

Java is an object-oriented programming (OOP) language through which you can develop programs and logic to solve a problem.

● Why use BlueJ for Java?

BlueJ is a software used for the Java programming language, developed mainly for educational purposes, but also suitable for small-scale software development. It runs with the help of JDK (Java Development Kit).

I’ve been using BlueJ for Java because it is well organized and user-friendly. 

● Data members and Functions:

To make your own program you need to store data and execute your logic. Data members stores your data and Functions have your logic to be executed.

1. Data members (Characteristics):

Imagine a laptop. It would have a name, color, and the number of USB ports. So, its data members are:

  • Name
  • Colour
  • NoUSB (number of USB ports)

In the program they will be written as:

  • String name
  • String color
  • int NoUSB

2. Functions (Behaviour):

Now, the laptop has many functions. Its functions are:

  • It takes input
  • It displays output

In programs, the function will be written as:

  • Input()
  • Output()

Functions and data members are declared inside a class.

● What is class and object?

Class is simply a representation of the type of objects. It is a blueprint that describes the detail of an object. For instance, if ‘Device’ is a class then the smartphone, computer and laptop are its objects.

Object is a unique entity, containing data members (also called characteristics or attributes) and functions (also called behaviour). For instance, a laptop’s characteristics are:

  • It has a name.
  • It is black in colour.
  • It has three USB ports.

And its behaviours are:

  • It takes input.
  • It displays output.

You’ll have to write everything inside a class in your programs.

● What is Package?

Package is a collection of classes. By importing a package, you can use all the classes and classes’ function and data members available in it.

It’s very useful because it shortens your program.

● Visibility Of Class:

Your class needs to be visible in other places of your program to use it. Access specifiers are used to display the visibility of a class, function or data member. There are 4 types of access specifiers:

  • Default: This specifier is activated when no other access specifier is used. Data members or functions of default category can only be used within the same package of the class.
  • Public: The data members and functions which are specified as public can be used anywhere.
  • Private: The data members and functions which are specified as private can be used only within the same class.
  • Protected: The data members and functions which are specified as protected can be used within the class but can be used in another class through inheritance.

● How to create a class?

Class name should be capitalized according to the convention. And you cannot use keywords as a class name. This is how you create a class:

Syntax: <access specifier> class <name of the class>

Example: public class Device

● How to create an object?

Follow 3 steps to create an object of a class:

  • Declare: Use class as data type along with an object. 
  • Instantiate: Use ‘new’ keyword to allocate an object in the dynamic memory.
  • Initialize: Call a constructor to initialize data members of your object. 

Syntax: <class name> <object name>= new <class name>();

Example: Device laptop=new Device();

● How to call functions through object?

To use a function – you can directly call it or call through an object. To call directly:

Syntax:<function> ();

Example: display();

To call the function through an object:

Syntax:<object>.<function>();

Example: laptop.display();

You may wonder why to call a function through an object if it can be called directly? 

You call a function directly when you call it in another function which is not static. Whereas, you call a function through an object when you call it in another function which is static.

● Comments:

Sometimes it’s difficult for the user to understand your program or he can’t figure out the logic of your statements in the program. In these cases, you use comments to explain your logic. There are 3 types of comments:

  • Single line comment: You use it when you can explain in a single line. Syntax:// comments
  • Multi line comment: You use it when you have to explain things in 3 to 4 lines. Syntax:/*comments*/
  • Documentation comment: You use it when you want to insert some text document which does not explain the program logic but serve some other information. Syntax: /**comment*/

● Semicolon:

You have to insert semicolon after every statement. Don’t insert it after class or function or something which has a body in brackets. This is because those are continued in brackets and are not finished just after they have been created.

● How to show your Program Output?

You need an output statement to show the result of execution or display a message. Java provides 2 output statements:

  • System.out.print(): Prints a message or a result. The control remains on the same line after printing.
  • System.out.println(): Prints a message or a result. The control goes to the next line after printing.

Syntax: System.out.println();

Example: System.out.println(“Java is easy”);

● 'Hello world' snippet:

public class Hello_world // Create a class
{
    public static void main() // Create ‘main’ function
    {
        System.out.println(“Hello World”); //To print output
    }
}

This program will display “Hello World”.

● How to import a class of a package?

For instance, you want to import Scanner class of util package then follow the syntax:

Syntax: import java.<package name>.<class name>;

Example: import java.util.Scanner;

Instead of class name use ‘*’ to import all classes of the package.

Example: import java.util.*;

● Data types:

There are 2 categories of data types:

1. Primitive data types: These data types are inbuilt by java. They are:

Float data type can store up to 6 digits whereas double data type can store up to 15 digits.

2. Reference data types: These data types are created by you to be used in your programs. They are: 

  • Class
  • Arrays
  • Interface

● Java Virtual Machine (JVM)

The program which you write in java is in java source code. When you compile then it is converted into byte code. This code is independent of the machine on which the program is to run. This makes a java program highly portable as its byte code can easily be transferred from one system to another. 

When this byte code runs on another system, an interpreter, known as Java Virtual Machine translates the byte code to machine code.

● elements of programs you need to have (tokens):

Tokens is everything in your program which takes part in effective execution of the program. There are 7 types of tokens:

1. Literals:

Literals are the constants (which do not change throughout the program) in Java program. There are 6 types of literals:

2. Punctuators:

These are punctuation signs. Some of them are: (?)Question mark, (;)semi colon, (.)dot.

3. Separators:

They are used to separate the characters or variables. Some of them are: ( ) Brackets, { } Curly brackets, [ ] Square brackets.

4. Variables (Identifiers) :

A variable is a named memory location, which contains a value. You’ll often use it in your program to save or initialize a value.

Syntax:<data type><space><variable name>

Example: int a;

5. Keywords:

Keywords are java reserved words.  They carry special meaning for the system compiler. So, these words can’t be used as variable names in a computer program. Some of them are:

  • static
  • class
  • switch
  • import
  • break
  • for
  • boolean
  • while
  • throw
  • throws
  • if
  • else
  • void
  • final
  • continue
  • import
  • implements
  • try
  • public
  • do

6. Operators:

Operators are tokens which perform arithmetical or logical operations. There are 3 types of operators:

1. Arithmetical Operators: + , – , * , / ,etc. It further contains: unary (operator applied to single operand, e.g ), binary, and ternary operator. 

  • Unary operator: These operators deals with a single operand, e.g,+ ,- ,++ ,–.
  • Binary operators: These operators deals with two operands, e.g, +, >, AND.
  • Ternary operators: This operator deals with three operands. 

Syntax of ternary operator: variable=(test expression)?Expression1: Expression 2;

The variable contains the result of Expression1 if the test result is true, otherwise Expression2.

Example: if a=8;b=5;

max=(a>b)?a:b;

Here the value 8 will be stored in max.

2. Relational Operators: > , < , == , != , >= , etc.

3. Logical Operators: && , || , ! , etc.

7. Assignment:

Assignment means to store constant in variables using a token ‘=’ symbol (known as assignment operator).

Syntax: <variable> = <constant>;

Example: int a= 2;

● Rules for naming class and variable:

  • Name should not start with a digit or special character.
  • Name should not include a space in between its characters.
  • Name should not be a keyword.

● Basic program:

public class Hello_world //Create a class
{
    public static void main() // Create ‘main’ function
    {
        int a=1,b=2,c=a+b; // Create your data members, define their data type and assign value to them
        System.out.println(“Answer is: “+c); // To print output
    }
}

Above program will display “Answer is: 3”.

● How to convert one type of data to another?

There conversions are done by a process called type conversions. There are two types of conversions:

1. Implicit conversion:

In a mixed expression such as d= c+i+f/d , the data type of the result gets converted automatically to its higher type. This is implicit conversion.

2. Explicit conversion:

When the data type gets converted to another type after user intervention, the type conversion is called explicit type conversion. Here, the user forcibly changes the data type of a variable.

Example: d =(int)( c +i +f / d);

● Scanner class

Scanner class is used when you need to take input from user in your program. The code to import Scanner class is:

import java.util.Scanner;

Now to use Scanner class, you’ll have to make an object of it because object is the entity whereas class is a blueprint. Syntax for object creation:

Scanner ob=new Scanner(System.in);

● How to take input from user?

You may ask “How should I accept input from user?”

Scanner class provides you with inbuilt functions to accept values from user. You have to create its object (example in) and call its functions through objects:

  • in.nextInt() : To accept integer values.
  • in.nextLong() : To accept larger integer values.
  • in.nextFloat() : To accept decimal values.
  • in.nextDouble() : To accept larger decimal values.
  • in.next() : To accept a word.
  • in.nextLine() : To accept a sentence.

● Structure of a program:

For starting, you need a structure to organize your program. When you adapt to this programming language then you may manipulate according to your needs. For now, follow this structure:

1. Import a desired class:

Import a class of a package. You’ll definitely need to do so for Scanner class which is in util package if you want to take input from user.

2. Make your own class:

Now, every statement and code you’ll have to write within a class. So create a class and make its body under curly brackets.

3. Make a Constructor:

Constructor is used to initialize your data members. It has the same name as the class name. Even if you don’t make a constructor, a default constructor is then used to initialize data members with garbage value.

4. Make Functions:

You’ll definitely need to make a function to write your code. The most important is the ‘main’ function. When you compile your program, the compiler starts to compile from the main function. Syntax to create main function: 

public static void main() {start writing your code in the curly brackets}.

After creating the function make its body under curly brackets. With main function, you don’t have to make an object of the class separately to run the program. Other than ‘main’ function, you can make your own functions if needed.

5. Create object of the imported class

Create an object of the imported class in the function where you have to use it. For instance, you write code in main function to take input from the user. For those statements to work, you have to make an object of Scanner class in that function.

● Features of Java:

  • Java is an object oriented programming language.
  • Java programs are platform-independent.
  • Java programs are written within a class.
  • Java is case sensitive language. Hence, it will distinguish upper case and lower case language.
  • Java programs can create applets.

● Conclusion:

Now you know the basics you will need in your programs. If you want to know more about Java components in the easiest way then check out my other articles on globalblogs101- java.