You are on page 1of 71

THEORY

1.Revision of class 9 syllabus Unit


1:
INTRODUCTION OF JAVA
Java is a class-based, object-oriented programming language that is
designed to have as few implementation dependencies as possible. It is a
general-purpose programming language intended to let application
developers write once, run anywhere (WORA),[17] meaning that compiled
Java code can run on all platforms that support Java without the need for
recompilation.[18] 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 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. As of
2019, Java was one of the most popular programming languages in use
according to GitHub,[19][20] particularly for clientserver web applications,
with a reported 9 million developers.[21]
Java was originally developed by James Gosling at Sun
Microsystems (which has since been acquired by Oracle) and released in
1995 as a core component of Sun Microsystems' Java 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, Sun had relicensed most of its Java technologies under the GNU
General Public License. Oracle offers its own Hot
Spot Java Virtual Machine, however the official reference implementation is
the OpenJDK JVM which is free open source software and used by most
developers including the Eclipse IDE and is the default JVM for almost all
Linux distributions.
The latest version is Java 15, released in September 2020, with Java 11, a
currently supported long-term support (LTS) version, released on
September 25, 2018; Oracle released for the legacy Java 8 LTS the last
zero-cost public update in January 2019 for commercial use, although it will
otherwise still support Java 8 with public updates for personal use up to at
least December 2020. Other vendors have begun to offer zero-cost builds of
OpenJDK 8 and 11 that are still receiving security and other upgrades.
Oracle (and others) highly recommend uninstalling older versions of Java
because of serious risks due to unresolved security issues. [22] Since Java 9,
10, 12 and 13 are no longer supported, Oracle advises its users to
immediately transition to the latest version (currently Java 15) or an LTS
release.

Null Literals: Null literals denotes the Objects: Object is a unique entity having some
characteristics and behaviour. It is known as an ‘Instance of a Class’.
Class: Class is a blue print or prototype of an object. It is known as ‘Object Factory’.
Tokens: Tokens is a set of valid characters used for writing a statement in java
program. In other words we may say that a Java statement comprises a number
of tokens . They are the smallest elements of the program identified by the
compiler.
The different types of tokens used in java are:
Literals, Identifiers, Assignment, Operators, Punctuators, Separators, Keywords.
Literals: You would be heard about constants in mathematics. They have fixed
values which can’t be changed at all. The term constants are referred to as literals
in java programing that remain unchanged during entire execution of the
program.
The various types of literals used in java:
Integer, Real, Character, String, Boolean, Null.
Integer literals: The whole numbers are known as integer literals.
Example: 43, 345,312, etc.
Real literals: Real literals are also called as floating point numbers. They are the
fractional numbers.
Example: 23.4,435.7,21.3, etc.
Character literals: a single letter or a digit or any special symbol enclosed within
single quotes is known as a character literal.
Example: ‘a’,’3’,’;’, etc.
String literals: A set of group of characters enclosed within double quotes is known
as String literal.
Example: ”Sting”, ”Computer”, ”Java”, etc.
Boolean literals: Boolean literals are true or false. A Boolean literal can either be
true of false.
Datatypes in
java
A data type is an attribute of a variable which tells the compiler or
interpreter how the programmer intends to use the variable. It defines the
operations that can be done on the data and what type of values can be
stored. In this article, I will give you a brief insight into the different data
types in Java. According to the properties they possess, data types are
divided into two groups:

1. Primitive Data Types


2. Non-Primitive Data Types
Primitive Data Types: A primitive data type is pre-defined by the
programming language. The size and type of variable values are specified,
and it has no additional methods.

Non-Primitive Data Types: These data types are not actually defined by
the programming language but are created by the programmer. They are
also called “reference variables” or “object references” since they reference
a memory location which stores the data.

Now, let’s move further and get into the details of Primitive Data Types.

Primitive Data Types


Data types in Java are classified into 4 aspects as int, float, character
and boolean. But, in general, there are 8 data types. They are as
follows:

• boolean data type


• byte data type
• char data type
• short data type
• int data type
• long data type
• float data type
• double data type

Non-Primitive Datatypes
Non-Primitive data types refer to objects and hence they are called
reference types. Examples of non-primitive types include Strings, Arrays,
Classes, Interface, etc. Below image depicts various non-primitive data
types.

They are as follows

Strings

Arrays

Class

Interface
Java Operators
with Examples
Operators constitute the basic building block to any programming language.
Java too provides many types of operators which can be used according to the
need to perform various calculation and functions be it logical, arithmetic,
relational etc. They are classified based on the functionality they provide. Here
are a few types:
1. Arithmetic Operators 2.
Unary Operators
3. Assignment Operator
4. Relational Operators
5. Logical Operators
6. Ternary Operator
7. Bitwise Operators
8. Shift Operators
This article explains all that one needs to know regarding the Unary Operators.
Unary Operators in Java
Java unary operators are the types that need only one operand to perform
any operation like increment, decrement, negation etc. It consists of various
arithmetic, logical and other operators that operate on a single operand.
Let’s look at the various unary operators in detail and see how they operate.
1.Unary minus(-): This operator can be used to convert a
negative value to a positive one. Syntax:
-(operand )

