U1B Java Basics
U1B Java Basics
PREPARED BY:
CHINTAN A GAJJAR
INFORMATION TECHNOLOGY DEPARTMENT
DR S & S S GHANDHY COLLEGE OF ENGINEERING & TECHNOLOGY, SURAT
Naming Conventions in Java
Naming conventions specify the rules to be followed by a Java programmer
while writing the names of packages, classes, methods, variables etc.
A represents a sub directory that contains a group of classes and
interfaces. Names of packages in Java are written in small letters as:
PREPARED BY: C A GAJJAR, IT DEPT, DR S & S S GHANDHY COLLEGE OF ENGG & TECH, SURAT 2
Naming Conventions in Java
A class and interface contain methods and variables. The first word of a
method name is in small letters; then from second word onwards, each new
word starts with a capital letter as shown here:
The naming convention for variables’ name is same as that for method as
given here:
PREPARED BY: C A GAJJAR, IT DEPT, DR S & S S GHANDHY COLLEGE OF ENGG & TECH, SURAT 3
Data Types in Java
We need variables to store the data. Internally, a variable represents a
memory location to hold data. To use a variable in a program, we have first
declare it with data type.
In Java, there are two types of data:
1. Primitive data types:
PREPARED BY: C A GAJJAR, IT DEPT, DR S & S S GHANDHY COLLEGE OF ENGG & TECH, SURAT 4
Integer Data Types
These data types represent integer numbers, i.e. numbers without any
fractional parts or decimal points. For example, 124, -22943, 0, 1025 etc.
There are again sub divided into below given types.
Data type Memory size Minimum and Maximum values
1 byte
2 bytes
4 bytes
8 bytes
PREPARED BY: C A GAJJAR, IT DEPT, DR S & S S GHANDHY COLLEGE OF ENGG & TECH, SURAT 5
Example
Output:
java.lang.Integer
java.lang.Long
PREPARED BY: C A GAJJAR, IT DEPT, DR S & S S GHANDHY COLLEGE OF ENGG & TECH, SURAT 6
Float Data Types
These data types are useful to represent numbers with decimal points. For
example, 3.14, 0.012, 1.0, -11.49 etc. These are again classified as
(single precision) and (double precision). The only difference is in the
essential number of digits accurately after the decimal point. This accuracy is
also called precision.
Data type Memory size Minimum and Maximum values
4 bytes
8 bytes
Output:
java.lang.Double
java.lang.Float
float can represent up to 7 digits accurately after decimal, whereas double can represent
up to 15 digits accurately after decimal point.
PREPARED BY: C A GAJJAR, IT DEPT, DR S & S S GHANDHY COLLEGE OF ENGG & TECH, SURAT 8
Character Data Type
This data type represents a single character like a, P, &, * etc.
Data type Memory size Minimum and Maximum values
2 bytes
Here, a single character is stored into the variable ch. Here, is called
character literal (constant). Always, a character literals enclosed inside the
single quote.
PREPARED BY: C A GAJJAR, IT DEPT, DR S & S S GHANDHY COLLEGE OF ENGG & TECH, SURAT 9
Boolean Data Type
data type represent any of the two values – true or false. JVM uses
1 bit to represent a value internally.
PREPARED BY: C A GAJJAR, IT DEPT, DR S & S S GHANDHY COLLEGE OF ENGG & TECH, SURAT 10
String Data Type
A represents a group of characters, like “Gujarat”, “AP-123” etc. The
simplest way to create a is by storing a group of characters into a
type variable as:
PREPARED BY: C A GAJJAR, IT DEPT, DR S & S S GHANDHY COLLEGE OF ENGG & TECH, SURAT 11
Reading Input from keyboard with Scanner class
We can use class of package to read input from the
keyboard or a text file. When the class receives input, it breaks it
into several pieces, called tokens. These tokens can be retrieved from the
object using the following methods:
– to read a string.
– to read a single string till the end of the line.
– to read a single char
– to read byte value
– to read an integer value
– to read float value
– to read long value
– to read double value
PREPARED BY: C A GAJJAR, IT DEPT, DR S & S S GHANDHY COLLEGE OF ENGG & TECH, SURAT 12
Example
To read input from keyboard, we can use class as:
Now, if user has given an integer value from the keyboard, it is stored into
the Scanner object (input) as a token. To retrieve that token, we can use the
method:
The program in the next slide will make this concept clear.
PREPARED BY: C A GAJJAR, IT DEPT, DR S & S S GHANDHY COLLEGE OF ENGG & TECH, SURAT 13
Example
Output:
Enter Your ID, Name and Salary:123 Chintan 20000.00
ID =123
Name :Chintan
Salary =20000.0
PREPARED BY: C A GAJJAR, IT DEPT, DR S & S S GHANDHY COLLEGE OF ENGG & TECH, SURAT 14
Command Line Arguments
During program execution, information passed following a program name in
the command line is called Command Line Arguments. In Java, an argument
passed in main( ) method is known as command line arguments.
When we launch an application, we can pass command-line arguments to
the application’s main( ) method through an array of Strings:
Both are valid syntax.
Each element in the array "args" is one command-line argument.
PREPARED BY: C A GAJJAR, IT DEPT, DR S & S S GHANDHY COLLEGE OF ENGG & TECH, SURAT 15
Command Line Arguments
Java command Arguments sent to main( )
args[0] = "word0"
args[1] = "word1“
args[2] = "word2“
and so on…
Here, to store arguments, we usually provide variable name as "args". We can assign any
arbitrary name for the command-line arguments.
For example, is valid.
PREPARED BY: C A GAJJAR, IT DEPT, DR S & S S GHANDHY COLLEGE OF ENGG & TECH, SURAT 16
Command Line Arguments-Example
PREPARED BY: C A GAJJAR, IT DEPT, DR S & S S GHANDHY COLLEGE OF ENGG & TECH, SURAT 17
Command Line Arguments
Here, it is obvious that each argument (though it is a number like 1 2 3) is
stored as a String data type. To perform any operation based on the data
type (here, integer) we have to explicitly convert it. Otherwise, arguments
work as String only. For example,
Sum=12
Here, 1 and 2 are treated as and so + operation concatenates them
and generates result 12 instead of 3.
PREPARED BY: C A GAJJAR, IT DEPT, DR S & S S GHANDHY COLLEGE OF ENGG & TECH, SURAT 18
Command Line Arguments
To convert String argument into integer, there are 2 methods of class:
1. Integer.parseInt(): e.g
Similarly, we can use parseFloat(), parseDouble() and other methods for
other data types.
2. Integer.valueOf(): e.g.
PREPARED BY: C A GAJJAR, IT DEPT, DR S & S S GHANDHY COLLEGE OF ENGG & TECH, SURAT 19
Another Example of CLA
PREPARED BY: C A GAJJAR, IT DEPT, DR S & S S GHANDHY COLLEGE OF ENGG & TECH, SURAT 20
Example of CLA with float arguments
PREPARED BY: C A GAJJAR, IT DEPT, DR S & S S GHANDHY COLLEGE OF ENGG & TECH, SURAT 21
Write a program to find out maximum from array of 10 numbers using CLA
Summer-2024 GTU Exam
class CLA_MAX10{
public static void main(String args[]){
int Arr[] = new int[10];
int i, MAX;
MAX = Integer.parseInt(args[0]);
for(i=1; i<10; i++){
Arr[i] = Integer.parseInt(args[i]);
if(Arr[i]>MAX)
MAX = Arr[i];
}
System.out.println("Maximum = "+MAX);
}
}
PREPARED BY: C A GAJJAR, IT DEPT, DR S & S S GHANDHY COLLEGE OF ENGG & TECH, SURAT 22
OPERATORS in JAVA
PREPARED BY: C A GAJJAR, IT DEPT, DR S & S S GHANDHY COLLEGE OF ENGG & TECH, SURAT 23
Operators
Arithmetic operators: +, -, *, /, %
Relational operators: <, >, >=, <=, !=, ==
Logical operators: &&, ||, !
Increment-Decrement operator: ++, --
Assignment operator: =, +=, -=, *=, /=, %=, <<=, >>=, &=, ^=, |=
Bitwise operators: &, |, ^, ~, <<, >>, >>>
Conditional Operator: ? :
Cast operator: (type) e.g. (int), (float)
Member operator: ( ).
operator, operator
PREPARED BY: C A GAJJAR, IT DEPT, DR S & S S GHANDHY COLLEGE OF ENGG & TECH, SURAT 24
Classification of Operators
Unary operators: This operator works only on one operand. It appears as
prefix or suffix with its operand.
PREPARED BY: C A GAJJAR, IT DEPT, DR S & S S GHANDHY COLLEGE OF ENGG & TECH, SURAT 25
Arithmetic Operators
-14 % 4 = -2
-14 % -2 = -2
14 % -2 = 2
For modulo division, the sign of the result
Is always the sign of the first operand.
PREPARED BY: C A GAJJAR, IT DEPT, DR S & S S GHANDHY COLLEGE OF ENGG & TECH, SURAT 26
Bitwise Operators
00001100
& 00011001
00001000 = 8 (In decimal)
00001100
| 00011001
00011101 = 29 (In decimal)
00001100
^ 00011001
00010101 = 21 (In decimal)
2'complement of
~N= -(~(~N)+1) = -(N+1)
PREPARED BY: C A GAJJAR, IT DEPT, DR S & S S GHANDHY COLLEGE OF ENGG & TECH, SURAT 27
Bitwise Operators
12<<1
Left Shift by 1 = 24 1100 → 11000
12>>2
Right Shift by 2 = 3 1100 → 0110 → 0011
>>> also shifts the bits of the number towards right a specified number of
positions. But, it stores 0 in the sign bit.
If >>> is applied on a positive no, it gives same output as that of >>. But in
case of negative no, the output will be positive, since the sign bit is replaced
by a 0.
The difference between >> and >>> is that >> will protect the sign bit
whereas the >>> operator will not protect the sign bit. It always fills 0 in the
sign bit.
PREPARED BY: C A GAJJAR, IT DEPT, DR S & S S GHANDHY COLLEGE OF ENGG & TECH, SURAT 28
Increment – Decrement (++) (--) operators
The operator ++ adds 1 to the operand while – subtracts
1 from the operand. Both are unary operators.
++m and m++ means the same when they form statements
individually. They behave differently when they are used in
expressions on the right-hand side of an assignment
Statement.
PREPARED BY: C A GAJJAR, IT DEPT, DR S & S S GHANDHY COLLEGE OF ENGG & TECH, SURAT 29
Conditional Operator
PREPARED BY: C A GAJJAR, IT DEPT, DR S & S S GHANDHY COLLEGE OF ENGG & TECH, SURAT 30
Casting Operation
It is possible to convert one primitive data type into another primitive data
type. There are two ways:
1. Implicit Type conversion (widening)
2. Explicit Type conversion (narrowing)
Lower<------------------------------------------------------> Higher
Thus, is lower data type than . is higher that .
Here, is not included because it cannot be converted into any other
type.
PREPARED BY: C A GAJJAR, IT DEPT, DR S & S S GHANDHY COLLEGE OF ENGG & TECH, SURAT 31
Widening casting
Automatic casing done by the Java compiler internally is called implicit
casting. Implicit casting is done to convert a lower data type into higher data
type.
For example,
PREPARED BY: C A GAJJAR, IT DEPT, DR S & S S GHANDHY COLLEGE OF ENGG & TECH, SURAT 32
Explicit casting (narrowing)/Type-cast operator
The casting done by a programmer is called explicit casting. Explicit casting is
compulsory while converting from a higher data type to a lower data type.
For example,
For example,
class TypeCast{
public static void main(String args[]){
int male=100, fem=93;
float ratio = (float)fem / male;
System.out.println("Ratio = "+ratio);
} Note:
Without (float) operation,
} the output is Ratio = 0.0
PREPARED BY: C A GAJJAR, IT DEPT, DR S & S S GHANDHY COLLEGE OF ENGG & TECH, SURAT 33
Control Statements
statement
Nested statement
ladder
statement
loop
loop
loop
loop
PREPARED BY: C A GAJJAR, IT DEPT, DR S & S S GHANDHY COLLEGE OF ENGG & TECH, SURAT 34
if statement needs Boolean expression
class Control{
public static void main(String args[]){
int a = 1, b;
if(a)
b = 1;
else b = 0;
System.out.print("Values="+ a + b);
}
}
F:\T232_Prac>javac Control.java
Control.java:87: error: incompatible types
if(a)
^
required: boolean
found: int
1 error
PREPARED BY: C A GAJJAR, IT DEPT, DR S & S S GHANDHY COLLEGE OF ENGG & TECH, SURAT 35
Nested if Example
class Control{
public static void main(String args[]){
int n1=12, n2=5, n3=30;
if(n1>n2)
if(n1>n3)
System.out.println(n1+" is Maximum");
else System.out.println(n3+" is Maximum");
else
if(n2>n3)
System.out.println(n2+" is Maximum");
else System.out.println(n3+" is Maximum");
}
}
PREPARED BY: C A GAJJAR, IT DEPT, DR S & S S GHANDHY COLLEGE OF ENGG & TECH, SURAT 36
else if ladder Example-1
class Control{
public static void main(String args[]){
int num = -3;
if(num == 0)
System.out.println("Zero");
else if(num>0)
System.out.println(num+" is Positive");
else System.out.println(num+" is Negative");
}
}
PREPARED BY: C A GAJJAR, IT DEPT, DR S & S S GHANDHY COLLEGE OF ENGG & TECH, SURAT 37
else if ladder Example-2
class Control{
public static void main(String args[]){
int mark = 89;
String Grade;
if(mark>=70 && mark<=100)
Grade = "First";
else if(mark>=60 && mark<70)
Grade = "Second";
else if(mark>=59 && mark<60)
Grade = "Pass";
else Grade = "Fail";
System.out.println("Result = "+Grade);
}
}
PREPARED BY: C A GAJJAR, IT DEPT, DR S & S S GHANDHY COLLEGE OF ENGG & TECH, SURAT 38
switch statement Example-1
import java.util.Scanner;
class Control{
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
System.out.print("Enter No-1:");
int n1 = sc.nextInt();
System.out.print("Enter No-2:");
int n2 = sc.nextInt();
System.out.print("Select Option + - * / :");
char opt = sc.next().charAt(0);
switch(opt){
case '+': System.out.println(n1+"+"+n2+"="+(n1+n2));
break;
case '-': System.out.println(n1+"-"+n2+"="+(n1-n2));
break;
case '*': System.out.println(n1+"*"+n2+"="+(n1*n2));
break;
case '/': System.out.println(n1+"/"+n2+"="+(n1/n2));
break;
default: System.out.println("Invalid Operation!!");
}
}
}
PREPARED BY: C A GAJJAR, IT DEPT, DR S & S S GHANDHY COLLEGE OF ENGG & TECH, SURAT 39
switch statement Example-2
import java.util.Scanner;
class Control{
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
System.out.print("Enter No:");
String day = sc.next();
switch(day)
{
case "Sun": System.out.println("Sunday"); break;
case "Mon": System.out.println("Monday"); break;
case "Tue": System.out.println("Tuesday"); break;
case "Wed": System.out.println("Wednesday"); break;
case "Thu": System.out.println("Thursday"); break;
case "Fri": System.out.println("Friday"); break;
case "Sat": System.out.println("Saturday"); break;
default: System.out.println("Wrong Input");
}
}
}
PREPARED BY: C A GAJJAR, IT DEPT, DR S & S S GHANDHY COLLEGE OF ENGG & TECH, SURAT 40
while Loop Example
class WhileLoop{ import java.util.Scanner;
public static void main(String a[]){ class PalindromeWhileLoop{
int count = 101; public static void main(String args[]){
while(count <= 109){ Scanner sc = new Scanner(System.in);
System.out.print(count+" "); System.out.print("Enter Integer:");
count++; int num = sc.nextInt();
} int temp = num, Sum = 0;
} while(temp>0){
} Sum = Sum*10 + temp%10;
temp /= 10;
Output: }
101 102 103 104 105 106 107 108 109
if(num==Sum) System.out.print(num+" is PAL");
else System.out.print(num+" is not PAL");
}
}
Output:
Enter Integer: 121
121 is PAL
PREPARED BY: C A GAJJAR, IT DEPT, DR S & S S GHANDHY COLLEGE OF ENGG & TECH, SURAT 41
do…while Loop
class doWhile{
public static void main(String args[]){
int count = 1;
do{
System.out.print(count+" ");
count++; import java.util.Scanner;
}while(count <= 10); class doWhile{
} public static void main(String args[]){
} Scanner sc = new Scanner(System.in);
int num, Sum = 0;
Output:
1 2 3 4 5 6 7 8 9 10 do{
System.out.print("Enter Integer:");
num = sc.nextInt();
Sum += num;
}while(num != -1);
System.out.print("Sum = "+(Sum+1));
}
}
PREPARED BY: C A GAJJAR, IT DEPT, DR S & S S GHANDHY COLLEGE OF ENGG & TECH, SURAT 42
for Loop
class Loop{ class Loop{
public static void main(String args[]){ public static void main(String args[]){
int i; int i;
for(i = 1; i < 5; i++){ for(i = 1; i < 5; i++); {
System.out.print(i); System.out.print(i);
} }
} }
} }
Output: 1234 Output: 5
class Loop{ class Loop{
public static void main(String args[]){ public static void main(String args[]){
int i; int i;
for(i = 1; i < 5; i=i+1/2){ for(i = 1; i < 5; i++)
System.out.print(i); System.out.print(i);
} System.out.print(i);
} }
} }
Output: 111… Output: 12345
PREPARED BY: C A GAJJAR, IT DEPT, DR S & S S GHANDHY COLLEGE OF ENGG & TECH, SURAT 43
for Loop
class Loop{ class Loop{
public static void main(String args[]){ public static void main(String args[]){
int i; int i, m;
for(i = 1; i ; i++){ for(i=1, m = 11; i<=5; i++, --m){
System.out.print(i); System.out.print(m+" ");
} }
} }
} } Output: 11 10 9 8 7
PREPARED BY: C A GAJJAR, IT DEPT, DR S & S S GHANDHY COLLEGE OF ENGG & TECH, SURAT 44
break and continue
class forLoop{ class forLoop{
public static void main(String arg[]){ public static void main(String arg[]){
int x = 1; int x;
for( ; ; ) for(x=1; x<=10 ; x++)
{ {
System.out.print(x+" "); if (x % 3 == 0)
x++; continue;
if (x > 10) break; System.out.print(x+" ");
} }
} }
} }
Output: 1 2 3 4 5 6 7 8 9 10 Output: 1 2 4 5 7 8 10
PREPARED BY: C A GAJJAR, IT DEPT, DR S & S S GHANDHY COLLEGE OF ENGG & TECH, SURAT 45
Array
An array is a collection of similar data type elements. It is an indexed
collection of fixed number of same data values. In java, there are three types
of array:
1. Single dimensional array
2. Multi dimensional array
3. Non-Rectangular array
PREPARED BY: C A GAJJAR, IT DEPT, DR S & S S GHANDHY COLLEGE OF ENGG & TECH, SURAT 46
Single Dimensional Array (1D array)
A list of items can be given one variable name using only one subscript(index)
and such a variable is called a one-dimensional array.
Syntax:
mark[0]
mark[1]
mark[2]
both are valid syntax. mark[3]
mark[4]
PREPARED BY: C A GAJJAR, IT DEPT, DR S & S S GHANDHY COLLEGE OF ENGG & TECH, SURAT 47
Single Dimensional Array (1D array)
Array can be initialized as shown above. We can initialize or modify specific
element in the array by specifying its index(subscript) within square brackets.
An array index always starts from Zero.
The index of an array can be int constant, variable of expression that yield
integers.
PREPARED BY: C A GAJJAR, IT DEPT, DR S & S S GHANDHY COLLEGE OF ENGG & TECH, SURAT 48
1D Array Example
import java.util.Scanner;
class Array1D{
public static void main(String args[]){
int sub[] = new int[4], i;
int sum = 0;
Scanner sc = new Scanner(System.in);
for(i=0; i<4; i++){
System.out.print("Enter Marks for Sub-"+(i+1)+":");
sub[i]=sc.nextInt();
sum = sum + sub[i];
}
System.out.print("Percentage = "+(sum/4.0));
}
}
Enter Marks for Sub-1:75
Enter Marks for Sub-2:60
Enter Marks for Sub-3:65
Enter Marks for Sub-4:70
Percentage = 67.5
PREPARED BY: C A GAJJAR, IT DEPT, DR S & S S GHANDHY COLLEGE OF ENGG & TECH, SURAT 49
Multi Dimensional Array (2D, 3D,… arrays)
Two dimensional array represents several rows and columns of data. For
example, marks obtained by 3 students in five subjects can be represented
by a 2D array of 3×5.
col-0 col-1 col-2 col-3 col-4
row-0 [0][0] [0][1] [0][2] [0][3] [0][4]
row-1 [1][0] [1][1] [1][2] [1][3] [1][4]
row-2 [2][0] [2][1] [2][2] [2][3] [2][4]
PREPARED BY: C A GAJJAR, IT DEPT, DR S & S S GHANDHY COLLEGE OF ENGG & TECH, SURAT 50
2D Array Example
import java.util.Scanner; Enter Rows & Columns:2 3
class Array2D{ Enter elements of
public static void main(String args[]){ Matrix:
Scanner sc = new Scanner(System.in); 1 2 3
System.out.print("Enter Rows & Columns:");
int r = sc.nextInt(); 4 5 6
int c = sc.nextInt(); The transpose of Matrix:
int arr[][] = new int[r][c], i, j; 1 4
System.out.println("Enter elements of Matrix:"); 2 5
for(i=0; i<r; i++) 3 6
for(j=0; j<c; j++)
arr[i][j]=sc.nextInt();
System.out.println("The transpose of Matrix:");
for(i=0; i<c; i++)
{
for(j=0; j<r; j++)
{
System.out.print(arr[j][i]+" ");
}
System.out.print("\n");
}
}
}
PREPARED BY: C A GAJJAR, IT DEPT, DR S & S S GHANDHY COLLEGE OF ENGG & TECH, SURAT 51
Non-Rectangular Array / Jagged Array
In non-rectangular/jagged arrays, number of rows elements are fixed, but
number of columns for each row are different. Jagged arrays are useful when
dealing with a group of arrays of different sizes.
PREPARED BY: C A GAJJAR, IT DEPT, DR S & S S GHANDHY COLLEGE OF ENGG & TECH, SURAT 52
Jagged Array Example
class JaggedArray {
public static void main(String args[]) {
int x[][] = new int[3][];
//create 3 more 1D arrays as part of x
x[0]= new int[4];
x[1]= new int[2];
x[2]= new int[3];
//store 4 elements into 1st array
x[0][0]=11; x[0][1]=12; x[0][2]=23; x[0][3]=24;
//store 2 elements into 2nd array
x[1][0]=31; x[1][1]=32;
//store 3 elements into 3rd array
x[2][0]=41; x[2][1]=52; x[2][2]=63;
for(int i=0; i<4; i++) System.out.print(x[0][i]+",");
System.out.println();
for(int i=0; i<2; i++) System.out.print(x[1][i]+",");
System.out.println();
for(int i=0; i<3; i++) System.out.print(x[2][i]+",");
}
}
PREPARED BY: C A GAJJAR, IT DEPT, DR S & S S GHANDHY COLLEGE OF ENGG & TECH, SURAT 53
for-each Loop
This loop is specially designed to handle the elements of a collection.
Collection represents a group of elements. For example, we can take an
array as a collection or any class in package can be
considered as a collection.
The reason is that an array stores a group of elements like integer
values or strings. Similarly, package classes are developed to
handle a group of objects.
The for-each lop repeatedly executes a group of statements for each
element of the collection. It executes as many times as there are
number of elements in the collection.
PREPARED BY: C A GAJJAR, IT DEPT, DR S & S S GHANDHY COLLEGE OF ENGG & TECH, SURAT 54
for-each Loop Example
class forEachLoop{ Output:
public static void main(String ar[]){ 11
23
int arr[] = {11, 23, 24, 12, 40, 32};
24
int Sum = 0; 12
for(int i : arr) 40
{ 32
System.out.println(i); Sum = 142
Sum = Sum + i;
}
System.out.print("Sum = "+Sum);
}
}
PREPARED BY: C A GAJJAR, IT DEPT, DR S & S S GHANDHY COLLEGE OF ENGG & TECH, SURAT 55