You are on page 1of 37

Java Programming Language

Introduction:
class-based, object-oriented programming language that is
Java is a high-level, class
designed to have as few implementation dependencies as possible. It is a general
general-
purpose programming language intended to let programmers write once, run
anywhere (WORA), meaning that compiled Java code can run on all platforms that support
Java without the need to recompile. Java applications are typically compiled to bytecode that
can run on any Java virtual machine (JVM) regardless of the underlying computer
architecture. The syntax of Java is similar to C and C++, but has fewer low-level
level facilities
than either of them. The Java runtime provides dynamic capabilities (such as reflection and
runtime code modification) that are typically not available in traditional compiled languages.
Java was originally developed by James Gosling at Sun Microsystems.. It was
released in May 1995 as a core component of Sun Microsystems' Java platform.
platform The original
and reference implementation Java compilers, virtual machines, and class libraries were
originally released by Sun under proprietary licenses.. As of May 2007, in compliance with
the specifications of the Java Community Process
Process, Sun had relicensed most of its Java
technologies under the GPL-2.0--only license. Oracle offers its own HotSpot Java Virtual
Machine, however the official reference implementation is the OpenJDK JVM which is free
open-source
source software and used by most developers and is the default JVM for almost all
Linux distributions.

Features of Java Programming Language:


Language

 Object Oriented: In Java, everything is an Object. Java can be easily extended


extended
since it is based on the Object model.
 Platform Independent: Unlike many other programming languages including C and
C++, when Java is compiled,
compiled, it is not compiled into platform specific machine, rather
into platform independent byte code. This byte code is distributed over the web and
interpreted by the Virtual Machine (JVM) on whichever platform it is being run on.
 Simple: Java is designed tto
o be easy to learn. If you understand the basic concept of
OOP Java, it would be easy to master.
 Secure: With Java's secure feature it enables to develop virus-free,
virus free, tamper-free
tamper
systems. Authentication techniques are based on public
public-key encryption.
 High Performance: With the use of Just-In-Time
Just Time compilers, Java enables high
performance.

Page 1 of 37
 Interpreted: Java byte code is translated on the fly to native machine instructions
and is not stored anywhere. The development process is more rapid and analytical
since the linking is an incremental and light-weight
light process.

HOW JAVA PROGRAM WORKS IN MACHINE?


1. Here for the first step, we need to have a java source code otherwise we won't be
able to run the program you need to save it with the program.java extension.
2. Secondly, we need to use a compiler so that it compiles the source code which in turn
gives out the java bytecode and that needs to have a program.class extension. The
Java bytecode is a redesigned version of the java source codes, and this bytecode
can be run anywherehere irrespective of the machine on which it has been built.
3. Later on, we put the java bytecode through the Java Virtual Machine which is an
interpreter that reads all the statements thoroughly step by step from the java
bytecode which will further convert it to the machine-level language so that the
machine can execute the code. We get the output only after the conversion is through.

Java- Basic Syntax


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

 Object - Objects have states and behaviors. Example: A dog has states - color,
name, breed as well as behavior such as wagging their tail, barking, eating. An object
is an instance of a class.
 Class - A class can be defined as a template/blueprint that describes the
behavior/state that the object of its type supports.

Page 2 of 37
 Methods - A method is basically a behavior. A class can contain many methods.
method It is
in methods where the logics are written, data is manipulated and all the actions are
executed.
 Instance Variables - Each object has its unique set of instance variables. An
object's state is created by the values assigned to these instance variables.
variabl

Let us look at a simple code that will print the words Hello World.
public class MyFirstJavaProgram {
public static void main(String[ ] args){
System.out.println("hello world!");
world
}
}

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

1. Open notepad and add the code as above.


2. Save the file as: MyFirstJavaProgram.java
MyFirstJavaProgram.java.
3. Open a command prompt window and go to the directory where you saved the class.
Assume it's C:\user1\desktop
desktop\folder>
4. Type 'javac MyFirstJavaProgram.java' and press enter to compile your code. If
there are no errors in your code, the command prompt will take you to the next line
(Assumption : The path variable is set).
5. Now, type ' java MyFirstJavaProgram ' to run your program.
6. You will be able to see ' Hello World ' printed on the window.

C:\user1\desktop\folder>
> javac MyFirstJavaProgram.java

C:\user1\desktop\folder>
> java MyFirstJavaProgram

Hello World

Basic Syntax Rules


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

 Case Sensitivity - Java is case sensitive, which means identifier Helloand hello
would have different meaning in Java.
 Class Names - For all class names the first letter should be in Upper Case. If
several words are used to form a name of the class, each inner word's first letter
should be in Upper Case.
Example: class MyFirstJavaClass
 Method Names - All method names should start with a Lower Case letter. If