Example:
a = -10

2.‘NOT’ Operator(!): This is used to convert true to false or vice versa. Basically it
reverses the logical state of an operand.
Syntax:
!( operand )

Example:
cond = !true;

// cond < false


3.Increment(++): It is used to increment the value of an integer. It can be used in
two separate ways:
a. Post-increment operator: When placed after the variable name, the
value of the operand is incremented but the previous value is
retained temporarily until the execution of this statement and it gets
updated before the execution of the next statement. Syntax:
num++
Example:
num = 5
num++ = 6
4.Pre-increment operator: When placed before the variable name, the operand’s
value is incremented instantly.
Syntax:
++ num

Example:
num = 5

++ num = 6

5.Decrement(--): It is used to decrement the value of an integer. It can be used in


two separate ways:
a. Post-decrement operator: When placed after the variable name, the
value of the operand is decremented but the previous values is
retained temporarily until the execution of this statement and it gets
updated before the execution of the next statement.
Syntax:
num --

Example:
num = 5

num -- = 4

b. Pre-decrement operator: When placed before the variable name, the


operand’s value is decremented instantly. Syntax:
--num
Example: num =
5
--num = 4
Operator
Precedence
Table
Java Operator Precedence
Operators Precedence

postfix increment and decrement ++ -


-
prefix increment and decrement, and unary ++ -- + - ~ !

* / %
multiplicative

additive + -
>> >>>
shift <<> <= >= instanceof
!
relational <== =

equality

bitwise AND &

bitwise exclusive OR ^

bitwise inclusive OR |

The table below lists the precedence of operators in Java; higher it appears in
the table, the higher its precedence.
&
&
logical AND

logical OR |
|
ternary ?
:
=+= - *= /= %=
assignment =
&= ^= |= <<= >>= >>>=

Java Arrays
Arrays are used to store multiple values in a single variable, instead of declaring
separate variables for each value.

To declare an array, define the variable type with square brackets:


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

Access the Elements of an


Array

You 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
Note: Array indexes start with 0: [0] is the first element. [1] is
the second element, etc.

Change an Array Element

To change the value of a specific element, refer to the index


number:

Example
cars[0] = "Opel";
Example

String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};

cars[0] = "Opel";

System.out.println(cars[0]);

// Now outputs Opel instead of Vol

Array Length

To find out how many elements an array has, use the


length property:

Example
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};

System.out.println(cars.length);

// Outputs 4

Loop Through an Array


You can loop through the array elements with the for loop, and
use length property to specify how many times the loop
the
should
run.
The following example outputs all elements in the cars array:
Example

String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};

