Documente Academic
Documente Profesional
Documente Cultură
Programming Languages
Machine languages
Assembly languages
High-Level languages
1. Machine languages
Machine language is the lowest-level programming language. Machine languages are
the only languages understood by computers. machine languages are almost impossible for
humans to use because they consist entirely of numbers.
2. Assembly languages
An assembly language implements a symbolic representation of the machine code
needed to program a given CPU architecture. An assembly language is the most basic
programming language available for any processor.
Assembly languages generally lack high-level conveniences such as variables and functions,
and they are not portable between various families of processors.
3. High-Level languages
A high-level language (HLL) is a programming language that enables a programmer to
write programs that are more or less independent of a particular type of computer.
Such languages are considered high-level because they are closer to human languages and
further from machine languages.
OOP’s main concern is to hide the data from non-member functions of a class, which it
treats like “critical information”. Data is closely tied to the member functions of a class,
which operates on it. It doesn’t allow any non-member function to modify the data inside it.
Objects communicate with each other through member functions to access their data.
A Program can be written in both the languages, but if the task is highly complex, OOP
operates well as compared to POP.
In POP, the ‘data security’ is at risk as data freely moves in the program, as well as, ‘code
reusability’ is not achieved which makes the programming lengthy, and hard to understand.
Large programs lead to more bugs, and it increases the time of debugging. All these flaws
(faults) lead to a new approach namely “object-oriented programming”.
In object-oriented programming’s main concern is given on ‘data security’; it binds the data
closely to the functions which operate on it. It also resolves the problem of ‘code
reusability’, as if a class is created, its multiple instances (objects) can be created which
reuses the members and member functions defined by a class.
Comparison Chart
BASIS FOR
POP OOP
COMPARISON
Division Large program is divided into units Entire program is divided into
called functions. objects.
Entity accessing mode No access specifier observed. Access specifier are "public",
"private", "protected".
Data hiding & security There is no proper way of hiding Data is hidden in three modes
the data, so data is insecure public, private, and protected.
hence data security increases.
Data sharing Global data is shared among the Data is shared among the
functions in the program. objects through the member
functions.
Conclusion
The flaws (fault) of POP arises the need of OOP. OOP corrects the flaws (fault) of POP by
introducing the concept of “object” and “classes”. It enhances the data security, and
automatic initialization & clear-up of objects. OOP makes it possible to create multiple
instances of the object without any interference.
Since main() method of java is not returning any value and hence its return type must be
void.
Since main() method of java executes only once throughout the java program execution
and hence its nature must be static.
Since main() method must be accessed by every java programmer and hence whose access
specifier must be public.
Each and every main() method of java must take array of objects of String.
Block of statements represents set of executable statements which are in term calling user-
defined methods are containing business-logic.
The file naming conversion in the java programming is that which-ever class is containing
main() method, that class name must be given as a file name with an extension .java.
OOPs Concepts:
Object
Class
Inheritance
Polymorphism
Abstraction
Encapsulation
Message Passing
1. Object :
It is a basic unit of Object Oriented Programming and represents the real life entities. A typical
Java program creates many objects, which as you know, interact by invoking methods. An object
consists of :
1. State : It is represented by attributes of an object. It also reflects the properties of an object.
2. Behavior : It is represented by methods of an object. It also reflects the response of an
object with other objects.
3. Identity : It gives a unique name to an object and enables one object to interact with other
objects.
Example of an object : dog
Objects correspond to things found in the real world. For example, a graphics program may have
objects such as “circle”, “square”, “menu”. An online shopping system might have objects such
as “shopping cart”, “customer”, and “product”.
2. Class:
A class is a user defined blueprint or prototype from which objects are created. It represents the
set of properties or methods that are common to all objects of one type. In general, class
declarations can include these components, in order:
Class is user defined data type, on which objects are created.
Class is “blueprint”––
Class is a “prototype”
3. Inheritance
1. Inheritance
2. Types of Inheritance
Inheritance in Java is a mechanism in which one object acquires all the properties and
behaviors of a parent object. It is an important part of OOPs (Object Oriented programming
system).
The idea behind inheritance in Java is that you can create new classes that are built upon
existing classes. When you inherit from an existing class, you can reuse methods and fields
of the parent class. Moreover, you can add new methods and fields in your current class
also.
o Sub Class/Child Class: Subclass is a class which inherits the other class. It is also
called a derived class, extended class, or child class.
o Super Class/Parent Class: Superclass is the class from where a subclass inherits the
features. It is also called a base class or a parent class.
The extends keyword indicates that you are making a new class that derives from an
existing class. The meaning of "extends" is to increase the functionality.
In the terminology of Java, a class which is inherited is called a parent or superclass, and the
new class is called child or subclass.
On the basis of class, there can be three types of inheritance in java: single, multilevel and
hierarchical.
In java programming, multiple and hybrid inheritance is supported through interface only.
We will learn about interfaces later.
class Animal
{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal
{
void bark(){System.out.println("barking...");}
}
class TestInheritance
{
public static void main(String args[])
{
Dog d=new Dog();
d.bark();
d.eat();
}
}
different behaviors.
5. Abstraction
Data Abstraction may also be defined as the process of identifying only the required
characteristics of an object ignoring the irrelevant details.
Consider a real-life example of a man driving a car. The man only knows that pressing the
accelerators will increase the speed of car or applying brakes will stop the car but he does
not know about how on pressing the accelerator the speed is actually increasing, he does not
know about the inner mechanism of the car or the implementation of accelerator, brakes etc
in the car. This is what abstraction is.
6. Encapsulations
Encapsulation is defined as the wrapping up of data under a single unit. It is the
mechanism that binds together code and the data it manipulates.
Other way to think about encapsulation is, it is a protective shield that prevents the
data from being accessed by the code outside this shield.
Technically in encapsulation, the variables or data of a class is hidden from any other
class and can be accessed only through any member function of own class in which
they are declared.
As in encapsulation, the data in a class is hidden from other classes, so it is also
known as data-hiding.
Encapsulation can be achieved by: Declaring all the variables in the class as private
and writing public methods in the class to set and get the values of variables.
Advantage of Encapsulation
The main advantage of using of encapsulation is to secure the data from other methods, when
we make a data private then these data only use within the class, but these data not accessible
outside the class.
The common example of encapsulation is capsule. In capsule all medicine are encapsulated in
side capsule.
Benefits of encapsulation
7. Message Passing
An object oriented program consists of a set of objects that communicates with each other.
The process of programming in an object oriented language, therefore, involves the
following basic steps.
1. Creating classes that define objects and their behavior.
2. Creating objects from class definitions.
3. Establishing communication among objects.
History of Java
The principles for creating Java programming were "Simple, Robust, Portable, Platform-
independent, Secured, High Performance, Multithreaded, Architecture Neutral, Object-Oriented,
Interpreted and Dynamic".
Currently, Java is used in internet programming, mobile devices, games, e-business solutions,
etc. There are given the significant points that describe the history of Java.
1) James Gosling, Mike Sheridan, and Patrick Naughton initiated the Java language project in
June 1991. The small team of sun engineers called Green Team.
2) Originally designed for small, embedded systems in electronic appliances like set-top boxes.
3) Firstly, it was called "Greentalk" by James Gosling, and file extension was .gt.
4) After that, it was called Oak and was developed as a part of the Green project.
5) In 1995, Oak was renamed as "Java" because it was already a trademark by Oak
Technologies.
Many java versions have been released till now. The current stable release of Java is Java SE 10.
Features of Java
Features of a language are nothing but the set of services or facilities provided by the
language vendors to the industry programmers. Some important features of java are;
1. Simple
A program or technology is said to be platform independent if and only if which can run on
all available operating systems with respect to its development and compilation. (Platform
represents O.S).
3. Portable
If any language supports platform independent and architectural neutral feature known as
portable. The languages like C, CPP, Pascal are treated as non-portable language. It is a
portable language.
According to SUN microsystem.
4. Robust
Simply means of Robust are strong. It is robust or strong Programming Language because of
its capability to handle Run-time Error, automatic garbage collection, the lack of pointer
concept, Exception Handling. All these points make It robust Language.
5. Secure
It is a more secure language compared to other language; In this language, all code is
covered in byte code after compilation which is not readable by human
6. High performance
This language uses Bytecode which is faster than ordinary pointer code so Performance
of this language is high.
Garbage collector, collect the unused memory space and improve the performance of
the application.
It has no pointers so that using this language we can develop an application very easily.
It support multithreading, because of this time consuming process can be reduced to
executing the program.
7. Dynamic
It supports Dynamic memory allocation due to this memory wastage is reduce and improve
performance of the application. The process of allocating the memory space to the input of
the program at a run-time is known as dynamic memory allocation, To programming to
allocate memory space by dynamically we use an operator called 'new' 'new' operator is
known as dynamic memory allocation operator.
8. Interpreted
9. Object Oriented
The Java Development Kit (JDK) is a software development environment used for
developing Java applications and applets. It includes the Java Runtime Environment (JRE), an
interpreter/loader (Java), a compiler (javac), an archiver (jar), a documentation generator
(Javadoc) and other tools needed in Java development.
OR
The JDK is a software package that contains a variety of tools and utilities that make it
possible to develop, package, monitor and deploy applications that build for any standard Java
platform, including Java Platform, Standard Edition (Java SE); Java Platform, Micro Edition
(Java ME); and Java Platform, Enterprise Edition (Java EE)
The bin directory of the JDK provides a variety of features and tools that aid in the software
development process. Some of the more popular JDK utilities include:
javac: This utility is used to compile Java source code into Java bytecode.
jar: This compression utility aggregates a multitude of files into a single Java ARchive
(JAR) file. The jar utility uses a standard compression algorithm used by all of the most
common zip utilities.
javadoc: This utility can examine the names of classes and the methods contained within a
class, as well as consume special annotations in order to create application programming
interface (API) documentation for Java code.
javap: This utility disassembles class files, generating information about the methods,
properties and attributes of a given compiled component and etc.
JVM (Java Virtual Machine) is an abstract machine. It is a specification that provides runtime
environment in which java bytecode can be executed.
JVMs are available for many hardware and software platforms (i.e. JVM is platform dependent).
It is:
o Loads code
o Verifies code
o Executes code
o Provides runtime environment
o Memory area
o Class file format
o Register set
o Garbage-collected heap
o Fatal error reporting etc.
The Java Runtime Environment is a set of software tools which are used for developing Java
applications. It is used to provide the runtime environment. It is the implementation of JVM. It
physically exists. It contains a set of libraries + other files that JVM uses at runtime.
The implementation of JVM is also actively released by other companies besides Sun Micro
Systems.
Java Environment:
Java Identifiers
For example :
The only allowed characters for identifiers are all alphanumeric characters([A-Z],[a-z],[0-
9]), ‘$‘(dollar sign) and ‘_‘ (underscore).For example “java@” is not a valid java identifier
as it contain ‘@’ special character.
Identifiers should not start with digits([0-9]). For example “123java” is a not a valid java
identifier.
Java identifiers are case-sensitive.
There is no limit on the length of the identifier but it is advisable to use an optimum length
of 4 – 15 letters only.
Reserved Words can’t be used as an identifier. For example “int while = 20;” is an invalid
statement as while is a reserved word. There are 53 reserved words in Java.
1. MyVariable 7. i1
2. MYVARIABLE 8. _myvariable
3. myvariable 9. $myvariable
4. x 10. sum_of_array
5. i 11. geeks123
6. x1
Reserved Words
Any programming language reserves some words to represent functionalities defined by
that language. These words are called reserved words.
They can be briefly categorized into two parts : keywords(50) and literals(3).
Java keywords
java keywords are also known as reserved words. Keywords are particular words which act as a
key to a code. These are predefined words by Java so it cannot be used as a variable or object
name.
All keywords are written in lower-case letter. And we cannot use them as names for variables,
classes, and methods and so on..
publicclassJavaKeyword
{
publicstaticvoidmain(String[] args)
{
double d1 = 23.56; // Here double is a keyword
double d2 = 56.23;
System.out.println(d1);
}
}
Primitive data types – these data types are the data types which is predefined by java is known as
primitive data types.
It includes 8 primitive data types are: byte, short, int, long, float, double, boolean and char
Non-primitive data types are the data types which is defined by the programmers
- such as String, Arrays and Classes
Data
Type Size Description
double 8 bytes Stores fractional numbers. Sufficient for storing 15 decimal digits
Numbers
Primitive number types are divided into two groups:
Integer types store whole numbers, positive or negative (such as 123 or -456), without decimals.
Valid types are byte, short, int and long. Which type you should use, depends on the numeric value.
Floating point types represents numbers with a fractional part, containing one or more decimals.
There are two types: float and double.
Even though there are many numeric types in Java, the most used for numbers are int (for whole
numbers) and double (for floating point numbers). However, we will describe them all as you
continue to read.
Integer Types
Byte :
The byte data type can store whole numbers from -128 to 127. This can be used instead of int or
other integer types to save memory when you are certain that the value will be within -128 and 127:
Ex: byte a=100;
Short :
The short data type can store whole numbers from -32768 to 32767:
Ex: short myNum = 5000;
Int :
The int data type can store whole numbers from -2147483648 to 2147483647. In general, and in our
tutorial, the int data type is the preferred data type when we create variables with a numeric value.
Long :
The long data type can store whole numbers from -9223372036854775808 to
9223372036854775807. This is used when int is not large enough to store the value. Note that you
should end the value with an "L":
Ex: long myNum = 15000000000L;
Float :
The float data type can store fractional numbers from 3.4e−038 to 3.4e+038. Note that you should
end the value with an "f":
Ex: float myNum = 5.75f;
Double :
The double data type can store fractional numbers from 1.7e−308 to 1.7e+308. Note that you should
end the value with a "d":
Ex: ouble myNum = 19.99d;
Scientific Numbers
A floating point number can also be a scientific number with an "e" to indicate the power of 10:
public class MyClass {
public static void main(String[] args) {
float f1 = 35e3f;
double d1 = 12E4d;
System.out.println(f1);
System.out.println(d1);
}
}
O/P:
35000.0
120000.0
Booleans :
A boolean data type is declared with the boolean keyword and can only take the values true or false:
O/P:
------------
True
false
Characters :
The char data type is used to store a single character. The character must be surrounded by single
quotes, like 'A' or 'c':
public class MyClass
{
public static void main(String[] args)
{
char myGrade = 'B';
System.out.println(myGrade);
}
}
Strings :
The String data type is used to store a sequence of characters (text). String values must be
surrounded by double quotes:
The String type is so much used and integrated in Java, that some call it "the special ninth type".
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.
//Write a java program to display the size of primitive data types that is in
bytes.
import java.io.*;
public class PrimitiveDatatypes
{
public static void main(String[] args)
{
System.out.println("Byte= "+(Byte.SIZE/8));
System.out.println("Short="+(Short.SIZE/8));
System.out.println("Integer="+(Integer.SIZE/8));
System.out.println("Long="+(Long.SIZE/8));
System.out.println("Float="+(Float.SIZE/8));
System.out.println("Character="+(Character.SIZE/8));
System.out.println("Double="+(Double.SIZE/8));
}
}
---------------------Output-------------------
C:\Users\staff1\Desktop\JAVA PROGRAMS\Journal_Programs>javac PrimitiveDatatypes.java
C:\Users\staff1\Desktop\JAVA PROGRAMS\Journal_Programs>java PrimitiveDatatypes
Byt e= 1
Short = 2
Integer = 4
Long = 8
Float = 4
Character = 2
Double = 8
Widening Casting
Widening casting is done automatically when passing a smaller size type to a larger size type:
Example
public class MyClass
{
public static void main(String[] args)
{
int myInt = 9;
double myDouble = myInt; // Automatic casting: int to double
System.out.println(myInt); // Outputs 9
System.out.println(myDouble); // Outputs 9.0
}
}
OUTPUT
9
9.0
Narrowing Casting
Narrowing casting must be done manually by placing the type in parentheses in front of the value:
Syntax:
dataType <variableName> = (dataType) <variableToConvert>;
Example
public class MyClass
{
public static void main(String[] args)
{
double myDouble = 9.78f;
int myInt = (int) myDouble; // Manual casting: double to int
System.out.println(myDouble); // Outputs 9.78
System.out.println(myInt); // Outputs 9
}
}
OUTPUT
9.78
9
Java Variables
A variable is a container which holds the value while the java program is executed. A
variable is assigned with a data type.
A variable is a name given to a memory location. It is the basic unit of storage in a
program. The value stored in a variable can be changed during program execution.
A variable is only a name given to a memory location, all the operations done on the variable
effects that memory location.
In Java, all the variables must be declared before use.
Examples:
float simpleInterest; //Declaring float variable
int time = 10, speed = 20; //Declaring and Initializing integer variable
char var = 'h'; // Declaring and Initializing character variable
Variable is a name of memory location. There are three types of variables in java:
1) Local variable
2) Instance variable
3) Static variable
Variable
Variable is name of reserved area allocated in memory. In other words, it is a name of memory
location. It is a combination of "vary + able" that means its value can be changed.
Types of Variables
There are three types of variables in java:
o local variable
o instance variable
o static variable
1) Local Variable
A variable declared inside the body of the method is called local variable. You can use
this variable only within that method and the other methods in the class aren't even aware that
the variable exists.
A local variable cannot be defined with "static" keyword.
The scope of these variables exists only within the block in which the variable is declared.
i.e. we can access these variable only within that block.
Initilisation of Local Variable is Mandatory.
Example:
public class StudentDetails
{
public void StudentAge()
{
// local variable age
int age = 0;
age = age + 5;
System.out.println("Student age is : " + age);
}
public static void main(String args[])
{
StudentDetails obj = new StudentDetails();
obj.StudentAge();
}
}
Output:
Student age is : 5
In the above program, the variable age is a local variable to the function StudentAge(). If we
use the variable age outside StudentAge() function, the compiler will produce an error as
shown in below program.
public class StudentDetails {
public void StudentAge()
{ // local variable age
int age = 0;
age = age + 5;
}
Output:
Compilation Error in java code:-
prog.java:12: error: cannot find symbol
System.out.println("Student age is : " + age);
^
symbol: variable age
location: class StudentDetails
1 error
2) Instance Variable
A variable declared inside the class but outside the body of the method, constructors or
any blocks is called instance variable. It is not declared as static.
It is called instance variable because its value is instance specific and is not shared among
instances.
As instance variables are declared in a class, these variables are created when an object of
the class is created and destroyed when the object is destroyed.
Initialization of Instance Variable is not Mandatory. Its default value is 0
Instance Variable can be accessed only by creating objects.
import java.io.*;
class InstanceVariable
{
int c; //instance variable
public void add()
{
int a=10;
int b=10;
c=a+b; // using instance variable here that is c
System.out.println(c);
}
}
class variables
{
public static void main(String args[])
{
InstanceVariable instance=new InstanceVariable();
instance.add();
}
}
Output:
20
Here in above program int c; is a instance variable and it is declared within a class of
InstanceVariable. And this variable again we are used in add() method that is c=a+b; but only
we can access this instance variable by creating object for this add() method ie
instance.add();
3) Static variable
A variable which is declared as static is called static variable. It cannot be local. You can
create a single copy of static variable and share among all the instances of the class. Memory
allocation for static variable happens only once when the class is loaded in the memory.
Static variables are created at the start of program execution and destroyed automatically
when execution ends.
Initilisation of Static Variable is not Mandatory. Its default value is 0
If we access the static variable like Instance variable (through an object), the compiler will
show the warning message and it won’t halt the program. The compiler will replace the
object name to class name automatically.
If we access the static variable without the class name, Compiler will automatically append
the class name.
To access static variables, we need not create an object of that class, we can simply access the
variable as
class_name.variable_name;
Sample Program:
import java.io.*;
class Emp
{
// static variable salary
public static double salary;
public static String name = "Harsh";
}
class A
{
int data=50;//instance variable
static int m=100;//static variable
void method()
{
int n=90;//local variable
}
}//end of class
In above program consist three types of variable , here int data=50; is a instance variable
because it is declared in class and static int m=100; is a static variable because it is declared as
a static by using static keyword and also outside the method and inside the class and int n=90;
Is a local variable it is declared in within method().
In programming, it's often desirable to execute a certain section of code based upon whether the
specified condition is true or false (which is known only during the run time). For such cases,
control flow statements are used.
The Java if statement is used to test the condition. It checks boolean
condition: true or false. There are various types of if statement in java.
o if statement
o if-else statement
o if-else-if ladder
o nested if statement
The Java if statement tests the condition. It executes the if block if condition is true.
The syntax of if-then statement in Java is:
if (expression)
{
// statements
}
Number is positive.
This statement is always executed.
When number is 10, the test expression number > 0 is evaluated to true. Hence, codes inside the
body of if statements are executed.
Now, change the value of number to a negative integer. Let's say -5. The output in this case will
be:
When number is -5, the test expression number > 0 is evaluated to false. Hence, Java compiler skips
the execution of body of if statement.
The Java if-else statement also tests the condition. It executes the if block if condition is
true otherwise else block is executed.
if (expression)
{
// codes
}
Else
{
// some other code
// Else code will executes.
}
Number is positive.
This statement is always executed.
When number is 10, the test expression number > 0 is evaluated to true. In this case, codes inside
the body of if are executed, and codes inside the body of else statements are skipped from
execution.
Now, change the value of number to a negative number. Let's say -5. The output in this case will
be:
When number is -5, the test expression number > 0 is evaluated to false. In this case, codes inside
the body of else are executed, and codes inside the body of if statements are skipped from
execution.
if (expression1)
{
// codes
}
else if(expression2)
{
// codes
}
else if (expression3)
{
// codes
}
.
.
else
{
// codes
}
The if statements are executed from the top towards the bottom. As soon as the test expression
is true, codes inside the body of that if statement is executed. Then, the control of program jumps
outside if-else-if ladder.
If all test expressions are false, codes inside the body of else is executed.
Number is 0.
When number is 0, both test expression number > 0 and number < 0 is evaluated to false. Hence, the
statement inside the body of else is executed.
The above program checks whether number is positive, negative or 0.
The nested if statement represents the if block within another if block. Here, the inner if
block condition executes only when outer if block condition is true.
It's possible to have if..else statements inside a if..else statement in Java. It's called
nested if...else statement.
Here's a program to find largest of 3 numbers:
Sysntax:
if(condition)
{
//code to be executed
if(condition)
{
//code to be executed
}
}
Note: In above programs, we have assigned value of variables ourselves to make this easier.
However, in real world applications, these values may come from user input data, log files, form
submission etc.
You should also check ternary operator in Java, which is kind of shorthand notation
of if...else statement.
Syntax:
switch(expression)
{
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
}
This is how it works:
The switch expression is evaluated once.
The value of the expression is compared with the values of each case.
If there is a match, the associated block of code is executed.
The break and default keywords are optional,
The example below uses the weekday number to calculate the weekday name:
Example:
public class MyClass
{
public static void main(String[] args)
{
int day = 4;
switch (day)
{
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
case 3:
System.out.println("Wednesday");
break;
case 4:
System.out.println("Thursday");
break;
case 5:
System.out.println("Friday");
break;
case 6:
System.out.println("Saturday");
break;
case 7:
System.out.println("Sunday");
break;
}
}
}
int day = 4;
switch (day) {
case 6:
System.out.println("Today is Saturday");
break;
case 7:
System.out.println("Today is Sunday");
break;
default:
System.out.println("Looking forward to the Weekend");
}
Outputs :
"Looking forward to the Weekend"
Note that if the default statement is used as the last statement in a switch block, it does not need a
break.
Syntax
while(condition)
{
Statement(s)
Increment / decrements (++ or --);
}
class whileDemo
{
public static void main(String args[])
{
int i=0;
while(i<5)
{
System.out.println(+i);
i++;
}
Output
0
2
3
4
Syntax
Initialization: This step is execute first and this is execute only once when we are
entering into the loop first time. This step is allow to declare and initialize any loop
control variables.
Condition: This is next step after initialization step, if it is true, the body of the loop is
executed, if it is false then the body of the loop does not execute and flow of control goes
outside of the for loop.
Increment or Decrements: After completion of Initialization and Condition steps loop
body code is executed and then Increment or Decrements steps is execute. This statement
allows to update any loop control variables.
Flow Diagram
class Hello
{
public static void main(String args[])
{
int i;
for (i=0: i<5; i++)
{
System.out.println("Hello Friends !");
}
}
}
Output
Hello Friends !
Hello Friends !
Hello Friends !
Hello Friends !
Hello Friends !
A do while loop is a control flow statement that executes a block of code at least once, and then
repeatedly executes the block, or not, depending on a given condition at the end of the block (in
while).
do
{
Statement(s)
In below example you can see in this program i=20 and we check condition i is less than 10, that
means condition is false but do..while loop execute onec and print Hello world ! at one time.
class dowhileDemo
{
public static void main(String args[])
{
int i=20;
do
{
System.out.println("Hello world !");
i++;
}
while(i<10);
}
}
Output
Hello world !
class dowhileDemo
{
public static void main(String args[])
{
int i=0;
do
{
System.out.println(+i);
i++;
}
while(i<5);
}
}
Output
1
2
3
4
5
It is mainly used to traverse the array or collection elements. The advantage of the for-each
loop is that it eliminates the possibility of bugs and makes the code more readable. It is
known as the for-each loop because it traverses each element one by one.
The drawback of the enhanced for loop is that it cannot traverse the elements in reverse order.
Here, you do not have the option to skip any element because it does not work on an index
basis. Moreover, you cannot traverse the odd or even elements only.
But, it is recommended to use the Java for-each loop for traversing the elements of array and
collection because it makes the code readable.
Advantages
o It makes the code more readable.
o It eliminates the possibility of programming errors.
Syntax
The syntax of Java for-each loop consists of data_type with the variable followed by a colon (:),
then array or collection.
How it works?
The Java for-each loop traverses the array or collection until the last element. For each element, it
stores the element in the variable and executes the body of the for-each loop.
class ForEachExample1
{
public static void main(String args[])
{
//declaring an array
int arr[]= {12,13,14,44};
Output:
12
12
14
44
Let us see another of Java for-each loop where we are going to total the elements.
class ForEachExample1
{
public static void main(String args[])
{
int arr[]= {12,13,14,44};
int total=0;
for(int i:arr)
{
total=total+i;
}
System.out.println("Total: "+total);
}
}
Output:
Total: 83
Array in java
Array is a collection of similar type of data. It is fixed in size means that you can't
increase the size of array at run time. It is a collection of homogeneous data elements. It
stores the value on the basis of the index value.
Advantage of Array
1) One variable can store multiple value: The main advantage of the array is we can
represent multiple value under the same name.
2) Code Optimization: No, need to declare a lot of variable of same type data, We can
retrieve and sort data easily.
3) Random access: We can retrieve any data from array with the help of the index
value.
Disadvantage of Array
The main limitation of the array is Size Limit when once we declare array there is
no chance to increase and decrease the size of an array according to our requirement,
Hence memory point of view array concept is not recommended to use. To overcome
this limitation in Java introduces the collection concept.
Types of Array
There are two types of array in Java.
Single Dimensional Array
Multidimensional Array
Array Declaration
Single dimension arrays declarations.
Syntax
1. int[] a;
2. int a[];
3. int []a;
Note: At the time of array declaration we cannot specify the size of the array. For
Example int[5] a; this is wrong.
2D Array declaration.
Def: Multidimensional Arrays can be defined in simple words as array of arrays. Data in
multidimensional arrays are stored in tabular form (in row major order).
Syntax
1. int[][] a;
2. int a[][];
3. int [][]a;
4. int[] a[];
5. int[] []a;
6. int []a[];
2D Array creation
Every array in a Java is an object, Hence we can create array by using new keyword.
Syntax
arrayname[n-1];
int[] arr={10,20,30,40};
System.out.println("Element at 4th place"+arr[2]);
Example of Array
Output
10
20
39
Note:
1) At the time of array creation we must be specify the size of array otherwise get an
compile time error. For Example
int[] a=new int[]; Invalid.
int[] a=new int[5]; Valid
2) If we specify the array size as negative int value, then we will get run-time error,
NegativeArraySizeException.
3) To specify the array size the allowed data types are byte, short, int, char If we use
other data type then we will get an Compile time error.
4) The maximum allowed size of array in Java is 2147483647 (It is the maximum value
of int data type)
length: It is a final variable and only applicable for array. It represent size of array.
Example
length(): It is the final method applicable only for String objects. It represents the
number of characters present in the String.
Example
String s="Java";
System.out.println(s.length()); // 4
System.out.println(s.length); // Compile time error
Jagged Array:
Jagged array is a multidimensional array where member arrays are of different size.
We can create a 2-D arrays but with variable number of columns in each row. These
type of arrays are also known as Jagged arrays.
Example :
class JaggedArray
{
// Program to illustrate Jagged array in Java
public static void main(String[] args)
{
// Declare a jagged array containing three elements
int[][] arr = new int[3][];
class CommandLineExample
{
public static void main(String args[])
{
System.out.println("Argument is: "+args[0]);
}
}
Output
class Demo1
{
public static void main(String args[])
{
System.out.println("First argument is: "+args[0]);
System.out.println("Second argument is: "+args[1]);
}
}
Output
When the above statement is executing the following sequence of steps will take place.
Class loader sub-system loads Demo1 along with Command line argument(10, 20) and in
main memory.
JVM takes the loaded class Demo1 along with Command line arguments (10, 20) and
place the number of values in the length variable that is 2.
JVM looks for main() that is JVM will place the Command in the main() in the form of
string class that is.
10
main(String args[length]) args
20
Hence all the CMD line arguments of Java are sending to main() method available in the
form of an array of object of String class (every CMD are available or stored in main
method in the form of an array of object of String class).
JVM calls the main() method with respect to load class Demo1 that is Demo1.main().
class CMD
{
public static void main(String args[])
{
System.out.println("no. of arguments ="+ args.length);
for(int i=0;i< args.length;i++)
{
System.out.println(args.[i]);
}
}
}
Note: Except + operator any numeric operation not allowed in command line arguments.
import java.io.*;
public class Factorial
{
public static void main(String args[])
{
int fact=1,n;
if(args.length==1)
{
n=Integer.parseInt(args[0]); //convert entered argument into integer
for(int i=1;i<n;i++)
{
fact=fact*i;
}
System.out.println("Factorial of a given number is: "+fact);
}
else if(args.length>1)
{
System.out.println("More than one argument entered");
}
else
{
System.out.println("No command line arguments are passed");
}
}
}
OUTPUT:
C:\Users\staff1>set path="C:\Program Files\Java\jdk1.7.0\bin"
C:\Users\staff1>cd C:\Users\staff1\Desktop\JAVA PROGRAMS\Journal_Programs
C:\Users\staff1\Desktop\JAVA PROGRAMS\Journal_Programs>javac Factorial.java
RUN 1:
C:\Users\staff1\Desktop\JAVA PROGRAMS\Journal_Programs>java Factorial
RUN 2:
RUN 3:
C:\Users\staff1\Desktop\JAVA PROGRAMS\Journal_Programs>java Factorial 8 9
More than one argument entered