Notes New
Notes New
Basics
Basic syntax and functions from the Java programming language.
Boilerplate
class HelloWorld
{
public static void main(String args[])
{
System.out.println("Hello World");
}
}
Copy
Showing Output
Taking Input
The eight primitives defined in Java are int, byte, short, long, float, double,
boolean, and char those aren't considered objects and represent raw
values.
byte
long
long is another primitive data type related to integers. long takes up 64 bits
of memory.
class HelloWorld
{
public static void main(String args[])
{
long var=900.0;
System.out.println(age);
}
}
Copy
float
We represent basic fractional numbers in Java using the float type. This is a
single-precision decimal number. Which means if we get past six decimal
points, this number becomes less precise and more of an estimate.
class HelloWorld
{
public static void main(String args[])
{
float price=100.05;
System.out.println(price);
}
}
Copy
char
int
short
If we want to save memory and byte is too small, we can use short.
class HelloWorld
{
public static void main(String args[])
{
short var2=5666;
System.out.println(var2);
}
}
Copy
Comments
A comment is the code that is not executed by the compiler, and the
programmer uses it to keep track of the code.
Multi-line comment
/* It's a
multi-line
comment
*/
Copy
Constants
Constants are like a variable, except that their value never changes during
program execution.
public class Declaration {
Arithmetic Expressions
Addition
Subtraction
Division
Modulo Remainder
Addition assignment
Subtraction assignment
Multiplication assignment
Modulus assignment
Escape Sequences
Tab
Copy
Backslash
It adds a backslash
public class HelloWorld
{
public static void main(String args[])
{
System.out.print("\\");
}
}
Copy
Single quote
Copy
Question mark
Copy
Carriage return
Copy
Double quote
Copy
Type Casting
}
Copy
}
Copy
if Statement
if (condition) {
// block of code to be executed if the condition is true
}
Copy
if-else Statement
if (condition) {
// If condition is True then this block will get executed
} else {
// If condition is False then this block will get executed
}
Copy
if else-if Statement
if (condition1) {
// Codes
}
else if(condition2) {
// Codes
}
else if (condition3) {
// Codes
}
else {
// Codes
}
Copy
Ternary Operator
Syntax
Example
Switch Statements
Copy
Iterative Statements
while Loop
for Loop
}
Copy
for-each Loop
do-while Loop
It is an exit controlled loop. It is very similar to the while loop with one
difference, i.e., the body of the do-while loop is executed at least once even
if the condition is False
public class HelloWorld
{
public static void main(String args[])
{
int i=1;
do
{
System.out.println(i);
i++;
}while(i<=100);
}
}
Copy
Break statement
}
Copy
Continue statement
continue keyword skips the rest of the current iteration of the loop and
returns to the starting point of the loop
class HelloWorld
{
public static void main(String args[])
{
int i;
for(i=1;i<100;i++)
{
System.out.println(i);
if(i==50)
continue;
}
}
}
Copy
Arrays
Declaring an array
Declaration of an array
public class HelloWorld
{
public static void main(String args[])
{
String [] var_name;
}
}
Copy
Defining an array
Defining an array
public class HelloWorld
{
public static void main(String args[])
{
String [] var_name={"harry","rohan","aakash"}
}
}
Copy
Accessing an array
Copy
Changing an element
Array length
Copy
Copy
Multi-dimensional Arrays
Methods
Methods are used to divide an extensive program into smaller pieces. It can
be called multiple times to provide reusability to the program.
Declaration
Declaration of a method
returnType methodName(parameters) {
//statements
}
Copy
Calling a method
Calling a method
methodName(arguments);
Copy
Example
Method Overloading
Method overloading means having multiple methods with the same name,
but different parameters.
class Calculate
{
void sum (int x, int y)
{
System.out.println("Sum is: "+(a+b)) ;
}
void sum (float x, float y)
{
System.out.println("Sum is: "+(a+b));
}
public static void main (String[] args)
{
Calculate calc = new Calculate();
calc.sum (5,4); //sum(int x, int y) is method is called.
calc.sum (1.2f, 5.6f); //sum(float x, float y) is called.
}
}
Copy
Recursion
Strings
String Length
toLowerCase()
indexOf()
concat()
Copy
Math Class
min() method
sqrt() method
random() method
Object-Oriented Programming
class
Copy
object of class
Encapsulation
// Getter
public String getName()
{
return name;
}
// Setter
public void setName(String newName)
{
this.name = newName;
}
}
Copy
Inheritance
Inheritance can be defined as the process where one class acquires the
properties of another. With the use of inheritance the information is made
manageable in a hierarchical order.
class Subclass-name extends Superclass-name
{
//methods and fields
}
Copy
Example
class Employee
{
float salary=40000;
}
class Programmer extends Employee
{
int bonus=10000;
public static void main(String args[])
{
Programmer p=new Programmer();
System.out.println("Programmer salary is:"+p.salary);
System.out.println("Bonus of Programmer is:"+p.bonus);
}
}
Copy
Polymorphism
// method 2
public void add(int a, int b, int c)
{
System.out.println(a + b + c);
}
// method 3
public void add(String a, String b)
{
System.out.println(a + " + " + b);
}
}
// My main class
class MyMainClass
{
public static void main(String[] args)
{
Adder adder = new Adder(); // create a Adder object
adder.add(5, 4); // invoke method 1
adder.add(5, 4, 3); // invoke method 2
adder.add("5", "4"); // invoke method 3
}
}
Copy
File Operations
File handling refers to reading or writing data from files. Java provides some
functions that allow us to manipulate data in the files.
Assume that we have created the file “D:\\Example.txt”
canRead method
createNewFile method
try {
canWrite method
exists method
// Main class
public class FileOperations {
delete method
It deletes a file
import java.io.*;
getName method
length Method
list Method
System.out.println("Files are:");
mkdir method
close method
try {
FileInputStream input= new FileInputStream(file);
int character;
// read character by character by default
// read() function return int between
// 0 and 255.
input.close();
System.out.println("File is Closed");
System.out.println(
"Now we will again try to read");
while ((character = input.read()) != -1) {
System.out.print((char)character);
}
}
catch (Exception e) {
System.out.println(
"File is closed. Cannot be read");
e.printStackTrace();
}
}
}
Copy
To write something in the file
Exception Handling
try-catch block
try statement allow you to define a block of code to be tested for errors.
catch block is used to handle the exception.
try {
// Statements
}
catch(Exception e) {
// Statements
}
Copy
Example
class Main {
public static void main(String[] args) {
try {
int divideByZero = 5 / 0;
System.out.println("Rest of code in try block");
}
catch (ArithmeticException e) {
System.out.println("ArithmeticException => " +
e.getMessage());
}
}
}
Copy
finally block
Example
class Main {
public static void main(String[] args) {
try {
int divideByZero = 5 / 0;
}
finally {
System.out.println("Finally block is always executed");
}
}
}