for (int i = 0; i < cars.length; i++) {

System.out.println(cars[i]);

Loop Through an Array with


For-Each

There is also a "for-each" loop, which is used exclusively to loop


through elements in arrays:

Syntax
for (type variable : arrayname) {

...

}
The following example outputs all elements in the cars array,
using a "for-each" loop:

Example
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"}; for
(String i : cars) {

System.out.println(i);

}
The example above can be read like this: for
each String element (called i - as in index) in cars, print out the
value of i.

If you compare the for loop and for-each loop, you will see that
the for-each method is easier to write, it does not require a
counter (using the length property), and it is more readable.

One-
dimensional
arrays
A one-dimensional array (or single dimension array) is a type of linear array.
Accessing its elements involves a single subscript which can either represent
a row or column index.
As an example consider the C declaration int anArrayName[10]; which declares a
one-dimensional array of ten integers. Here, the array can store ten elements of
type int . This array has indices starting from zero through nine. For example, the
expressions anArrayName[0] and anArrayName[9] are the first and last elements
respectively.
For a vector with linear addressing, the element with index i is located at the
address B + c × i, where B is a fixed base address and c a fixed constant,
sometimes called the address increment or stride.
If the valid element indices begin at 0, the constant B is simply the address of the
first element of the array. For this reason, the C programming language specifies
that array indices always begin at 0; and many programmers will call that element
"zeroth" rather than "first".
However, one can choose the index of the first element by an appropriate choice
of the base address B. For example, if the array has five elements, indexed 1
through 5, and the base address B is replaced by B + 30c, then the indices of those
same elements will be 31 to 35. If the numbering does not start at 0, the constant
B may not be the address of any element.

String handling
What is a Java String? In Java, a string is an object that represents a sequence of
characters or char values. The java.lang.String class is used to create a Java string
object.
There are two ways to create a String object:

1. By string literal : Java String literal is created by using double quotes. For
Example: String s=“Welcome”;
2. By new keyword : Java String is created by using a keyword “new”.
For example: String s=new String(“Welcome”); It creates two objects (in
String pool and in heap) and one reference variable where the variable ‘s’ will refer
to the object in the heap.

Now, let us understand the concept of Java String pool.

Java String Pool: Java String pool refers to collection of Strings which are stored in
heap memory. In this, whenever a new object is created, String pool first checks
whether the object is already present in the pool or not. If it is present, then same
reference is returned to the variable else new object will be created in the String pool
and the respective reference will be returned.
Java String
Methods
1 public class Example{
2 public static void main(String args[]{
3 String s1="hello";
4 String s2="whatsup";
5 System.out.println("string length is: "+s1.length());
6 System.out.println("string length is: "+s2.length());
7 }}
1 public class CompareToExample{
2 public static void main(String args[]){
3 String s1="hello";
4 String s2="hello";
• Java String length(): The Java String length() method tells the
length of the string. It returns count of total number of
characters present in the String. For example:

Here, String length() function will return the length 5 for s1 and 7 for
s2 respectively.

• Java String compareTo(): The Java String compareTo() method


compares the given string with current string. It is a method of
‘Comparable’ interface which is implemented by String class.
Don’t worry, we will be learning about String interfaces later. It
either returns positive number, negative number or 0. For
example:

This program shows the comparison between the various string. It


is noticed that if s1 > s2, it returns a positive number if s1 < s2,
it returns a negative number if s1 == s2, it returns 0
5 String s3="hemlo";

6 String s4="flag";

7 System.out.println(s1.compareTo(s2)); // 0 because both ar

8 System.out.println(s1.compareTo(s3)); //-1 because "l" is onl


lower than "m"
9
System.out.println(s1.compareTo(s4)); // 2 because "h" is
10 greater than "f"
}}
1 public class ConcatExample{
2 public static void main(String args[]){
3 String s1="hello";
4 s1=s1.concat("how are you");
5 System.out.println(s1);
6 }}
1 public class IsEmptyExample{
2
• Java String concat() : The Java String concat() method combines
a specific string at the end of another string and ultimately
returns a combined string. It is like appending another string.
For example:

• The above code returns “hellohow are you”.

• Java String IsEmpty() : This method checks whether the String


contains anything or not. If the java String is Empty, it returns
true else false. For example:

1 public class StringTrimExample{


2 public static void main(String args[]){
3 String s1=" hello ";
4 System.out.println(s1+"how are you"); // without
5 trim()
6 System.out.println(s1.trim()+"how are you"); // with
trim()
}}
3 public static void main(String args[]){

4 String s1="";

5 String s2="hello";

6 System.out.println(s1.isEmpty()); // true

7 System.out.println(s2.isEmpty()); // false
}}
1 public class StringLowerExample{
2 public static void main(String args[]){
3 String s1="HELLO HOW Are You?”;
4 String s1lower=s1.toLowerCase();
• Java String Trim() : The java string trim() method removes the
leading and trailing spaces. It checks the unicode value of space
character (‘u0020’) before and after the string. If it exists, then
removes the spaces and return the omitted string. For example:

• In the above code, the first print statement will print “hello how
are you” while the second statement will print “hellohow are
you” using the trim() function.
• Java String toLowerCase() : The java string toLowerCase()
method converts all the characters of the String to lower case.
For example:

• The above code will return “hello how are you”.


• Java String toUpper() : The Java String toUpperCase() method
converts all the characters of the String to upper case. For
example:

1 public class StringUpperExample{


2 public static void main(String args[]){
3 String s1="hello how are you";

4 String s1upper=s1.toUpperCase();

5 System.out.println(s1upper);

6 }}

5 System.out.println(s1lower);}

6 }
1 public class StringValueOfExample{
2 public static void main(String args[]){ int
3 value=20;
String s1=String.valueOf(value);

• The above code will return “HELLO HOW ARE YOU”.

• Java String ValueOf(): This method converts different types of


values into string.Using this method, you can convert int to
string, long to string, Boolean to string, character to string, float
to string, double to string, object to string and char array to
string. The signature or syntax of string valueOf() method is
given below:
public static String valueOf(boolean b)
public static String valueOf(char c)
public static String valueOf(char[] c)
public static String valueOf(int i)
public static String valueOf(long l)
public static String valueOf(float f)
public static String valueOf(double d)
public static String valueOf(Object o)

Let’s understand this with a programmatic example:

In the above code, it concatenates the Java String and gives the
output – 2017.

• Java String replace(): The Java String replace() method returns a


string, replacing all the old characters or CharSequence to new
characters. There are 2 ways to replace methods in a Java
String.
• In the above code, it will replace all the occurrences of ‘h’ to ‘t’.
Output to the above code will be “tello tow are you”. Let’s see
the another type of using replace method in java string:

1 public class ReplaceExample2{


2 public static void main(String args[]){
3 String s1="Hey, welcome to Edureka";
4 String
5 replaceString=s1.replace("Edureka","Brainforce")
6 System.out.println(replaceString); }}
1 public class ReplaceExample1{
2 public static void main(String args[]){
3 String s1="hello how are you";
4 String replaceString=s1.replace('h','t');
5 System.out.println(replaceString); }}
1 class ContainsExample{
2
public static void main(String args[]){
3
String name=" hello how are you doing";
4
4 System.out.println(s1+17); //concatenating string with 10
}}
5
6
Java String replace(CharSequence target, CharSequence
replacement) method :

• In the above code, it will replace all occurrences of “Edureka” to


“Brainforce”. Therefore, the output would be “ Hey, welcome to
Brainforce”.
• Java String contains() :The java string contains() method
searches the sequence of characters in the string. If the
sequences of characters are found, then it returns true otherwise
returns false. For example:

• In the above code, the first two statements will return true as it
matches the String whereas the second print statement will
return false because the characters are not present in the string.
1 public class EqualsExample{
public static void main(String args[]){
2 String s1="hello";
3 String s2="hello";
4
String s3="hi";
5
System.out.println(s1.equalsIgnoreCase(s2)); // return
6
true System.out.println(s1.equalsIgnoreCase(s3)); //
7
8 return false
9 }
}
public class EqualsIgnoreCaseExample{
1 public static void main(String args[]){
2 String s1="hello";
3 String s2="HELLO";
4
String s3="hi";
5
System.out.println(s1.equalsIgnoreCase(s2)); // return
6
7 true
8 System.out.println(s1.equalsIgnoreCase(s3)); // return
false
5 System.out.println(name.contains("how are you")); //
6 returns true
7 System.out.println(name.contains("hello")); //
returns true
System.out.println(name.contains("fine")); //
returns false
}}
• Java String equals() : The Java String equals() method compares
the two given strings on the basis of content of the string i.e
Java String representation. If all the characters are matched, it
returns true else it will return false. For example:

• Java String equalsIgnoreCase(): This method compares two


string on the basis of content but it does not check the case like
equals() method. In this method, if the characters match, it
returns true else false. For example:
}}
• In the above code, the first statement will return true because the
content is same irrespective of the case. Then, in the second
print statement will return false as the content doesn’t match in
the respective strings.
• Java String toCharArray(): This method converts the string into a
character array i.e first it will calculate the length of the given
Java String including spaces and then create an array of char
type with the same content. For example:

1 public class StringGetBytesExample {


2 public static void main(String args[]){
3 String s1="ABC"; byte[]
4 b=s1.getBytes();
5 for(int i=0;i<b.length;i++){
6
System.out.println(b[i]);
7
8 }
}}
1 StringToCharArrayExample{ public
2 static void main(String args[]){
3 String s1="Welcome to Edureka"; char[]
4 ch=s1.toCharArray();
5
for(int i=0;i<ch.length;i++){
6
System.out.print(ch[i]); }}}
7
1 public class IsEmptyExample{ public
2 static void main(String args[]) {
3 String s1="";
• The above code will return “Welcome to Edureka”.

• Java StringGetBytes() : The Java string getBytes() method


returns the sequence of bytes or you can say the byte array of
the string. For example:

• In the above code, it will return the value 65,66,67.


• Java String IsEmpty() : This method checks whether the String is
empty or not. If the length of the String is 0, it returns true else
false. For example:

In the above code, the first print statement will return true as it does
not contain anything while the second print statement will return
false.

• Java String endsWith() : The Java String endsWith() method


checks if this string ends with the given suffix. If it returns with
the given suffix, it will return true else returns false. For
example:

This is not the end. There are more Java String methods that will help
you make your code simpler.

1 public class EndsWithExample{


2 public static void main(String args[]) {
3 String s1="hello how are you”;
4 System.out.println(s1.endsWith("u")); // returns true
5 System.out.println(s1.endsWith("you")); // returns true
6 System.out.println(s1.endsWith("how")); // returns false
7 }}
4 String s2="hello";
5 System.out.prinltn(s1.isEmpty()); // returns true
6 System.out.prinltn(s2.isEmpty()); // returns false
7 }}
Moving on, Java String class implements three interfaces, namely –
Serializable, Comparable and CharSequence.

Methods in java
A method is a block of code which only runs when it is called.

You can pass data, known as parameters, into a method.


Methods are used to perform certain actions, and they are also
known as functions.

Why use methods? To reuse code: define the code once, and use it
many times.

Create a Method

A method must be declared within a class. It is defined with the


name of the method, followed by parentheses (). Java provides

you can also create your own methods to perform certain actions:

Example

Create a method inside MyClass:

public class MyClass {

static void myMethod() {

// code to be executed

Example Explained
some pre-defined methods, such as System.out.println(), but

• myMethod() is the name of the method


• static means that the method belongs to the MyClass class
and not an object of the MyClass class. You will learn more
about objects and how to access methods through objects
later in this tutorial.
• void means that this method does not have a return value.
You will learn more about return values later in this chapter
Call a method
To call a method in Java, write the method's name followed by two parentheses ()
and a semicolon;
In the following example, myMethod() is used to print a text (the
action), when it is called:

Example

Inside main , call the myMethod() method:

public class MyClass {

static void myMethod () {

System .out .println ("I just got executed!" );

public static void main (String [] args ) {

myMethod () ;

// Outputs "I just got executed!"

A method can also be called multiple times:

Example
public class MyClass { static void

myMethod() {

System.out.println("I just got executed!");


} public static void main(String[] args) {

myMethod();

myMethod(); myMethod();

// I just got executed!

// I just got executed!

// I just got executed!

Parameters and Arguments


Information can be passed to methods as parameter. Parameters
act as variables inside the method.

Parameters are specified after the method name, inside the


parentheses. You can add as many parameters as you want, just
separate them with a comma.

The following example has a method that takes


a String called fname as parameter. When the method is called,
we pass along a first name, which is used inside the method to
print the full name:
Example
public class MyClass {

static void myMethod(String fname) {

System.out.println(fname + " Refsnes");

} public static void main(String[]

args) { myMethod("Liam");

myMethod("Jenny"); myMethod("Anja");

// Liam Refsnes

// Jenny Refsnes

// Anja Refsnes

fname
When a parameter is passed to the method, it is called
an argument. So, from the example above: is
a parameter, while Liam, Jenny and Anja are arguments.
Multiple Parameters

You can have as many parameters as you like:

Example
public class MyClass { static void

myMethod(String fname, int age) {

System.out.println(fname + " is " + age);

} public static void main(String[]

args) { myMethod("Liam", 5);

myMethod("Jenny", 8); myMethod("Anja",

31);

// Liam is 5

// Jenny is 8 //

Anja is 31

Note that when you are working with multiple parameters, the
method call must have the same number of arguments as there
are parameters, and the arguments must be passed in the same
order.
Return Values
The void keyword, used in the examples above, indicates that the
method should not return a value. If you want the method to
return a value, you can use a primitive data type (such as int,
char, etc.) instead of void, and use the return keyword inside
the method:

Example
public class MyClass {

static int myMethod(int x) {

return 5 + x;

} public static void main(String[]

args) {

System.out.println(myMethod(3));

// Outputs 8 (5 + 3)

This example returns the sum of a method's two parameters:

Example
public class MyClass { static int
myMethod(int x, int y) { return x
+ y;
} public static void main(String[]

args) {

System.out.println(myMethod(5, 3));

// Outputs 8 (5 + 3)

You can also store the result in a variable (recommended, as it is


easier to read and maintain):

Example
public class MyClass { static int

myMethod(int x, int y) { return x

+ y;

} public static void main(String[]

args) { int z = myMethod(5, 3);

System.out.println(z);

// Outputs 8 (5 + 3)

Run example »
A Method with
If...Else
It is common to use if...else statements inside methods:

Example
public class MyClass {

// Create a checkAge() method with an integer variable


called age static void checkAge(int age) {

// If age is less than 18, print "access denied"

if (age < 18) {

System.out.println("Access denied - You are not old


enough!");

// If age is greater than, or equal to, 18, print "access


granted"

} else {

System.out.println("Access granted - You are old


enough!");

}
public static void main(String[] args) {

checkAge(20); // Call the checkAge method and pass along


an age of 20

// Outputs "Access granted - You are old enough!”

Method
Overloading
With method overloading, multiple methods can have the same
name with different parameters:

Example
int myMethod(int x) float
myMethod(float x) double
myMethod(double x, double y)

Consider the following example, which have two methods that add
numbers of different type:

Example
static int plusMethodInt(int x, int y) {

return x + y;

} static double plusMethodDouble(double x, double


y) { return x + y;
}

public static void main(String[] args) {

int myNum1 = plusMethodInt(8, 5);

double myNum2 = plusMethodDouble(4.3, 6.26);

System.out.println("int: " + myNum1);

System.out.println("double: " + myNum2);

Run example »

Instead of defining two methods that should do the same thing, it


is better to overload one.
In the example below, we overload the plusMeth od method to
work for both int and double :

Example

static int plusMethod ( int x , int y) {

return x + y;

static double plusMethod ( double x , double y) {

return x + y;

public static void main ( String [] args ) {

int myNum1 = plusMethod(8, 5); double myNum2 =

plusMethod(4.3, 6.26); System.out.println("int: " +

myNum1);

System.out.println("double: " + myNum2);

Run example »

Note: Multiple methods can have the same name as long as the
number and/or type of parameters are different.

Programs
2 Write a program to generate a triangle or an inverted triangle till ‘n’ terms
based on user’s choice of triangle to be displayed.
Type 1 Type 2
1 54321
2 1 4321
3 21 321
4 321 21
5 4 3 2 1...n 1
import java.util.*; class
Triangle2

{
public static void main()
{

Scanner sc= new Scanner(System.in);


System.out.println("Type 1 for a triangle");
System.out.println("Type 2 for an inverted triangle");

System.out.print("Enter your choice: ");


int ch = sc.nextInt();
System.out.print("Enter the number of terms: ");
int n = sc.nextInt();

switch (ch)
{
case 1:
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= i; j++)
{
System.out.print(i + " ");
}
System.out.println();
}
break;

case 2:
for (int i = n; i > 0; i--)
{
for (int j = 1; j <= i; j++)
{
System.out.print(i + " ");
}
System.out.println();
}
break;

default:
System.out.println("Incorrect Choice");
}
}
}

Output:
Type 1 for a triangle
Type 2 for an inverted triangle
Enter your choice: 2
Enter the number of terms: 5
55555
4444
333
22
1

VARIABLE DESCRIPTION:
VARIABLE DATA TYPE PURPOSE
ch int choose between the two
types n int store the number of
terms i int count the line of the
loop j int count the numbers in a
line sc Scanner making scanner object

4 Write a program to accept two numbers and find the greatest common divisor
(G.C.D) of those numbers
Sample input-25,45
Sample output- The greatest common divisor :5
import java.util.*; class GCD
{
public static void main()
{
Scanner sc=new Scanner(System.in);
int a,b,i,p,gcd=0;
System.out.println("Enter two numbers");
a=sc.nextInt(); b=sc.nextInt(); p=a*b;
for(i=1;i<p;i++)
{
if(a%i==0&& b%i==0)
gcd=i;
}
System.out.println("The GCD of two numbers are:"+gcd);
}
}

Output:
Enter two numbers
25
45
The GCD of two numbers are:5 VARIABLE
DESCRIPTION:
VARIABLE DATA TYPE PURPOSE
a int store the first number entered b
int store the second number entered i
int counts the iterations in the program p
int multiply the numbers entered gcd
int store the greatest common divisor sc
Scanner making scanner object

5.Write a program to input three different single digit numbers between 1 and
9(both inclusive).Display the greatest and the smallest number.
import java.util.*; class
number
{
public static void main()
{
Scanner sc=new Scanner(System.in);
int a,b,c,gn=0,sn=0;
System.out.println("Enter the number
between 1 and 9"); a=sc.nextInt();
b=sc.nextInt(); c=sc.nextInt();
if((a>b)&&(a>c))
{ if(b>
c)
{
gn=100*a+10*b+c;
sn=100*c+10*b+a;
}
else
{
gn=100*a+10*c+b;
sn=100*b+10*c+a;
}
}
if((b>a)&&(b>c))

{ if(a>
c)
{
gn=100*b+10*a+c;
sn=100*c+10*a+b;
}
else
{
gn=100*b+10*c+a;
sn=100*a+10*c+b;
}
}
if((c>a)&&(c>b))

{ if(a>
b)
{
gn=100*c+10*a+b;
sn=100*b+10*a+c;
}
else
{
gn=100*c+10*b+a;
sn=100*a+10*b+c;
}
}
System.out.println("The greatest number is"+gn);
System.out.println("The smallest number is"+sn);
}
}
Output:
Enter the number between 1 and 9
2
3
4
The greatest number is432 The
smallest number is234

VARIABLE DESCRIPTION:
VARIABLE DATA TYPE PURPOSE
a int store the first number entered b
int store the second number entered c int
store the third number entered gn int store
the value of the greatest number sn int
store the value of the smallest number sc Scanner
making scanner object
6.Write a program in java to input a letter if it is an uppercase letter then encode
it by next 5th letter, otherwise encode it with 3rd previous letter in ASCII table.
import java.util.*; class
Encode
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
char c,ch; int t;
System.out.println("Enter a letter");
c=sc.next().charAt(0);
if(Character.isUpperCase(c))
t=(int)c+5; else t=(int)c-3;
ch=(char)t;
System.out.println("Encoded letter is:+ch);
}
}
Output:
Enter a letter
A
Encoded letter is:F

VARIABLE DESCRIPTION:
VARIABLE DATA TYPE PURPOSE
c character store the character ch
character store value of the encoded letter t
int store the value of ASCII code

sc Scanner making scanner object


8 Write a program to enter two single dimensional array of size n. Add
corresponding elements of two array and store it in the third array. Print the final
array.
import java.util.*; class
merge
{
public static void main()
{
Scanner sc=new Scanner(System.in);
int i,n,m,p;

System.out.println("Enter the number of array elements arr1");


n=sc.nextInt();
System.out.println("Enter the number of array elements arr2");
m=sc.nextInt();
System.out.println("Enter the number of merged elements in the array
arr3");
p=sc.nextInt();
int arr1[]=new int[n];
int arr2[]=new int[m];
int arr3[]=new int[p];
System.out.println("Enter the elements in the array arr1");
for(i=0;i<n;i++)
{
arr1[i]=sc.nextInt();
}
System.out.println("Enter the elements in the array arr2");
for(i=0;i<m;i++)
{
arr2[i]=sc.nextInt();
}
for(i=0;i<n;i++)
arr3[i]=arr1[i]; for(i=0;i<m;i+
+) arr3[n+i]=arr2[i];
System.out.println("Array elements after emerging");
for(i=0;i<p;i++)
System.out.println(arr3[i]);
}
}

Output:
Enter the number of array elements arr1:
4
Enter the number of array elements arr2:
4
Enter the number of array elements arr3:
8
Enter the elements in the array arr1
12
34
45
65
Enter the elements in the array arr2
55
87
98
11
Array elements after emerging
12
34
45 65
55
87
98
11
VARIABLE DESCRIPTION:
VARIABLE DATA TYPE PURPOSE
i int counts the number of iterations in program
n int store the value of the first array m
int store the value for the second array p int
store the value of the third array sc Scanner
making scanner object

9.Write a program to accept 20 different numbers in a single dimensional array.


Using Linear search technique check whether a number entered is present in the
list of the array elements. If present then display the message “Search successful
"otherwise “Search unsuccessful”.
import java .util.*; class
linearsearch
{
public static void main()
{
Scanner sc=new Scanner(System.in);
int s,pos=-1,i;

int a[]=new int[20];


System.out.println("Enter the values in the array:");
for(i=0;i<20;i++)
{
a[i]=sc.nextInt();
}
System.out.print("Enter the value to search:");
s=sc.nextInt(); for(i=0;i<20;i++)
{
if(s==a[i])
{
pos= i+1;
break;
}
}
if(pos !=-1)
System.out.println("Search successful");
else
System.out.println("Search not successful");
}
}
Output:
Enter the values in the array:
21
22
32 45
54
56
76 88
76
56
11 21
19
18
81
71 61
54
32
56
Enter the value to search:12
Search not successful

VARIABLE DESCRIPTION:
VARIABLE DATA TYPE PURPOSE
s int store the number entered to search pos
int store the position of the value
i int counts the number of iterations in the
program a int store all the numbers
entered in the array sc Scanner making scanner object

10 Write a program to accept a set of 10 integers in a single dimensional array.


Sort the numbers in ascending order by using the ‘Selection sort’ techniques.
Display the sorted array.
import java.util.*; class
Sorting
{
public static void main()
{
Scanner sc=new Scanner(System.in);
int i,tmp,j,min;
int a[]=new int[10];
System.out.println("Enter the values in the array:");
for(i=0;i<10;i++)
{
a[i]=sc.nextInt();
}
for(i=0;i<10;i++)
{ min=i;
for(j=i+1;j<10;j++)
{
if(a[min]>a[j])
{
min=j;
} }
if(i!=min)
{
tmp=a[i];
a[i]=a[min];
a[min]=tmp;
}
}
System.out.println("The sorted values in ascending order are:");
for(i=0;i<10;i++)
{
System.out.println(a[i]);
}
}
}

Output:
Enter the values in the array:
12
21
34
76 77
89
98
45
54
57
The sorted values in ascending order are:
12
21
34
45 54
57
76
77 89
98

VARIABLE DESCRIPTION:
VARIABLE DATA TYPE PURPOSE
i int used for counting the number of iterations in the
program
tmp int
j int used to count the number of comparisons in the
program
min int goes through every value one at a time
a int stores all numbers of the array sc
Scanner making scanner object
11 Write a program to accept 10 different numbers in a single dimensional array.
Display the greatest and the smallest number of the elements.
import java.util.*; class
max_min
{
public static void main()
{
Scanner sc =new Scanner(System.in);
int a[]=new int[10]; int i,max, min;
System.out.println("Enter the values in the array:");
for(i=0;i<10;i++)
{
a[i]=sc.nextInt();
}
max=a[0];
for(i=1;i<10;i++)
{
if(max<a[i])
max=a[i];
}
System.out.println("Largest value in the array:" +max);
min=a[0];
for(i=1;i<10;i++)
{
if(min>a[i])
min=a[i];
}
System.out.println("Smallest value in the array is:"+ min);
}
}
Output:
Enter the values in the array:
12
23
45
65
99 98
76
1
63
69
Largest value in the array is:99
Smallest value in the array is:1
VARIABLE DESCRIPTION:
VARIABLE DATA TYPE PURPOSE
a int stores the values entered in the array
i int counts the number of iteration in the program
max int stores the largest value in the array min
int stores the smallest value in the array sc Scanner
making scanner object
12 Write a program on java to accept a set of any 10 characters. Calculate and
print the sum of ASCII code of the characters.
import java.util.*; class
sum
{
public static void main()
{
Scanner sc=new Scanner(System.in);
char ch; int i,s=0;
System.out.println("Enter any 10 characters");
for(i=0;i<10;i++)
{
ch=sc.next().charAt(0);
s=s+ (int)ch;
}
System.out.println("Sum of ASCII codes:"+s);
}
}

Output:
Enter any 10 characters
aD
bs
e
x
b
t
a
m
Sum of ASCII codes:1019 VARIABLE
DESCRIPTION:
VARIABLE DATA TYPE PURPOSE
ch character stores the value of all the characters and print it
i int counts the number of iterations in the
program
s int store the sum of ASCII and print it sc
Scanner for making scanner object

13 Write a program to accept 20 integers numbers in a single dimensional array.


Find and display the following:

1. Number of even numbers


2. Number of odd numbers
3. Number of multiples of 4

import java.util.*;
class Numbers
{
public static void main()
{
Scanner sc=new Scanner(System.in);
int i,j,c1=0,c2=0,c3=0; int a[]=new
int[20];
System.out.println("Enter 20 numbers:");
for(i=0;i<20;i++)
{
a[i]=sc.nextInt();
}
for(i=0;i<20;i++)
{
if(a[i]%2==0)

c1++; if(a[i]
%2!=0) c2++;
if(a[i]%4==0) c3+
+;
}
System.out.println("Even numbers:"+c1);
System.out.println("Odd numbers:"+c2);
System.out.println("Multiple of 4:"+c3);
}
}

Output:
Enter 20 numbers:
12
34 56
76
88
98 99
88
77
66

56
43
44
22 11
19
81
73 49
76
Even numbers:12
Odd numbers:8 Multiple of 4:8
VARIABLE DESCRIPTION:
VARIABLE DATA TYPE PURPOSE
i int counts the number of iterations in the program
c1 int stores the frequency of even numbers and print it
c2 int stores the frequency of odd numbers and print it
c3 int stores the frequency of multiples of 4 and print it
a int stores the values given in the array and print it sc
Scanner for making scanner object

14 Write a program to store 6 elements in an array P and 4 elements in an array


Q. Now, produce a third array R, containing all the elements of array P and Q.
Display the resultant array.
Input Input Output
P[ ] Q[ ] R[ ]
4 19 4
6 23 6
1 7 1
2 8 2
3 3
10 10
19
23
7
8

import java.util.*; class


merge2
{
public static void main()
{
Scanner sc=new Scanner(System.in);
int P[]=new int[6]; int Q[]=new
int[4]; int R[]=new int[10]; int
i=0;
System.out.println("Enter elements of array P:");
for(i=0;i<6;i++)
{
P[i]=sc.nextInt();
}
System.out.println("Enter elements of array Q:");
for(i=0;i<4;i++)
{
Q[i]=sc.nextInt();
} i=0;
while(i<6)
{
R[i]=P[i];
i++;
} int
j=0;
while(j<4)
{
R[i++]=Q[j++];
}
System.out.println("Elements in the array R:");
for(i=0;i<10;i++)
{
System.out.println(R[i]);
}
}
}
Output:
Enter elements of array P:
6
12
34
32 66
77
Enter elements of array Q:
11
49
98
76
Elements in the array R:
6
12
34 32
66
77
11

49
98
76

VARIABLE DESCRIPTION:
VARIABLE DATA TYPE PURPOSE
P int stores the value entered in first array and print it
Q int stores the value entered in second array and print
it
R int stores the value entered in third array and print it
I int counts the number of iterations in the program
Sc Scanner for making scanner object

15.Write a program to enter 10 elements in an array x. Now insert an element


from the array taking the position and element to be inserted from the user.

import java.util.*; class


insert
{
public static void main ()
{
Scanner sc=new Scanner(System.in);
int x[]=new int [10]; int pos, n,i;
System.out.println("Enter the elements in the array:"); for(i=0;i<10;i++)
{
x[i]=sc.nextInt();
}
System.out.println("Enter the position where you want to insert element:");
pos=sc.nextInt();
System.out.println("Enter the element to be inserted:");
n=sc.nextInt(); for(i=(n-1);i>=(pos-1);i--)
{
x[i+1]=x[i];
}
x[pos-1]=n;
System.out.println("Numbers after inserting:"); for(i=0;i<n;i++)
{
System.out.println(x[i]);
}
System.out.println(x[n]);
}
}
Output:
Enter the elements in the array:
12
4
4
53
4565
65 56
74
654
34
Enter the position where you want to insert element:
5
Enter the element to be inserted:
7
Numbers after inserting:
12
4
4
53
7
4565
65
56
VARIABLE DESCRIPTION:
VARIABLE DATA TYPE PURPOSE
N int store the value of the number to be inserted
Pos int stores the position of the of the index
I int goes through the iteration of the loop
X int store the value of all the elements and store it
Sc int for making scanner object

You might also like