several words are used to form the name of the method, then each inner word's
first letter should be in Upper Case.
Example: public void myMethodName()
 Program File Name - Name of the program file ile should exactly match the class
name.

Page 3 of 37
When saving the file, you should save it using the class name (Remember Java
is case sensitive) and append '.java' to the end of the name (if the file name and
the class name do not match, your program will not compile).
com
Example: Assume 'MyFirstJavaProgram' is the class name. Then the file should
be saved as 'MyFirstJavaProgram.java'
 publicc static void main(String[] args
args) - Java program processing starts fromthe
from
main() method which is a mandatory part of every Ja Java program.

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

Class name, main method, String (Predefined Class name),


name) args (String variables),
variables) System
(Predefined class), out (Variable
e name)
name), println (method) etc. are example of identifier in java
programming language.

In Java, there are several points to remember about identifiers declaration and used of them
in your program.

They are as follows:

 All identifiers should begin with a lletter


etter (A to Z or a to z), currency character ($) or
an underscore (_).
 After the first character, identifiers can have any combination of characters.
 A key word cannot be used as an identifier.
 Most importantly, identifiers are case sensitive.
 Examples
ples of legal identifiers: age, $salary, _value, __1_value.
 Examples of illegal identifiers: 123abc, -salary.

Variables
Every program works with values. A variable lets you store a value by assigning it to
a name. The name can be used to refer to the valu
value later in the program.

For example, in game development, you would use a variable to store how many points the
player has scored.

Page 4 of 37
Example:

In programming terms, the process of creating a variable is called declaration.

 A variable has a name and a type of the value it holds. A variable can hold a text
value, a number, a decimal, etc
 To declare a variable use the type followed by the name of the variable.
 You can assign a value to the declared variable using the = operator.
 A variable can change its valu
value
e during the program, by being assigned to a new
value.

Difference between Identifier and Variable

The following table highlights all the important differences between identifier and variable −

S.No. Identifier Variable

It is used to name a variable, a function, It is used to give a name to a memory


1. a class, a structure, a union. location that holds a value.

Identifiers are created assign a name to Variable is created to assign a unique name
2. an entity. to a specific memory location.

All identifiers
ers are not variables. All the variables names are identifiers.
3.

Identifier can take more number of Variable takes less number of characters.
4.
characters.

Page 5 of 37
DATA TYPES IN JAVA
Data types in Java specify how memory stores the values of the variable
variable.. Each variable has
a data type that decides the value the variable will hold. Moreover, Primitive Data Types are
also used with functions to define their return type.

PRIMITIVE DATA TYPES


Primitive data types specify the size and type of variable values.
values. They are the building blocks
of data manipulation and cannot be further divided into simpler data types.

Boolean
Another important type is boolean
boolean. It can hold only the values true or false.
Syntax:
Boolean is_open=false;

Char
The char type is used to hold a single character. it uses
uses single quotes for the value.
value It
takes memory space of 16 bits or 2 bytes. The values stored range between 0 to 65536.
Syntax:
char letter=’b’;

Byte
The byte is the smallest data type among all the integer data types. It is an 8-bit
bit signed two’s
complement integer. It stores whole numbers ranging from -128 to 127.
Syntax:
byte byteVariable;

Short
Short is a 16-bit
bit signed two’s complement integer. It stores whole numbers with values
ranging from -32768
32768 to 32767. Its default
defau value is 0.
Syntax: short shortVariable;

Page 6 of 37
Int
The int type is used to store whole numbers (or integers,, as we call them in programming).
Int is a 32-bit
bit signed two’s complement integer that stor
stores
es integral values ranging from
-2147483648 (-2^31) to 2147483647
483647 (2^31
(2^31-1). Its default value is 0.
Syntax:
int age=42;

long
long is a 64-bit
bit signed two’s complement integer that stores values ranging from -
9223372036854775808(-2^63)2^63) to 9223372036854775807(2^63 -1). 1). It is used when we need
a range of values more than those provided by int. Its default value is 0L. This data type
ends with ‘L’ or ‘l’.
Syntax:
long longVariable;

Float
It is a floating-point
point data type that stores the values, including their decimal precision. It is
not used for precise data such ass currency or research data.
A Float value:
 is a single-precision
precision 32-bit or 4 bytes IEEE 754 floating-point
 can have a 7-digit
digit decimal precision
 ends with an ‘f’ or ‘F’
 default value = 0.0f
 stores fractional numbers ranging from 3.4e
3.4e-038 to 3.4e+038
Syntax:
float height=1.94f;

