Java Programming Basics and Concepts
Java Programming Basics and Concepts
Program Structure in Java: Introduction, Writing Simple Java Programs, Elements or Tokens
in Java Programs, Java Statements, Command Line Arguments, User Input to Programs,
Escape Sequences Comments, Programming Style.
Data Types, Variables, and Operators :Introduction, Data Types in Java, Declaration of
Variables, Data Types, Type Casting, Scope of Variable Identifier, Literal Constants, Symbolic
Constants, Formatted Output with printf() Method, Static Variables and Methods, Attribute
Final, Introduction to Operators, Precedence and Associativity of Operators, Assignment
Operator ( = ), Basic Arithmetic Operators, Increment (++) and Decrement (- -) Operators,
Ternary Operator, Relational Operators, Boolean Logical Operators, Bitwise Logical
Operators.
INTRODUCTION TO JAVA:
Java is a popular object-oriented programming language, developed by sun micro
systems of USA in 1991(which has since been acquired by oracle). originally it was called as
oak. the developers of java are james gosling and his team (patrick naughton, chris warth, ed
frank, and mike sheridan). this language was renamed as “java” in 1995. java was publicly
announced in 1995. and now more than 3 billion devices run java.
Features of Java:
• Platform Independence: Java works on different platforms (Windows, Mac, Linux,
Raspberry Pi, etc.) and Programs developed in JAVA are executed anywhere on any
system.
• Simple: They made java simple by eliminating difficult concepts of C and C++.
example the concept of pointers and Java is simple because it has the same syntax of C
and C++
• Object Oriented: Object oriented throughout - no coding outside of class definitions,
including main ().
• Compiler/Interpreter Combo: Usually a computer language is either compiled or
interpreted. Java combines both these approaches thus making java a two-stage
[Link], java compiler translates source code into bytecode. Bytecodes are not
machine instructions and therefore, in the second stage, java interpreter generates
machine code that can be directly executed by the machine that is running the java
program so we can say that java is both compiled and interpreted language.
• Robust: because of the following concept included in java it is called as robust
1. Exception handling
2. strong type checking
3. local variables must be initialized.
• Automatic Memory Management: Automatic garbage collection - memory
management handled by JVM.
• Security: Security problems like eavesdropping, tampering, impersonation and virus
threats can be eliminated or maintained by using java on internet.
• Dynamic Binding: The linking of data and methods to where they are located, is done
at run-time.
• High Performance: The Java language supports many high-performance features such
as multithreading, just-in-time compiling, and native code usage.
• Threading: A thread represents an individual process to execute a group of statements.
JVM uses several threads to execute different block of code.
• Built-in Networking: Java was designed with networking in mind and comes with
many classes to develop sophisticated Internet communications.
• It is open-source and free
• It is secure, fast and powerful
A token is the smallest element of a program that is meaningful to the compiler. Tokens can be
classified as follows:
• Keywords
• Identifiers
• Constants
• Special Symbols
• Operators
1. Keyword: Keywords are pre-defined or reserved words in a programming language.
Each keyword is meant to perform a specific function in a program. Since keywords
are referred names for a compiler, they can’t be used as variable names because by
doing so, we are trying to assign a new meaning to the keyword which is not
allowed. Java language supports following keywords:
2. Identifiers: Identifiers used for naming classes, methods, variables, objects, labels and
interfaces in a program.
2. All classes and interfaces should start with capital letter, for more then one word
the second word’s first character should be capital.
Ex:- Student, HelloJava
3. Constant variables should be in capital letters and for more than one word
underscore is used.
Ex:- MAX, TOTAL_VALUE
3. Constants: Constants are also like normal variables. But the only difference is, their
values cannot be modified by the program once they are defined. Constants refer to
fixed values. They are also called as literals. Constants may belong to any of the data
type.
Syntax: final data_type variable_name;
4. Special Symbols: The following special symbols are used in Java having some
special meaning and thus, cannot be used for some other purpose.
[] () {}, ; * =
• Brackets[]: Opening and closing brackets are used as array element reference.
These indicate single and multidimensional subscripts.
• Parentheses(): These special symbols are used to indicate function calls and
function parameters.
• Braces{}: These opening and ending curly braces marks the start and end of a
block of code containing more than one executable statement.
• comma (, ): It is used to separate more than one statements like for separating
parameters in function calls.
• semi colon : It is an operator that essentially invokes something called an
initialization list.
• asterick (*): It is used to create pointer variable.
• assignment operator: It is used to assign values.
5. Operators: Java provides many types of operators which can be used according to the
need. They are classified based on the functionality they provide. Some of the types
are-
• Arithmetic Operators
• Unary Operators
• Assignment Operator
• Relational Operators
• Logical Operators
• Ternary Operator(conditional operator)
• Bitwise Operators and bit-shift operators
• instance of operator
Package statement:
This is the first statement in java file. This statement declares a package name and informs
the compiler that the class defined here belong to this package.
Ex: - package student
Import statements:
This is the statement after the package statement. It is similar to # include in c/c++.
Ex: import [Link]
The above statement instructs the interpreter to load the String class from the lang package.
Note:
• Import statement should be before the class definitions.
• A java file can contain N number of import statements.
Interface statements:
An interface is like a class but includes a group of method declarations.
Note: Methods in interfaces are not defined just declared.
Class definitions:
Java is a true oop, so classes are primary and essential elements of java program. A program
can have multiple class definitions.
Static:
The keyword static allows main() to be called without creating any instance of that class.
This is necessary because main() is called by java interpreter before creating any object.
Void:
The keyword void tells the compiler that main() does not return any value.
main():
main() is the method called when a java application begins.
String args[]:
Any information that you pass to a method is received by variables specified with in the set of
parenthesis that follow the name of the method. These variables are called parameters. Here
args[] is the name of the parameter of string type.
[Link]:
It is equal to printf() or cout<<, since java is a true object oriented language, every method
must be part of an object.
The println method is a member of out object, which is a static data member of System class.
Note: println always appends a newline character to the end of the string. So the next println
prints the statements in next line.
How it works…!
Compile-time Environment Run-time Environment
Class
Loader Java
Class
Bytecode Libraries
Java Verifier
Source
(.java)
Just in
Java Java
Time
Bytecodes Interpreter Java
Compiler
move locally Virtual
or through machine
Java network
Compiler
Runtime System
JAVA STATEMENTS:
• A statement specifies an action in a Java program.
• Java statements can be broadly classified into three categories:
• Declaration statement
• Expression statement
• Control flow statement
For example,
int num;
int num2 = 100;
String str;
Java Expression Statement: An expression with a semicolon at the end is called an
expression statement. For example,
//Assignment expressions
num = 100;
num *= 10;
By default, all statements in a Java program are executed in the order they appear in the
program. Sometimes you may want to execute a set of statements repeatedly for a number of
times or as long as a particular condition is true.
All of these are possible in Java using flow control statements. The if statement, while
loop statement and for loop statement are examples of control flow statements.
the time of execution. The parameters are received by args array of string type.
class Commarg
int i=0,l;
l=[Link];
while(i<l)
[Link](args[i]);
i++;
Ex:
C:..\> java Commarg hello how are u
output:
number of arguments are : 4
hello
how
are
u
Note: From the above output it is clear that hello is stored at args[0]
Position and so on…..
Example-2:
Program to add two no’s using command line arguments.
class CmdAdd2
{
public static void main(String args[])
{
// if two arguments are not entered then come out
if([Link]!=2)
{
[Link]("Please enter two values....");
return;
}
int a=[Link](args[0]);
int b=[Link](args[1]);
int c=a+b;
[Link]("The Result is:"+c);
}
}
To run the program:
> java CmdAdd2 10 20
• The Scanner class is used to get user input, and it is found in the [Link] package.
• To use the Scanner class, create an object of the class and use any of the available
methods found in the Scanner class.
• For Example, we will use the nextLine() method to read String.
Input Types and their respective methods:
Method Description
Example:
import [Link];
class Main {
// String input
// Numerical input
JAVA COMMENTS:
• Comments can be used to explain Java code, and to make it more readable. It can also
be used to prevent execution when testing alternative code.
• Any text between // and the end of the line is ignored by Java (will not be executed).
Example
// This is a comment
[Link]("Hello World");
[Link]("Hello World");
A character preceded by a backslash (\) is an escape sequence and has a special meaning to the
compiler.
The following table shows the Java escape sequences.
Escape Sequence Description
DATA TYPES IN JAVA: Datatype specifies the size and types of values that a variable
hold. Java is rich in it’s data types.
Primitive Data Types: A primitive data type specifies the size and type of variable values, and
it has no additional methods.
Note 1: Note that you should end the value with an "f"
Note 2: Note that you should end the value with a "d"
Example:
int num = 5;
float num1 = 5.99f;
double num3=5.7896d;
char ch = 'D';
boolean status = true;
String name = "sai";
[Link]("Value inside integer type variable " + num);
[Link]("Value inside float type variable " + num1);
[Link]("Value inside double type variable " + num1);
[Link]("Value inside character type variable " + ch);
[Link]("Value inside boolean type variable " + status);
[Link]("Value inside string type variable " + name);
Note: A String in Java is actually a non-primitive data type, because it refers to an object.
The String object has methods that are used to perform certain operations on strings.
Type casting:Converting one datatype into another type is called “Type casting”.
Data types:
There are two types of data types.
• primitive data types or Fundamental data types.
o These data types will represent single entity (or value).
o Ex : int, char, byte,…….
• Referenced Data types or Advanced Data types.
o These Data types represent several values.
o Ex: arrays, classes, enums,…
Note: We can convert a primitive type to another primitive type and a Referenced type to
another Referenced type, but to convert Primitive type to Referenced type and Referenced
type to Primitive type Wrapper classes are used.
Casting primitive Data types:
• It is done in two ways
o Widening
o Narrowing
• The primitives are classified into two types lower types and higher types.
Ex: 2
int x=5000;
float sal=(float)x;
...here sal will contain 5000.0
Widening is safe because there will not be any loss of data or precision or accuracy. So
widening is done by compiler automatically.
Ex 1:
char ch=’A’;
int no=ch;
Ex 2:
int x=5000;
float sal=x;
widening is also known as implicit casting.
Narrowing implicit Data types:
Converting higher data type into lower data type is called narrowing.
Ex 1:
int n=65;
char ch=(char)n;
... here ch will contain A
Ex 2:
double d=12.890;
int x=(int)d;
.. here x will contain 12
narrowing is unsafe because there will be loss of data or precision or accuracy. So narrowing
is not done by compiler automatically. The programmer has to use cast operator explicitly.
Narrowing is also called Explicit casting.
Static methods:
•
A static method is a method that does not act upon instance variables of a class.
•
A static method is declared by using the keyword static.
•
Static methods are called using [Link]()
•
The reason why static methods cannot act on instance variables is that JVM first loads
static elements of the .class file one specific memory location inside the RAM and
then searches for the main method, and then only it creates the objects.
• Since objects are not available at the time calling static methods, the instance
variables are also not available at the time of calling the static methods.
• Static methods are also called as class methods.
• They cannot refer to this or super keywords (super used in inheritance)
Example:
class Smethod
{
static void disp()
{
[Link]("Hi....");
}
public static void main(String args[])
{
disp();
disp();
disp();
}
}
Static variable:
• The variables that are created comman to all the objects are called static
variables/class variables.
• The static variables belong to the class as a whole rather than the objects.
• It is mainly used when we need to count no of objects created for the class
Example:
class emp
{
int eno;
String name;
static int count;
Count
emp(int no,String str) 2
{
No- 101 No- 102
eno=no;
Name-tanu Name-man
name=str;
count++;
} e1 e2
}
class EmpCount
{
public static void main(String args[])
{
emp e1=new emp(101,"tan");
emp e2=new emp(102,"manu");
[Link]("No of objects are:"+[Link]);
}
}
Formatted Output with printf() Method(Displaying output with [Link]()):
To format and display the output, printf() method is available in PrintStream class.
This method works similar to printf() function in C.
Note: printf() is also available from J2SE 5.0 or later.
The following format characters can be used in printf():
• %s – String
• %c – char
• %d – decimal integer
• %f – float number
• %o – octal number
• %b, %B – Boolean value
• %x, %X – hexadecimal value
• %e, %E – number scientific notation
• %n – new line character
Example :
class PrintfDemo
{
public static void main(String[] args)
{
String s="sai";
int n=65;
float f=15.45f;
[Link](" String =%s %n number=%d %n HexaDecimal=%x %n
Float=%f",s,n,n,f);
}
}
Attribute Final:
Final variables: It is just like const in c/c++, which restricts the user to modify. The value of
final variable is finalized at the time of declaration it self.
Ex:
final double PI=3.14
example:
class Final
{
public static void main(String args[])
{
final int a=10;
[Link]("before modification:"+a);
a=a+10; //Error: cannot assign a value to final variable a a=a+10;
[Link]("after modification:"+a);
}
}
For-each loop:
The enhanced for loop, new to java 5, is a specialized for loop that simplifies looping
through an array or a collection.
Syntax:
for(declaration: expression)
{
---
---
}
Declaration: Its Data type should be same as the current array element.
Expression: It should be the array variable
Example:
class Loop
{
public static void main(String args[])
{
int x[]={10,20,30,40,50};
float y[]={1.5f,2.5f,3.5f,4.5f,5.5f};
String names[]={"vahida","madhuri","lalitha","anil","manik"};
for(int i:x)
{
[Link](i);
}
for(float j:y)
{
[Link](j);
}
for(String s:names)
{
[Link](s);
}
}
}
Classes and Objects: Introduction, Class Declaration and Modifiers, Class Members,
Declaration of Class Objects, Assigning One Object to Another, Access Control for Class
Members, Accessing Private Members of Class, Constructor Methods for Class, Overloaded
Constructor Methods, Nested Classes, Final Class and Methods, Passing Arguments by Value
and by Reference, Keyword this.
Class:
class ClassName
{
VariableDeclaration-1;
VariableDeclaration-2;
VariableDeclaration-3;
------------------------
------------------------
VariableDeclaration-n;
Object:
Class Members:
All the variable declared and method defined inside a class are called class members.
Instance variables: The variables defined within a class are called instance Variables (data
members).
Methods: The block in which code is written is called method (member functions).
The Java programming language defines the following kinds of variables:
There are 4 types of java variables
• instance variables
• class variables
• local variables
• Parameters
Instance variables:
Instance variables are declared inside a class. Instance variables are created when the
objects are instantiated (created). They take different values for each object.
Class variables:
Class variables are also declared inside a class. These are global to a class. So these
are accessed by all the objects of the same class. Only one memory location is created for a
class variable.
Local variables:
Variables which are declared and used with in a method are called local variables.
Parameters:
Variables that are declared in the method parenthesis are called parameters.
Class and Object Example:
class Test
{ int a; //default access
void setData(int i)
{
a=i;
}
int dispData()
{
return a;
}
}
class AccessTest
{
public static void main(String args[])
{
Test ob=new Test(); //object creation
[Link](100);
[Link](" value of a is:-”+[Link]());
}
}
Access specifiers (Or) Access Control (Or) access Modifiers or Access Control for Class
Members (Or) Accessing Private Members of Class:
An access specifier determines which feature of a class (class itself, data members,
methods) may be used by another classes.
Java supports four access specifiers:
1. The public access specifier
2. The private access specifier
3. The protected access specifier
4. The Default access specifier
Public:
If the members of a class are declared as public then the members (variables/methods) are
accessed by out side of the class.
Private:
If the members of a class are declared as private then only the methods of same class can
access private members (variables/methods).
Protected:
Discussed later at the time of inheritance.
Default access:
If the access specifier is not specified, then the scope is friendly. A class, variable, or method
that has friendly access is accessible to all the classes of a package (A package is collection
of classes).
Example:
class Test
{
int a; //default access
public int b; // public access
private int c; // private access
//methods to access c
void setData(int i)
{
c=i;
}
int dispData()
{
return c;
}
}
class AccessTest
{
public static void main(String args[])
{
Test ob=new Test();
//a and b can be accessed directly
ob.a=10;
ob.b=20;
// c can not be accessed directly because it is private
//ob.c=100; // error
// private data must be accessed with methods of the same class
[Link](100);
[Link](" value of a, b and c are:"+ob.a+" "+ob.b+"
"+[Link]());
[Link]();
}
}
Assigning One Object to Another or Cloning of objects:
We can copy the values of one object to another using many ways like :
Example:
class Copy
{
int a=10;
}
class CopyObject
{
public static void main(String args[])
{
Copy c1=new Copy();
Copy c2=c1;
[Link]("object c1 value-"+c1.a);
[Link]("object c2 value-"+c2.a);
}
}
Constructors:
1. JAVA provides a special method called constructor which enables an object to
initialize itself when it is created.
2. Constructor name and class name should be same.
3. Constructor is called automatically when the object is created.
4. Person p1=new Person() → invokes the constructor Person() and Initializes the
Person object p1.
5. Constructor does not return any return type (not even void).
There are two types of constructors.
Default constructor: A constructor which does not accept any parameters.
Parameterized constructor:A constructor that accepts arguments is called parameterized
constructor.
Default constructor Example:
class Rectangle
{
int length,bredth; // Declaration of variables
Rectangle() // Default Constructor method
{
[Link]("Constructing Rectangle..");
length=10;
bredth=20;
}
int rectArea()
{
return(length*bredth);
}
}
class Rect_Defa
{
public static void main(String args[])
{
Rectangle r1=new Rectangle();
[Link]("Area of rectangle="+[Link]());
}
}
Note: If the default constructor is not explicitly defined, then system default constructor
automatically initializes all instance variables to zero.
Parameterized constructor:
class Rectangle
{
int length,bredth; // Declaration of variables
Rectangle(int x,int y) // Constructor method
{
length=x;
bredth=y;
}
int rectArea()
{
return(length*bredth);
}
}
class Rect_Para
{
public static void main(String args[])
{
Rectangle r1=new Rectangle(5,10);
[Link]("Area of rectangle="+[Link]());
}
}
Writing more than one constructor with in a same class with different parameters is
called constructor overloading.
Example:
class Addition
{
int a,b;
Addition()
{
a=10;
b=20;
}
Addition(int a1,int b1)
{
a=a1;
b=b1;
}
void add()
{
[Link]("Addition of "+a+" and "+b+" is "+(a+b));
}
}
class ConsoverLoading
{
public static void main(String args[])
{
Addition obj=new Addition();
[Link](); //output:30
Addition obj2=new Addition(2,3);
[Link](); // output: 5
}
}
Nested Classes: nested class is a class that is declared inside the class or interface. it can
access all the members of the outer class, including private data members and methods.
Advantages:
1. Nested classes can access all the members (data members and methods) of the outer
class, including private.
2. to develop more readable and maintainable code
3. Code Optimization
Syntax of Inner class
class Java_Outer_class
{
//code
class Java_Inner_class
{
//code
}
}
Types of Nested classes
There are two types of nested classes non-static and static nested classes. The non-static nested
classes are also known as inner classes.
o Non-static nested class (inner class)
1. Member inner class
2. Anonymous inner class
3. Local inner class
o Static nested class
Example: local inner class
public class localInner1
{
private int data=30;//instance variable
void display()
{
class Local
{
void msg()
{
[Link](data);
}
}
Local l=new Local();
[Link]();
}
public static void main(String args[]){
localInner1 obj=new localInner1();
[Link]();
}
}
Syntax:
final class A
{
----
----
}
class B extends A // cannot be inherited
{ ---
----
}
class A
{
int a=10;
final void display()
{
[Link]("I am display() of class-A");
[Link]("my value is:"+a);
}
}
class B extends A
{
int b=20;
void display() //can’t be overriden
{
[Link]("I am display() of class-B");
[Link]("my value is:"+b);
}
}
class Final_Methods_Classes
{
public static void main(String args[])
{
B b=new B();
[Link]();
}
}
‘this’ keyword:
• ‘this’ is a keyword that referes to the object of the class where it is used.
• When an object is created to a class, a default reference is also created internally to
the object.
class Sample
{
private int x;
Sample()
{
this(10); // calls parameterized constructor and sends 10
[Link](); //calls present class method
}
Sample(int x)
{
this.x=x; // referes present class reference variable
}
void access()
{
[Link]("X ="+x);
}
}
class ThisDemo
{
public static void main(String[] args)
{
Sample s=new Sample();
}
}
Methods in java:
Predefined method:
In Java, predefined methods are the method that is already defined in the Java class libraries
is known as predefined methods. It is also known as the standard library method or built-in
method. We can directly use these methods just by calling them in the program at any point.
Some pre-defined methods are length(), equals(), compareTo(), sqrt(), etc. When we call any
of the predefined methods in our program, a series of codes related to the corresponding method
runs in the background that is already stored in the library.
Each and every predefined method is defined inside a class. Such as print() method is
defined in the [Link] class. It prints the statement that we write inside the method.
For example, print("Java"), it prints Java on the console.
Example:
User-defined Method:
Example:
import [Link];
//user defined method
public static void findEvenOdd(int num)
{
//method body
if(num%2==0)
[Link](num+" is even");
else
[Link](num+" is odd");
}
public class EvenOdd
{
public static void main (String args[])
{
//creating Scanner class object
Scanner scan=new Scanner([Link]);
[Link]("Enter the number: ");
//reading value from the user
int num=[Link]();
//method calling
findEvenOdd(num);
}
}
}
}
Recursive Methods:
A method can be called by using only its name by another method of the same class that is
called Nesting of Methods.
Syntax:
class Main
{
method1()
{
// statements
}
method2()
{
// statements
Example:
public class NestingMethod
{
public void a1()
{
[Link]("****** Inside a1 method ******");
// calling method a2() from a1() with parameters a
a2();
}
public void a2()
{
[Link]("****** Inside a2 method ******");
}
public void a3()
{
[Link]("****** Inside a1 method ******");
a1();
}
public static void main(String[] args)
{
// creating the object of class
NestingMethod n=new NestingMethod();
Note: when a super class method is overridden by the sub class method calls only the sub
class method and never calls the super class method. We can say that sub class method is
replacing super class method.