Professional Documents
Culture Documents
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:
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.
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.
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;
Example:
num = 5
++ num = 6
Example:
num = 5
num -- = 4
* / %
multiplicative
additive + -
>> >>>
shift <<> <= >= instanceof
!
relational <== =
equality
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.
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.
Example
cars[0] = "Opel";
Example
cars[0] = "Opel";
System.out.println(cars[0]);
Array Length
Example
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
System.out.println(cars.length);
// Outputs 4
System.out.println(cars[i]);
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.
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.
6 String s4="flag";
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:
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);
In the above code, it concatenates the Java String and gives the
output – 2017.
• 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:
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.
This is not the end. There are more Java String methods that will help
you make your code simpler.
Methods in java
A method is a block of code which only runs when it is called.
Why use methods? To reuse code: define the code once, and use it
many times.
Create a Method
you can also create your own methods to perform certain actions:
Example
// code to be executed
Example Explained
some pre-defined methods, such as System.out.println(), but
Example
myMethod () ;
Example
public class MyClass { static void
myMethod() {
myMethod();
myMethod(); myMethod();
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
Example
public class MyClass { static void
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 {
return 5 + x;
args) {
System.out.println(myMethod(3));
// Outputs 8 (5 + 3)
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)
Example
public class MyClass { static int
+ y;
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 {
} else {
}
public static void main(String[] args) {
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;
Run example »
Example
return x + y;
return x + y;
myNum1);
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()
{
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
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
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
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
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
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