Introduction to Java Programming Basics
Introduction to Java Programming Basics
1.1Introduction:
Java is an Object-oriented Programming language originally developed by Sun Micro
System and released in 1995, later acquired by Oracle.
Java is a popular and powerful language used in app development, desktop computing,
and gaming. It was created by James Gosling, Mike Sheridan, and Patrick Naughton.
Java was developed as a part of the Green project. Initially, it was called Oak, later it was
changed to Java in 1995.
Java was created based on C and C++. Java uses C syntax and many of the object-oriented
features are taken from C++.
1.2History of Java:
James Gosling, Mike Sheridan, and Patrick Naughton initiated the Java language project in
June 1991. The small team of sun engineers called Green Team.
Originally designed for small, embedded systems in electronic appliances like set-top
boxes.
Firstly, it was called “Greentalk” by James Gosling, and file extension was .gt.
After that, it was called Oak and was developed as a part of the Green project. In 1995,
Oak was renamed as “Java” because it was already a trademark by Oak Technologies.
Java is an island of Indonesia It is famous for its coffee beans
1.3 VARIABLES
Variable is a symbolic name refer to a memory location used to store values that can change during the
execution of a program.
Example:
Avariable declaration involves specifying the type (data type), name (identifier), and value(literal)
according to the type of the variable.
class PrimitiveDt
{
public static void main(String args[])
{
[Link]("Size of byte is " + [Link] + " bits");
[Link]("Size of short is " + [Link] + " bits");
[Link]("Size of int is " + [Link]+ " bits");
[Link]("Size of long is " + [Link]+ " bits");
[Link]("Size of float is " + [Link]+ " bits");
[Link]("Size of double is " + [Link]+ " bits");
[Link]("Size of char is " + [Link]+ " bits");
}
}
To find and print size of any primitive data type we take help of its associated wrapper
class.
Inside each wrapper class (Except Boolean type) there is SIZE property, which returns
amount of memory being allocated for that specific type of data in bits.
1.5. FLOW OF CONTROL
Control flow statements help programmers make decisions about which statements to execute
and to change the flow of execution in a program.
The categories of control flow statements available in Java are
Conditional
Statements
Loops
Branch Statements
if statement
if-else statement
if-else if statement
switch statement
[Link] if statement
It consists only true part, If the condition is True, then the block of statements is executed.
Syntax:
if(condition)
{
-------
------- //Block of Statements
}
Example Program:
class If
{
public static void main(String args[])
{
if(20>18)
[Link]("20 is greater than 18");
}
}
Example Program:
class Ifelse
{
public static void main(String
args[])
{
if(18>20)
[Link]("18 is greater than 20");
else
[Link]("18 is less than 20");
}
}
[Link] if else if statement
Writing an if-statement inside else of an if statement is called if-else-if statement.
Syntax:
if(condition)
{
------- //Block of Statements
}
else if(condition)
{
------- //Block of Statements
}
else
{
------- //Block of Statements
}
Example Program:
class Ifelseif
{
public static void main(String args[])
{
int x=20, y=18, z=22;
if(x>y && x>z)
{
[Link]("Largest Number is "+x);
}
else if(y>z)
{
[Link]("Largest Number is "+y);
}
else
{
[Link]("Largest Number is "+z);
}
}
}
[Link] Switch statement
Java has a shorthand for multiple if statement-the switch statement. Using the switch statement,
one can select only one option from more number of options very easily.
Syntax:
switch(condition or value)
{
case value1: statement 1;
break;
case value2: statement 2;
break;
.
.
default: statement n;
}
Example Program:
class SwitchCaseDemo
{
public static void main(String args[])
{
char c='B';
switch(c)
{
case 'A':[Link]("You entered Sunday");
break;
case 'B':[Link]("You entered Monday");
break;
case 'C':[Link]("You entered Tuesday");
break;
case 'D':[Link]("You entered Wednesday");
break;
case 'E':[Link]("You entered Thursday");
break;
case 'F':[Link]("You entered Friday");
break;
case 'G':[Link]("You entered Saturday");
break;
default:[Link]("Wrong choice");
}
}
}
1.5.2 Loops
The java programming language provides a set of iterative statements that are used to execute a
statement or a block of statements repeatedly as long as the given condition is true. The
iterative statements are also known as looping statements or repetitive statements. Java
provides the following iterative statements.
while statement
do-while statement
for statement
for-each statement
[Link] for Loop
The for statement is used to execute a single statement or a block of statements repeatedly as
long as the given condition is TRUE. To execute a code for a known number of times, for loop is
the right choice.
The for loop groups the following three common parts together into one statement:
(a) Initialization
(b) Condition
(c) Increment or decrement
Syntax:
for(initialization;Condition;Inc/Dec)
{
-------
------- //Block of Statements
}
Example :
Example Program 1:
class ForDemo
{
public static void main(String args[])
{
for(int i=1; i<=5; i++)
{
[Link]("Square of "+i+" is "+ (i*i));
}
}
}
Example Program 2:
class ForLoop
{
public static void main(String args[])
{
for(int i=0; i<=10; i++)
{
[Link]("i= "+i);
}
}
}
Syntax:
while(Condition)
{
-------
------- //Block of Statements
}
Example Program 1:
class WhileDemo
{
public static void main(String args[])
{
int i=1;
while(i<=10)
{
[Link]("i= "+i);
i++;
}
}
}
Example Program 2:
class While
{
public static void main(String args[])
{
int i = 1;
while(i<=5)
{
[Link]("Square of " +i+ " is " +(i*i));
i++;
}
}
}
Syntax:
do
{
-------
------- //Block of Statements
}while(Condition);
Example Program 1:
class DoWhileDemo
{
public static void main(String args[])
{
int i = 1;
do
{
[Link]("Square of " +i+ " is " +(i*i));
i++;
}while(i<=5);
}
}
Example Program 2:
class DoWhile
{
public static void main(String args[])
{
int i=1;
do
{
[Link]("i= "+i);
i++;
}while(i<=10);
}
}
Syntax:
for(datatype Variablename : Array)
{
-------
------- //Block of Statements
}
Example Program
class Foreach
{
public static void main(String args[])
{
int arr[]={10,20,30,40,50};
for(int i : arr)
{
[Link]("i= "+i);
}
}
}
class Break
{
public static void main(String args[])
{
int i;
for(i=1;i<=10;i++)
{
if(i==5)
{
break;
}
[Link]("i = "+i);
}
}
}
Example Program 2:
class BreakWhile
{
public static void main(String args[])
{
int i=1;
while(i<=10)
{
if(i==4)
{
break;
}
[Link]("i = "+i);
i++;
}
}
}
Example Program 3:
class Breakforeach
{
public static void main(String args[])
{
int numbers[] = {10, 20, 30, 40, 50};
for(int x : numbers )
{
if( x == 30 )
{
break;
}
[Link]( x );
}
}
}
class PrimeDemo
{
public static void main(String[] args)
{
int i,j;
[Link]("Prime numbers between 1 to 30 : ");
for(i=1;i<30;i++)
{
for(j=2;j<i;j++)
{
if(i%j==0)
break;
}
if(i==j)
{
[Link](j+ " ");
}
}
}}
[Link].1 Labeled break
The java programming language does not support goto statement, alternatively, the break and continue
statements can be used with label.
The labelled break statement terminates the block with specified label. The labeled continue statement
takes the execution control to the beginning of a loop with specified label.
Example Program 1:
class LabelledBreak
{
public static void main(String args[])
{
int i=7;
loop1:
while(i<20)
{
if(i==10)
break loop1;
[Link]("i ="+i);
i++;
}
[Link]("Out of the loop");
} }
Example Program 2:
class LabeledBreakDemo
{
public static void main(String args[])
{
Outer : for(int i = 0; i< 4; i++)
{
for(int j = 1; j < 4; j++)
{
[Link]("i:" + i + " j:" + j);
if(i == 2)
break Outer;
}
}
}
}
class LabeledContinueDemo
{
public static void main(String args[])
{
Outer : for(int i = 0; i< 4; i++)
{
for(int j = 1; j < 4; j++)
{
[Link]("i:" + i + " j:" + j);
if(i == 2)
continue Outer;
}
}
}
}
For Example, Pen is an object. Its name is Reynolds; color is white, known as its state. It is
used to write, so writing is its behavior.
All the member variables and methods are declared within the class. There are three types of variables in
Java: local variables, instance variables, and class variables.
Ex:-
class SalesTaxCalculator
{
float amount = 100.0f; // instance variable
float taxRate = 10.2f; // instance variable
}
1.6.3 Creating Objects
In java, an object is an instance of a class. When an object of a class is created, the class is said to be
instantiated. All the objects that are created using a single class have the same properties and methods.
But the value of properties is different for every object.
Syntax:
Classnameobjectname=new Classname();
where typeis the type of the object (i.e., class name) and name is the name of the reference
variableused to refer the object.
Ex: Area a;
a= new Area();
class SalesTaxCalculator
{
float amount = 100.0f;
float taxRate = 10.2f;
public static void main (String args[ ])
{
SalesTaxCalculator obj1 = new SalesTaxCalculator();
SalesTaxCalculator obj2 = new SalesTaxCalculator();
[Link]("Amount in Object 1: "+ [Link]);
[Link]("Tax Rate in Object 1: "+ [Link]);
[Link]("Amount in Object 2: "+ [Link]);
[Link]("Tax Rate in Object 2: "+ [Link]);
}
}
2. OPERATORS :
An operator performs an action on one or more operands.
An operator that performs an action on one operand is called a unary operator (+, –, ++, – –).
An operator that performs an actionon two operands is called a binary operator (+, –, / , * , and
more).
An operator that performs anaction on three operands is called a ternary operator (? :).
Java provides all the three operators.
2.1Binary Operators
Java providesarithmetic, assignment, relational, shift, conditional, bitwise, and member access
operators.
class ArithmeticDemo
{
public static void main(String args[])
{
int a=25,b=10;
[Link]("Addition is "+(a+b));
[Link]("Subtrction is "+(a-b));
[Link]("Multiplication is "+(a*b));
[Link]("Division is "+(a/b));
[Link]("Remainder is "+(a%b));
}
}
2.1.2 Relational Operators
The relational operators are the symbols that are used to compare two values. That means the relational
operators are used to check the relationship between two values. Every relational operator has two
possible results either TRUE or FALSE.
class LogicalDemo
{
public static void main(String args[])
{
boolean a=true,b=false;
[Link]("Logical OR: "+ (a|b));
[Link]("Logical XOR: "+ (a^b));
[Link]("Logical AND: "+ (a&b));
[Link]("Logical NOT: "+ (!a));
}
}
Unary operators, as the name suggest, are applied to only one operand. They are ++, - -, !, and ~.
Increment and decrement operators can be applied to all integers and floating-point types. They can be
used either in prefix (– –x, ++x) or postfix (x– –, x++) mode.
Prefix Increment/Decrement Operation
int x = 2;
int y = ++x; // x = 3, y = 3
int z = --x; // x = 1, z = 1
Postfix Increment/Decrement Operation
int x = 2;
int y = x++; // x == 3, y == 2
int z = x--; // x = 1, z = 2
2.1.6 Ternary Operators
Ternary operators are applied to three operands. This conditional operator (? :) decides, on the
basis of the first expression, which of the two expressions to be evaluated.
1.1Methods :
The Word method is commonly used in Object-oriented programming. It is similar to a
function in any other programming language.
Method is a block of statements under a name that gets executes only when it is called.
Every method is used to perform a specific task
The major advantage of methods is code re-usability (define the code once, and use it many
times).
In a java programming language, a method defined as a behavior of an object. That means,
every method in java must belong to a class.
Every method in java must be declared inside a class.
Syntax:
[Link](actualArguments);
The method of the class is known as an instance method. It is a non-static method defined in
the class. Before calling or invoking the instance method, it is necessary to create an object of
its class.
Example program 1:
class Circle
{
float pi = 3.14f; //Instance Variable initializer
float radius; //Instance variable declaration
void setRadius(float rad) // Instance Method
{
radius = rad;
}
float calculateArea() //Instance Method
{
float area = pi * radius * radius;
return (area);
}
}
class CallMethod
{
public static void main(String args[])
{
float area1;
Circle cirobj=new Circle(); //Object Creation
[Link](3.0f);
area1=[Link]();
[Link]("Area of Circle = " + area1);
}
}
Example program 2:
class InstanceAdd
{
int a=10, b=20; // Instance variable Initialization
void Add() // Instance Method
{
int sum=a+b;
[Link]("Addition = "+sum);
}
public static void main(String args[])
{
InstanceAddobj=new InstanceAdd();
[Link]();
}
}
1.3 Method Overloading :
Two or more methods can have the same name inside the same class with a different
arguments. This feature is known as method overloading.
Overloading allows us to perform the same action on different types of inputs.
Method Overloading is one way to achieving polymorphism in Java.
Example Program1 :
class Overloaddemo
{
void add(int a,int b)
{
[Link]("Addition of Two integers "+(a+b));
}
void add(float p,float q)
{
[Link]("Addition of Two float arguments "+(p+q));
}
public static void main(String args[])
{
Overloaddemool=new Overloaddemo();
[Link](10,20);
[Link](43.3,35.5);
}
}
Example Program2 :
class Overloaddemo
{
void max(long a,long b)
{
[Link]("max method with long args invoked");
if(a>b)
[Link](a + " is Greater ");
else
[Link](b + " is Greater ");
}
}
}
1.12 Inheritance
The inheritance is a very useful and powerful concept of object-oriented programming. In
java, using the inheritance concept, we can use the existing features of one class in
another class.
The inheritance provides a great advantage called code re-usability.
Inheritance means access the properties and features of one class into another class.
Inheritance Basics
In inheritance, we use the terms like parent class, child class, base class, derived class,
superclass, and subclass.
The Parent class is the class which provides features to another class. The parent class is
also known as Base class or Superclass.
The Child class is the class which receives features from another class. The child class is
also known as the Derived Class or Subclass.
Types of Inheritance
There are five types of inheritances, and they are as follows.
• Simple Inheritance (or) Single Inheritance
• Multiple Inheritance
• Multi-Level Inheritance
• Hierarchical Inheritance
• Hybrid Inheritance
The java programming language does not support multiple inheritance type. However, it provides
an alternate with the concept of interfaces.
In a java programming language, a class extends only one class. Extending multiple classes is not
allowed in java.
1.12.1 Single Inheritance
In this type of inheritance, one child class derives from one parent class.
Example Program:
class Parent
{
void display()
{
[Link]("Base class Method");
}
}
class Child extends Parent
{
void show()
{
[Link]("Child class Method");
}
}
class SingleInheritance
{
public static void main(String args[])
{
Child C=new Child();
[Link]();
[Link]();
}
}
1.12.2Multi-level Inheritance
In this type of inheritance, the child class derives from a class which already derived from
another class.
Example Program:
class Parent
{
void display()
{
[Link]("Base Class Method");
}
}
class Child1 extends Parent
{
void show1()
{
[Link]("Child1 Class Method");
}
}
class Child2 extends Child1
{
void show2()
{
[Link]("Child2 class Method ");
}
}
class MultilevelInheritance
{
public static void main(String args[])
{
Child2 obj=new Child2();
[Link]();
obj.show1(); obj.show2();
}
}
1.12.3Hierarchical Inheritance
In this type of inheritance, two or more child classes derive from one parent class.
Example Program:
class Parent
{
void display()
{
[Link]("Base Class Method");
}
}
class Child1 extends Parent
{
void show1()
{
[Link]("Child1 Class Method");
}
}
class Child2 extends Parent
{
void show2()
{
[Link]("Child2 class Method ");
}
}
class HierarchicalInheritance
{
public static void main(String args[])
{
Child1 obj1=new Child1();
[Link]();
obj1.show1();
Child2 obj2=new Child2();
[Link]();
obj2.show2();
}
}
1.12.4 Hybrid
Inheritance
The hybrid inheritance is the combination of more than one type of inheritance. We may use any
combination as a single with multiple inheritances, multi-level with multiple inheritances, etc.,
Example Program:
class Parent
{
void display()
{
[Link]("Parent class Method ");
}
}
class Child extends Parent
{
void display()
{
[Link]("Child class Method ");
}
}
class Overriding
{
public static void main(String args[])
{
Child C=new Child();
[Link]();
}
}
1.17 Interfaces:
In java, an interface is similar to a class, but it contains abstract methods and static final
variables only. The interface in Java is another mechanism to achieve abstraction.
We may think of an interface as a completely abstract class. None of the methods in the
interface has an implementation, and all the variables in the interface are constants.
The interface in java enables java to support multiple-inheritance. An interface may
extend only one interface, but a class may implement any number of interfaces.
Example Program:
interface Cal
{
int add(int a,int b);
int sub(int a, int b);
int multiply(int a, int b);
int divide(int a, int b);
}
class Calculator implements Cal
{
public int add(int a,int b)
{
return a+b;
}
public int sub(int a,int b)
{
return a-b;
}
public int multiply(int a, int b)
{
return a*b;
}
public int divide(int a, int b)
{
return a/b;
}
public static void main(String args[])
{
Calculator c=new Calculator();
[Link]("Value after Addition = "+[Link](5,2));
[Link]("Value after Subtraction = "+[Link](5,2));
[Link]("Value after Multiplication =
"+[Link](5,2));
[Link]("Value after division = "+[Link](5,2));
}
}
1.17.1 Extending Interfaces
Just like normal classes, interfaces can also be extended. An interface can inherit another
interfaceusing the same keyword extends, and not the keyword implements.
Example Program:
interface A
{
void showA();
}
interface B extends A
{
void showB();
}
Built-in Packages
User-defined Packages
Built-in Packages
The built-in packages are the packages from java API. The Java API is a library of pre-
defined classes, interfaces, and sub-packages. The built-in packages were included in the
JDK.
There are many built-in packages in java, few of them are as java, lang, io, util, awt, javax,
swing, net, sql, etc.
User-defined Packages
The user-defined packages are the packages created by the user. User is free to create their own
packages.
Syntax :-
packagepackageName;
🔔The package statement must be the first statement in the program.
🔔The package name must be a single word.
Package compilation command.
Syntax:
javac -[Link]
-dis used to create a new folder with package name and inside the package folder
[Link] will create .
. (dot)represents the current working directory.
Package running command with package name
Syntax:
java [Link]
Example:
package myPackage;
public class DefiningPackage
{
public static void main(String args[])
{
[Link]("This class belongs to myPackage.");
}
}
Now, save the above code in a file [Link], and compile it using the following
command.
javac -d . [Link]
The above command creates a directory with the package name myPackage, and the
[Link] saved into it.
In java, the import keyword used to import built-in and user-defined packages. When a
package has imported, we can refer to all the classes of that package using their name
directly.
The import statement must be after the package statement, and before any other
statement.
Using an import statement, we may import a specific class or all the classes from a
package.
🔔Using one import statement, we may import only one package or a class.
🔔 Using an import statement, we can not import a class directly, but it must be a part of a package.
🔔 A program may contain any number of import statements.
Syntax
[Link];
Example program on import statement to import a built-in package and Scanner class.
package myPackage;
import [Link];
public class ImportingExample
{
public static void main(String[] args)
{
Scanner read = new Scanner([Link]);
[Link]("Enter a number : ");
int i = [Link]();
[Link]("You have entered a number " + i);
}
}
In the above code, the class ImportingExamplebelongs to myPackagepackage, and it also
importing a class called Scanner from [Link].
package package1;
public class Sample
{
public void display()
{
[Link]("Display Method");
}
}
import [Link];
class Test
{
public static void main(String args[])
{
Sample s=new Sample();
[Link]();
}
}