Double
The double data type is similar to float. The difference between the two is that is double
twice the float in the case of decimal precision. It is used for decimal values just like float and
should not be used for precise val
values.
A double value:
 is a double-precision
precision 64-bit or 8 bytes IEEE 754 floating-point
 can have a 15-digit
digit decimal precision
 default value = 0.0d
 stores fractional numbers ranging from 1.7e
1.7e-308 to 1.7e+308
Syntax: double weight=12.5;

Float vs double
By default,
efault, decimal values are of type double.
float is using less storage in the memory, but is not as precise as the double type.
This means that the calculations that use floats are faster than the ones that use
double, however, the result is less accurate in terms of the decimal digits.

As a general rule: use float instead of double when memory usage is critical. If you
need more precise computations, for example, when dealing with currency,
use double.

Page 7 of 37
Primitive Data Types Table – Default Value, Size, and Range

Data Type Default Value Default size Range

byte 0 1 byte or 8 bits -128 to 127

short 0 2 bytes or 16 bits -32,768 to 32,767

int 0 4 bytes or 32 bits -2,147,483,648


2,147,483,648 to 2,147,483,647

-9,223,372,036,854,775,808
9,223,372,036,854,775,808 to
long 0 8 bytes or 64 bits
9,223,372,036,854,775,807
72,036,854,775,807

float 0.0f 4 bytes or 32 bits 1.4e-045 to 3.4e+038

double 0.0d 8 bytes or 64 bits 4.9e-324 to 1.8e+308

char ‘\u0000’ 2 bytes or 16 bits 0 to 65536

boolean FALSE 1 byte or 2 bytes 0 or 1

NON-PRIMITIVE
PRIMITIVE DATA TYPES
Non-primitive data types
ypes or reference data types refer to instances or objects. They cannot
store the value of a variable directly in memory. They store a memory address of the
variable. Unlike primitive data types we define by Java, non-primitive
non primitive data types are user-
user
defined. Programmers create them and can be assigned with null. All non non-primitive
primitive data
types are of equal size.

Array
Arrays are objects that store multiple variables of the same type. However, an array itself is
an object on the heap.

Arrays are used to store multiple


tiple values in a single variable, instead of declaring separate
variables for each value.

An array holds elements of the same type. It is an object in Java, and the array name (used
for declaration) is a reference value that carries the base address of the
the continuous location
of elements of an array.

Syntax: dataType[ ] arrayName;


Example: int[] nos={40,55,63,17,22,68,89,97,89}; dataType - it can be primitive data
types like int, char, double, byte, etc.
System.out.println(nos[1]); // output: 55
arrayName - it is an identifier

Page 8 of 37
Here,

Some steps for using array in java:

1) To declare an array, define tthe variable type with square brackets:

Example: String[ ] cars;


2) We have now declared a variable that holds an array of strings. To insert values to it,
you can place the values in a comma-separated
comma separated list, inside curly braces:
Example:
String[ ] cars = {"V
{"Volvo", "BMW", "Ford", "Mazda"};
3) To create an array of integers, you could write:
Example:
int[ ] myNum = {10, 20, 30, 40};

4) Access the Elements of an Array


Array. You can access an array element by referring to
the index number.
This statement accesses the value of the first element in cars:
Example:
String[ ] cars = {"Volvo", "BMW", "Ford", "Mazda"};
System.out.println(cars[0]);
// Outputs Volvo

String

The String data type stores a sequence or array of characters. A string is a nonnon--primitive
data type, but it is predefined in Java. String literals are enclosed in double quotes.
Example: String S1 = "Java String Data type";

Class
A class is a user-defined
defined data type from which objects are created. It describes the set of
properties or methods common to all objects of the same type. It contains fields and
methods that represent the behaviour of an object. A class gets invoked by the creation of
the respective object.

Page 9 of 37
There are two types of classes: a blueprint and a template. For instance, the
architectural diagram off a building is a class, and the building itself is an object created using
the architectural diagram.

Difference between object and class


There are many differences between object and class. A list of differences between object
and class are given below:

No. Object Class

1) Object is an instance of a class. Class is a blueprint or template from


which objects are created.

2) Object is a real world entity such as pen, Class is a group of similar objects.
objects
laptop, mobile, bed, keyboard, mouse, chair etc.

3) Object is a physical entity. Class is a logical entity.

4) Object is created through new keyword mainly Class is declared using class
e.g. keyword e.g.
Student s1=new Student(); class Student{}

5) Object is created many times as per Class is declared once.


once
requirement.

6) Object allocates memory when it is created


created. Class doesn't allocated memory when
it is created.

7) There are many ways to create object in java There is only one way to define class in
such as new keyword, newInstance() method, java using class keyword.
clone() method, factory method and
deserialization.

