Javanotes
Javanotes
Sample Code
Functions
A function is a block of code which takes some input, performs some operations and returns some
output.
Class
A class is a group of objects which have common properties. A class can have some properties and
functions (called methods).
package com.apnacollege;
System.out.println("Hello World");
}
}
Variables
package com.apnacollege;
// Variables
Data Types
Data types are declarations for variables. This determines the type and size of data associated with
variables which is essential to know since different data types occupy different sizes of memory.
There are 2 types of Data Types :
Data Type
Meaning
Size
(in Bytes)
Range
byte
-128 to 127
short
-32K to 32K
int
Integer numbers
-2B to 2B
long
(larger values)
-9,223,372,036,854,775,808
to 9,223,372,036,854,775,807
float
Floating-point
double
Double Floating-point
char
Character
a, b, c ..
A, B, C ..
@, #, $ ..
bool
Boolean
True, false
Non-Primitive Data Types
These are of variable size & are usually declared with a ‘new’ keyword.
Eg : String, Arrays
marks[0] = 97;
marks[1] = 98;
marks[2] = 95;
String Class
Strings are immutable non-primitive data types in Java. Once a string is created it’s value cannot be
changed i.e. if we wish to alter its value then a new string with a new value has to be created.
This class in java has various important methods that can be used for Java objects. These include:
Concatenation
System.out.println(sentence);
CharAt
String name = new String("Aman");
System.out.println(name.charAt(0));
Length
System.out.println(name.length());
Replace
System.out.println(name.replace('a', 'b'));
Substring
System.out.println(name.substring(0, 4));
Arrays
Arrays in Java are like a list of elements of the same type i.e. a list of integers, a list of booleans etc.
marks[0] = 97;
marks[1] = 98;
marks[2] = 95;
Casting in java is the assigning values of one type to another. The types being considered here are
compatible i.e. we can only assign values of a number type to another type storing numbers (vice-versa
is not allowed i.e. floating values cannot be assigned to boolean data types).
Implicit casting
This casting is done by java implicitly i.e. on its own. It is assigning smaller values to larger data types.
Explicit casting
This casting is done by the programmer. It is assigning larger values to smaller data types.
Constants
A constant is a variable in Java which has a fixed value i.e. it cannot be assigned a different value once
assigned.
package com.apnacollege;
// Constants
Operators
Arithmetic Operators
Arithmetic operators are just like operators we used in Math. These include:
‘+’ Add
int a = 30;
int b = 40;
int sum = a + b;
‘-’ Subtract
int a = 30;
int b = 40;
int diff = a - b;
‘*’ Multiply
int a = 30;
int b = 40;
int mul = a * b;
‘/’ Divide
int a = 30;
int b = 40;
int div = a / b;
int a = 30;
int b = 40;
int modulo = a % b;
Unary Operators
int a = 30;
a++;
a--;
Post-incrementer : It stores the current value of the operand temporarily and only after that statement
is completed, the value of the operand is incremented.
Post-decrementer : It stores the current value of the operand temporarily and only after that statement
is completed, the value of the operand is decremented.
Assignment Operators
Operator
Operation
Example
+=
Adds right operand to the left operand and assigns the result to left operand.
-=
Subtracts right operand from the left operand and assigns the result to left operand.
*=
Multiplies the right operand with the left operand and assigns the result to the left operand.
/=
Divides left operand with the right operand and assigns the result to left operand.
Operator
Operation
Example
==
A==B is not
true
!=
A!=B is true
>
A>B is not
true
<
A<B is true
>=
Gives true if left operand is more than right operand or equal to it
A>=B is not
true
<=
A<=B is true
Logical Operators
Operator
Operation
Example
&&
(A && B) is
false
||
OR operator. Gives true if atleast one of the two operands are non-zero.
(A || B) is
true
!
!A is true
Math class
Math is an important class in Java that is extensively used and has a lot of interesting functions.
Max
int a = 10;
int b = 20;
Math.max(a, b);
Min
int a = 10;
int b = 20;
Math.min(a,b);
Random
Taking Input
We take input using the Scanner class and input various types of data using it.
Example :
int n = sc.nextInt();
float a = sc.nextFloat();
The if block is used to specify the code to be executed if the condition specified in if is true, the else
block is executed otherwise.
System.out.println("This is an adult");
} else {
Switch case statements are a substitute for long if statements that compare a
switch(n) {
case 1 :
System.out.println("Monday");
break;
case 2 :
System.out.println("Tuesday");
break;
case 3 :
System.out.println("Wednesday");
break;
case 4 :
System.out.println("Thursday");
break;
case 5:
System.out.println("Friday");
break;
case 6 :
System.out.println("Saturday");
break;
default :
System.out.println("Sunday");
}
Break & Continue
Jumps in loops are used to control the flow of loops. There are two statements used to implement jump
in loops - Continue and Break. These statements are used when we need to change the flow of the loop
when some specified condition is met.
Continue statement is used to skip to the next iteration of that loop. This means that it stops one
iteration of the loop. All the statements present after the continue statement in that loop are not
executed.
int i;
if (i%3==0) {
continue;
System.out.println(i);
In this for loop, whenever i is a number divisible by 3, it will not be printed as the loop will skip to the
next iteration due to the continue statement. Hence, all the numbers except those which are divisible by
3 will be printed.
Break statement is used to terminate the current loop. As soon as the break statement is encountered in
a loop, all further iterations of the loop are stopped and control is shifted to the first statement after the
end of loop.
int i;
if (i == 11) {
break;
System.out.println(i);
In this loop, when i becomes equal to 11, the for loop terminates due to break statement, Hence, the
program will print numbers from 1 to 10 only.
Loops
A loop is used for executing a block of statements repeatedly until a particular condition is satisfied. A
loop consists of an initialization statement, a test condition and an increment statement.
For Loop
// body of-loop
System.out.println(i);
While Loop
while(condition) {
// body of the loop
int i = 0;
while(i<=20) {
System.out.println(i);
i++;
Do-While Loop
do {
// body of loop;
while (condition);
int i = 0;
do {
System.out.println(i);
i++;
} while(i<=20);
Exception Handling in Java is a mechanism to handle the runtime errors so that normal flow of the
application can be maintained.
It is done using 2 keywords - ‘try’ and ‘catch’.
Additional keywords like finally, throw and throws can also be used if we dive deep into this concept.
try {
System.out.println(marks[4]);
System.out.println("An exception for caught while accessing an index the 'marks' array");
System.out.println("We tried to print marks & an exception must have occurred with index >=3");
Methods/Functions
If some functionality is performed at multiple places in software, then rather than writing the same
code, again and again, we create a function and call it everywhere. This helps reduce code redundancy.
Functions make maintenance of code easy as we have to change at one place if we make future changes
to the functionality.
return-type
The return type of a function is the data type of the variable that that function returns.
For eg- If we write a function that adds 2 integers and returns their sum then the return type of this
function will be ‘int’ as we will return a sum that is an integer value.
When a function does not return any value, in that case the return type of the function is ‘void’.
function_name
Parameters
A function can take some parameters as inputs. These parameters are specified along with their data
types.
For eg- if we are writing a function to add 2 integers, the parameters would be passed like –
main function
The main function is a special function as the computer starts running the code from the beginning of
the main function. Main function serves as the entry point for the program.
Example :
package com.apnacollege;
System.out.println(sum);
int a = 10;
int b = 20;
Mini-Project
Let’s create a project where we are trying to ask the user to guess a randomly generated number.
If the user guesses a number that is greater, we print “The number is too large”.
If the user guesses a number that is smaller, we print “The number is too small”.
If the user is able to correctly guess the number, then we print “Correct Number!”.
At the end we will print the number that was generated by our Math library.
package com.apnacollege;
import java.util.Scanner;
//MINI PROJECT
int userNumber = 0;
do {
userNumber = sc.nextInt();
if(userNumber == myNumber) {
break;
else {
System.out.println("your number is too small");
System.out.println(myNumber);