Let's see some real life example of class and object in java to understand the difference well:

Class: Human Object: Man, Woman

Class: Fruit Object: Apple, Banana, Mango, Guava wtc.

Page 10 of 37
Java Reserved Keywords

Java has a set of keywords that are reserved words that cannot be used as variables,
methods, classes, or any other identifiers:

Keyword Description

abstract A non-access
access modifier. Used for classes and methods: An abstract cla class
cannot be used to create objects (to access it, it must be inherited from
another class). An abstract method can only be used in an abstract class,
and it does not have a body. The body is provided by the subclass (inherited
from)

assert For debugging

boolean A data type that can only store true and false values

break Breaks out of a loop or a switch block

byte A data type that can store whole numbers from -128
128 and 127

case Marks a block of code in switch statements

catch Catches exceptions generated


generat by try statements

char A data type that is used to store a single character

class Defines a class

continue Continues to the next iteration of a loop

const Defines a constant. Not in use - use final instead

Page 11 of 37
default Specifies the default block of code
cod in a switch statement

do Used together with while to create a do


do-while loop

double 1.7e−308 to 1.7e+308


A data type that can store whole numbers from 1.7e−308

else Used in conditional statements

enum Declares an enumerated (unchangeable) type

exports Exports a package with a module. New in Java 9

extends Extends a class (indicates that a class is inherited from another class)

final A non-access
access modifier used for classes, attributes and methods, which
makes them non
non-changeable (impossible to inherit or override)
ide)

finally Used with exceptions, a block of code that will be executed no matter if
there is an exception or not

float A data type that can store whole numbers from 3.4e−038
−038 to 3.4e+038

for Create a for loop

if Makes a conditional statement

implements Implements an interface

import Used to import a package, class or interface

Page 12 of 37
instanceof Checks whether an object is an instance of a specific class or an
a interface

int A data type that can store whole numbers from -2147483648
2147483648 to
2147483647

interface Used to declare a special type of class that only contains abstract methods

long A data type that can store whole numbers from -9223372036854775808
9223372036854775808 to
9223372036854775808
372036854775808

module Declares a module. New in Java 9

native Specifies that a method is not implemented in the same Java source file
(but in another language)

new Creates new objects

package Declares a package

private An access modifier used for att


attributes,
ributes, methods and constructors, making
them only accessible within the declared class

protected An access modifier used for attributes, methods and constructors, making
them accessible in the same package and subclasses

public An access modifier used for classes, attributes, methods and constructors,
making them accessible by any other class

requires Specifies required libraries inside a module. New in Java 9

return Finished the execution of a method, and can be used to return a value from
a method

Page 13 of 37
short A data type that can store whole numbers from -32768
32768 to 32767

static A non-access
access modifier used for methods and attributes. Static
methods/attributes can be accessed without creating an object of a class

strictfp Restrict the precision and rounding of floating point calculations

super Refers to superclass (parent) objects

switch Selects one of many code blocks to be executed

synchronized A non-access
access modifier, which specifies that methods can only be accessed
by one thread at a time

this Refers to the current object in a method or constructor

throw Creates a custom error

throws Indicates what exceptions may be thrown by a method

transient A non-accesss
accesss modifier, which specifies that an attribute is not part of an
object's persistent state

try Creates a try...catch statement

var Declares a variable. New in Java 10

void Specifies that a method should not have a return value

Page 14 of 37
volatile Indicates that an attribute is not cached thread
thread-locally,
locally, and is always read
from the "main memory"

while Creates
tes a while loop

Note: true, false, and null are not keywords, but they are literals and reserved words that
cannot be used as identifiers.

BASIC OPERATORS IN JAVA


Java provides a rich set of operators to manipulate variables. We can divide all the Java
perators into the following groups −
operators

 Arithmetic Operators
 Relational Operators
 Bitwise Operators
 Logical Operators
 Assignment Operators
 Misc Operators

The Arithmetic Operators

Arithmetic operators are used in mathematical expressions in the same way that tthey are
used in algebra. The following table lists the arithmetic operators −

Assume integer variable A holds 10 and variable B holds 20, then −

Operator Description Example

+ (Addition) Adds values on either side of the operator. A + B will give 30

Subtracts right
right-hand operand from left-hand
- (Subtraction) A - B will give -10
operand.

* (Multiplication) Multiplies values on either side of the operator. A * B will give 200

Divides left
left-hand operand by right-hand
/ (Division) B / A will give 2
operand.

Divides left
left-hand operand by right-hand
% (Modulus) B % A will give 0
operand and returns remainder.

Page 15 of 37
++ (Increment) Increases the value of operand by 1. B++ gives 21

-- (Decrement) Decreases the value of operand by 1. B--


B gives 19

The Relational Operators


ors

There are following relational operators supported by Java language.

Assume variable A holds 10 and variable B holds 20, then −

Operator Description Example

Checks if the values of two operands


== (equal to) are equal or not, if yes then condition (A == B) is not true.
becomes true.

Checks if the values of two operands


!= (not equal to) are equal or not, if values are not (A != B) is true.
equal then condition becomes true.

Checks if the value of left operand is


greater than the value of right
> (greater than) (A > B) is not true.
operand, if yes then condition
becomes true.

Checks if the value of left operand is


< (less than) less than the value of right operand, if (A < B) is true.
yes then condition becomes true.

Checks if the value of left operand is


greater than or equal to the value of
>= (greater than or equal to) (A >= B) is not true.
right operand, if yes then condition
becomes true.

Checks if the value of left operand is


less than or equal to the value of right
<= (less than or equal to) (A <= B) is true.
operand, if yes then condition
becomes true.

The Bitwise Operators

Java defines several bitwise operators, which can be applied to the integer types, long, int,
short, char, and byte.

Page 16 of 37
Bitwise operator works on bits and performs bitbit-by-bitt operation. Assume if a = 60 and b =
13; now in binary format they will be as follows −
here,
a = 0011 1100 (60 binary code
code= 00111100)
(11000011)2
b = 0000 1101 (13
13 binary code=
code 00001101)
=128+64+0+0+0+0+2+1
a&b = 0000 1100 (00001100
00001100 is equal with=12)
=128+67
a|b = 0011 1101 (00111101
00111101 is equal with= 61)
=195
a^b = 0011 0001 (00110001 1 is equal with= 49)
But, in bit-level
level number storing capacity is
~a = 1100 0011 (11000011 is equal with= -61) between -128 to 127.

The following table lists the bitwise operators −

Assume integer variable A holds 60 and variable B holds 13 then −

Operator Description Example

Binary AND Operator copies a bit to the result (A & B) will give 12
& (bitwise and)
if it exists in both operands. which is 0000 1100

Binary OR Operator copies a bit if it exists in (A | B) will give 61


| (bitwise or)
either operand. which is 0011 1101

Binary XOR Operator copies the bit if it is set (A ^ B) will give 49


^ (bitwise XOR)
in one operand but not both. which is 0011 0001

(⁓AA) will give -61


which is 1100 0011 in
Binary Ones Complement Operator is unary
⁓ (bitwise compliment) 2's complement form
and has the effect of 'flipping' bits.
due to a signed
binary number.

Binary Left Shift Operator. The left operands


operand
A << 2 will give 240
<< (left shift) value is moved left by the number of bits
which is 1111 0000
specified by the right operand.

Binary Right Shift Operator. The left operands


A >> 2 will give 15
>> (right shift) value is moved right by the number of bits
which is 1111
specified by the right operand.

Page 17 of 37
Shift right zero fill operator. The left operands
>>> (zero fill right value is moved right by the number of bits A >>>2 will give 15
shift) specified by the right operand and shifted whic
which is 0000 1111
values are filled up with zeros.

The Logical Operators

The following table lists the logical operators −

Assume Boolean variables A holds true and variable B holds false, then −

Operator Description Example

Called Logical AND operator. If both the


&& (logical and) operandss are non-zero,
non then the condition (A && B) is false
becomes true.

Called Logical OR Operator. If any of the two


|| (logical or) operands are non
non-zero, then the condition (A || B) is true
becomes true.

Called Logical NOT Operator. Use to reverses


the logical state of its operand. If a condition is
! (logical not) !(A && B) is true
true then Logical NOT operator will make
false.

The Assignment Operators

Following are the assignment operators supported by Java language −

Operator Description Example

Simple assignment operator. Assigns values from right side C = A + B will assign
=
operands to left side operand. value of A + B into C

Add AND assignment operator. It adds right operand to the C += A is equivalent


+=
left operand and assign the result to left operand. to C = C + A

Page 18 of 37
Subtract AND assignment operator. It subtracts right
C -=
= A is equivalent
-= operand from the left operand and assign the result to left
oC=C−A
to
operand.

Multiply AND assignment operator. It multiplies right


C *= A is equivalent
*= operand with the left operand and assign the result to left
to C = C * A
operand.

Divide AND assignment operator. It divides left operand with C /= A is equivalent


/=
the right operand and assign the result to left operand. to C = C / A

Modulus AND assignment operator. It takes modulus using C %= A is equivalent


%=
two operands and assign the result to left operand. to C = C % A

C <<= 2 is same as
<<= Left shift AND assignment operator.
operat
C = C << 2

C >>= 2 is same as
>>= Right shift AND assignment operator.
C = C >> 2

C &= 2 is same as C
&= Bitwise AND assignment operator.
=C&2

C ^= 2 is same as C
^= bitwise exclusive OR and assignment operator.
=C^2

C |= 2 is same as C =
|= bitwise
wise inclusive OR and assignment operator.
C|2

Page 19 of 37
Miscellaneous Operators

There are few other operators supported by Java Language.

Conditional Operator ( ? : )

Conditional operator is also known as the ternary operator. This operator


erator consists of three
operands and is used to evaluate Boolean expressions. The goal of the operator is to
decide, which value should be assigned to the variable.

The operator is written as −

variable x = (expression) ? value if true : value if false

Example:
int a, b;
a = 10;
b = (a == 1) ? 20: 30;
System.out.println( "Value of b is : " + b );
//output = 30
b = (a == 10) ? 20: 30;
System.out.println( "Value of b is : " + b );
// output =20

Loop in java:
Looping in programming languages is a feature which facilitates the execution of a
set of instructions/functions repeatedly
repeatedly while some condition evaluates to true. Java provides
three ways for executing the loops. While all the ways provide similar basic functionality,
they differ in their syntax and condition checking time.

Page 20 of 37
Method:
A method in Java is a block of code that, when called, performs specific actions
mentioned in it. For instance, if you have written instructions to draw a circle in the method, it
will do that task. You can insert values or parameters into methods, and they will only be
executed when called. They are also referred to as functions. The primary uses of methods
in Java are:
 It allows code reusability (define once and use multiple times)
 You can break a complex program into smaller chunks of code
 It increases code readability
Methods in Java can be broadly
oadly classified into two types:
 Predefined [Example: main(), print(), and sqrt() etc. ]
 User-defined [Custom
Custom methods defined by the user are known as user
user--defined
methods.]

Page 21 of 37
Simple Programs for Java Programming Language.

1) A program for print your 1st message in java.


Code:
public class first {
public static void main(String[ ] args){

System.out.println("hello world!");
}
}

You must save this program with the name of first.java in your folder before compile your
java code. File name must be same with public class name.
Here, You can write code that generates outputs with the System.out.println() statement
println instruction
truction needs to be followed by parentheses.

2) A program for print multiple message.


Code:
public class my_second {
public static void main(String[ ] args) {

System.out.println("welcome, to java world!!");


System.out.println("let's start to play with code.");
}
}

3) A program
rogram to add two integers.
Code:
public class add {
public static void main(String[
main(Str ] args) {
int first = 10;
int second = 20;
// add two numbers
int sum = first + second;
System.out.println(first + " + " + second + " = " + sum);
}
}

Page 22 of 37
4) A program to subtract two integers.
Code:
public class minus {
public static void main(String[ ] args) {

int first = 50;


int second = 20;

// minus two numbers


int sub = first - second;

System.out.println(first + " - " + second + " = " + sub);


}

5) A program
rogram to multiply two integers.
Code:
public class multi {
public static void main(String[ ] args) {

int first = 5;
int second = 20;

// multiply two numbers

int mult = first * second;

System.out.println(first + " * " + second + " = " + mult);

}
}

6) A program
rogram to divide two integers.
Code:
public class divide {
public static void main(String[ ] args) {

int first = 23;


int second = 7;

// divide two numbers

int divide = first / second;

Page 23 of 37
System.out.println(first + " / " + second + " = " + divide);
}
}

7) Program to find out remainder.


Code:
public class reminder {
public static void main(String[ ] args) {

int first = 23;


int second = 7;

// remainder of two numbers

int ans = ffirst % second;

System.out.println(first + " % " + second + " = " + ans);


}
}

8) Program to describe assignment operators.


Code:
public class assign {
public static void main(String[ ] args) {
int a =1;
int b =2;
int c =3;
int d =4, e=15;
System.out.println("
System.out.println("\t ------------------");
System.out.println("
System.out.println("\tassignment operators");
System.out.println("
System.out.println("\t ------------------");
//assignment operators
op
a +=2; //a =a+2
System.out.println("a is "+a);
b -=1;
- // b=b-1
System.out.println("b is "+b);
c *=10; // c=c*10

Page 24 of 37
System.out.println("c is "+c);
d /=2; //d=d/2
System.out.println("d is "+d);
e %=2; //e=e%2
System.out.println("e is "+e);
}
}
9) Program to demonstrate get number as input from user.
Code:
import java.util.Scanner;
public class input {

public static void main(String[ ] args) {

// Creates a reader instance which takes


// input from standard input - keyboard

Scanner reader=new Scanner(System.in);

System.out.println("enter any number");

// nextInt() reads the next integer from the keyboard

int number=reader.nextInt();

System.out.println("your entered: "+number);


}
}

10) Program to demonstrate collect text as input from user.


Code:
import java.util.Scanner;
public class text {
public static void
oid main(String[ ] args) {
Scanner getdata = new Scanner(System.in);
System.out.println("
System.out.println("\twelcome to my program. \n\t------------
---------------");
System.out.println(" what is your name? ");

Page 25 of 37
// collect your name and store on your_name
String your_name= getdata.nextLine();

System.out.println("Hello! "+ your_name);


}
}
11) Program to store and display different data types in java.
Code:
public class data_types {
public sta
static void main(String[ ] args) {
int g=457868;
float h=5.78f;
Check page no. 6
double i=5.78695;
and
char alphabet='g';
page no.7
7 for explanation.
Boolean is_open=false;
byte byteVariable=127;
short shortVariable=2356;
String text="vintage academy";
//output
System.out.println(g);
System.out.println(h);
System.out.println(i);
System.out.println(alphabet);
System.out.println(is_open);
System.out.println(byteVariable);
System.out.println(shortVariable);
System.out.println(text);
}
}

Page 26 of 37
12) Write a program for find out square root of any number.

Code:
import java.util.Scanner;

public class squareroot {


public static void main(String[ ] args) {
double result=0; // your can use integer also
System.out.println("enter any number : ");
Scanner getno = new Scanner(System.in);
double n= getno.nextDouble()
getno.nextDouble();

result= Math.sqrt(n);
System.out.println("Answer is : "+result);
}
}

13) Write a program


rogram for find out greater number amongst two integer.
Code:
public class greater {
public static void main(String[ ] args) {
int a=100, b=45;
System.out.println("Greater number is : ");
if(a>b){
System.out.println(a);
}
else{
System.out.println(b);
}
}
}

Page 27 of 37
14) Write a program for find out sm
smaller
aller number amongst two numbers.
number
Code:
public class smaller {
public static void main(String[ ] args) {
int z=67, w=109;
System.out.println(
System.out.println("~ a program for
or find out smaller number. ~");
if(z<w){
Syst
System.out.println(z
em.out.println(z + " is smaller than " + w);
}
else{
System.out.println(w + " is smaller than "+ z);
}
}
}
15) A programs for demonstrate all loop
loops in java.

a) while loop:
A while loop is a control flow statement
statement that allows code to be executed
repeatedly based on a given Boolean condition. The while loop can be thought of as
a repeating if statement.
Syntax:
while (boolean condition){
loop statements...
}

code:
public class whileloop
op {
public static void main(String[ ] args) {
int u=0;

while (u<=4){
System.out.println(u);

Page 28 of 37
u++; //for increment
}
}
}

b) do….while loop:
A do while loop is similar to while loop with only difference
difference that it checks for
condition after executing the statements, and therefore is an example of Exit Control
Loop.
Syntax:
do
{
statements..
}
while (condition);

code:
public class dowhile {
public static void main(String[ ] args) {
int u=0;
do{
System.out.println(u);
u++; //for increment
}while(u<=7);
}
}

c) for loop:
A for loop provides a concise way of writing the loop structure. Unlike a while
loop, a for statement
ment consumes the initialization, condition and increment/decrement
in one line thereby providing a shorter, easy to debug structure of looping.

Syntax:
for (initialization condition; testing condition; increment/decrement)
{
statement(s)
}

Page 29 of 37
16) Write a program to display a number series from 1 to 10 using for loop.
loop
Code:
public class series {
public static void main(String[ ] args) {
int s;
for(s=1; s<=10; s++){
System.out.print(s + ", ");
}
}
}
17) Write a program to display odd series from 1-20.
1
Code:
public class odd {
public static void main(String[ ] args) {
int p;
for(p=1; p<=20; p=p+2){
System.out.print(p + ", ");
}
}
}

Page 30 of 37
18) Write a program to print user defined text for 5 times.
Code:
import java.util.Scanner;

public class message {


public static void main(String[ ] args) {
Scanner m= new Scanner(System.in);
System.out.println("ENTER YOUR TEXT:
TE ");
String text= m.nextLine();

System.out.println("Message is given below


below- ");
for(int a=1; a<6; a++){
System.out.println(text);
}
}
}
19) A program to display current date and time.
Code:
import java.time.LocalDateTime;
public class time {
public static void main(String[ ] args) {
LocalDateTime today= LocalDateTime.now();
System.out.print("current date and time is: ");
System.out.print(today);
}
}

Page 31 of 37
20) Write a program for initialize and display the element of an array in java.
java
Code:
public class testarray {
public static void main(String[ ] args) {
//declares an array of integers
int[ ] numbers;

//allocates memory for 5 integers


numbers= new int[5];

//initialize 1st element of array


numbers[0]=45;
//initialize 2nd element of array
numbers[1]=23;
//and others also For explanation of array
numbers[2]=25; see in page
p 8 and 9

numbers[3]=12;
//initialize 5th element
numbers[4]=3;
// initialize is over

System.out.println(
System.out.println("~ The following
ing are the elements of array. ~
~");

System.out.println("e
System.out.println("element
lement of index 0: "+ numbers[0]);
System.out.println("element of index 1: "+ numbers[1]);
System.out.println("element of index 2: "+ numbers[2]);
System.out.println("element of index 3: "+ numbers[3]);
Syste
System.out.println("element
m.out.println("element of index 4: "+ numbers[4]);
}
}

Page 32 of 37
Or, Write a program forr initialize and display the element of an array using for
loop.
Code:
import java.util.Scanner; //for collect input from user
public class anarray {
public static void
id main(String[ ] args) {

//declare and allocate memmory for an array


int[ ] numbers= new int[6];

Scanner no= new Scanner(System.in);

System.out.println("~ welcome to my program. ~");

System.ou
System.out.println("--------input--------");
//declare a loop for assign an element in your array
for(int a=0; a<6; a++){
int e=a+1; //for design
System.out.print("Enter your "+ e +" : ");
numbers[a] = no.nextInt(); //intialize data every time
}

System.out.println("
System.out.println("-------output--------");
//a loop for display all element
for(int b=0; b<6; b++){
int el=b+1; //for design
System.out.println(el +" element is : "+ numbers[b]);
}
}
}

Page 33 of 37
21) A program for introduce class and object in java.
code:
//class declaration
class student{ Note: File name is testclass.java
int id=986750;
String name="ram das";
int dob=21032005;
}
public class testclass {
public static void main(String[] args) {
System.out.println("
System.out.println("\t~
t~ Intro with class and object ~");
//create object
student ram= new student();
//printing
printing the value of the member
members
System.out.println(ram.id);
System.out.println(ram.name);
System.out.println(ram.dob);
}
}
22) A program for find out the area of rectangle using class and object.
Code:
class area{
Note: File name is rectangle
rectangle.java
int length;
int width;
//create a function for collect data
void insert(int l, int w){
length=l;
width=w;
}
//create a method for calculate

Page 34 of 37
void calculateArea(){
System.out.print("
System.out.print("\tArea is : ");
System.out.println(length*width);
em.out.println(length*width);
}
}
public class rectangle {
public static void main(String[] args) {
// object created
area abcd= new area();
area pqrs= new area();

//collect data for object


abcd.insert(11,7);
pqrs.insert(23,31);

//printing the area of rectangle


System.out.println("For 'abcd' rectangle:");
abcd.calculateArea();

System.out.println("For 'pqrs' rectangle:");


pqrs.calculateArea();
}
}
23) A program for draw rectangle in java. (introduction with GUI)
Note:
For rectangle:
The drawRect(x, y, width, height) method, draws
raws the outline of the specified rectangle. The
left and right edges of the rectangle are at x and x + width. The top and bottom edges are
at y and y + height. The rectangle is drawn using the graphics context's current color.
Parameters: x - the x coordinate of the rectangle to be drawn.
y - the y coordinate of the rectangle to be drawn.

Page 35 of 37
width - the width of the rectangle to be drawn.
height - the height of the rectangle to be drawn.
For circle:
The drawOval(x,x, y, width, height
height) method takes four arguments: the first two
represent the top-left
left corner of the imaginary rectangle and the other two represent
the width and height of the oval itself.

Code:
import java.awt.Color; //for color
import java.awt.Graphics; //for graphics
import javax.swing.JFrame; //for jframe

public class drawrectangle extends JFrame{


//creating app window
public
lic drawrectangle()
{
super("Rectangle in GUI");

//window size
setSize(600,600);

//visible
setVisible(true);

//for exit
setDefaultCloseOperation(EXIT_ON_CLOSE);
}

//draw rectangle
ngle using user defined method
public void paint(Graphics gh)
{
super.paint(gh);

Page 36 of 37
//set color for outline
gh.setColor(Color.red);

//set outline and position of top


top-left corner
gh.drawRect(90,100,400,150);

//set fillcolor
gh.setColor(Color.CYAN);

//filling color in a shape


gh.fillRect(95,105,390,140);
}

public static void main(String[] args) {


//for execute above code for class
drawrectangle rec=new drawrectangle();

rec.paint(null);
}
}

Page 37 of 37

You might also like