Java
Java
Introduction:
Java Installation:
Java Syntax:
MyProgram.java (filename)
Java Comments:
Java Variables:
int a=20;
String name=“kiran”;
int a=1100;
System.out.println(a);
String name=“varun”;
System.out.println(“Hello”+name);
int x=5;
int y=10;
int z=15;
System.out.println(x+y+z);
Or
int x=5, y=10, z=15;
System.out.println(x+y+z);
and
int m=60;
Primitive Data Types - byte, short, int, long, float, double, boolean, char.
1) Byte (1 byte)
2) Short (2 bytes)
3) Int (4 bytes)
4) Long (8 bytes)
5) Float (4 bytes)
6) Double (8 bytes)
7) Boolean (1 bit)
8) Char (2 bytes)
1 byte=8 bits
Numbers:
For float we use 0.05f but output should be 0.05. and for double 19.99d output
is 19.99.
Boolean Types - declared with boolean keyword and can only takes the
values True or False.
Java Characters - char data type is used to store a single character like a or c
surrounded by single quotes.
Type casting means converting one data type to another data type.
byte -> short -> char -> int -> long -> float -> double
Java Operators:
Arithmetic Operators:
Addition (+)
Subtraction(-)
Multiplication(*)
Division(/)
Modulus(%)
Increment(++)
Decrement(--)
Assignment Operators:
=, +=, -=, *=, /=, %=, &=, |=, ^=, >>=, <<=
Comparison Operators:
Logical Operators:
Java Strings:
String txt=“nfheggfvnjkhngbjhg”;
System.out.println(txt.length());
Output - 18
String Concatenation:
String FName=“John”;
String LName=“Doee”;
System.out.println(FName+“ ”+LName); // John Doee
-> Java uses + operator for both addition and concatenation, numbers are
added, strings are concatenated.
int x=10;
int y=15;
int z=x+y; // z=25
String x= “10”;
String y= “15”;
String z=x+y; // 1015
int x=10;
String y= “15”;
String z=x+y; // z=1015
Java Math:
Math.max(x,y):
Math.max(5,10); //10
Math.min(x,y):
Math.min(5,10); //5
Math.sqrt(x):
Math.sqrt(64); //8
Math.abs(x):
Math.abs(-4.7); //4.7
Random Numbers:
Java Booleans:
-> Yes/No
-> True/False
-> On/Off
int x=10;
int y=9;
System.out.println(x>y); // True
Java If … Else:
The IF Statement -
Syntax:
if (condition) {
// block of code to be executed if the condition is true
}
if (condition) {
// block of code to be executed if the condition is true
}
else {
// block of code to be executed if the condition is false
}
Use the else if statement to specify a new condition if the first condition is
false.
if (condition1) {
// block of code to be executed if condition1 is true
}
else if (condition2) {
// block of code to be executed if the condition1 is false and condition2 is true
}
else {
// block of code to be executed if the condition1 is false and condition2 is
false
}
Java Switch:
Use the switch statement to select one of many code blocks to be executed.
switch(expression) {
case x:
// code block
break;
case y:
// code block
break;
default:
// code block}
int day = 4;
switch (day) {
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;
case 7:
System.out.println("Sunday");
break;
}
// Outputs "Thursday" (day 4)
The while loop loops through a block of code as long as a specified condition
is true.
While(condition) {
//code
}
Do While Loop-
The do/while loop is a variant of the while loop. This loop will execute the
code block once, before checking if the condition is true, then it will repeat the
loop as long as the condition is true.
do{
//code
}
While(condition);
When you know exactly how many times you want to loop through a block of
code, use the for loop instead of a while loop.
-> The break statement can also be used to jump out of a loop.
-> The continue statement breaks one iteration (in the loop), if a specified
condition occurs, and continues with the next iteration in the loop.
Java Arrays:
Multidimensional arrays -
Java Methods:
-> Methods are used to perform certain actions, and they are also known as
functions.
Create A method:
-> A Method must be declared within a class, it is defined with the name of the
method, followed by parentheses().
//code
System.out.println(“nfjhejv”);
myMethod();
Method Overloading -
Multiple Methods can have the same name with different parameters.
int myMethod(int x)
float myMethod(float x)
double myMethod(double x, double y)
Java Scope -
In Java, variables are only accessible inside the region they are created. This
is called scope.
int x = 100;
Java Recursion -
// output - 55
Java Classes:
Java OOP-
Everything in Java is associated with classes and objects, along with its
attributes and methods. For example: in real life, a car is an object. The car
has attributes, such as weight and color, and methods, such as drive and
brake.
Create a class -
Int x=5;
In Java, an object is created from a class. We have already created the class
named Main, so now we can use this to create objects.
To create an object of Main, specify the class name, followed by the object
name, and use the keyword new.
Int x=5;
Int y =10;
-> Accessing the attributes by creating an object of the class and by using the
dot syntax(.)
System.out.println(“Hello”);
myMethod();
}
}
Java Constructors-
Java Modifiers -
-> Access Modifiers are public and default, for classes you can use either
public or default.
-> For attributes, methods and constructors you can use public, private,
default, protected.
-> Non Access Modifiers are final and abstract, for classes.
Final-
If you don't want the ability to override existing attribute values, declare
attributes as final.
Java Encapsulation-
// Getter
public String getName() {
return name;
}
// Setter
public void setName(String newName) {
this.name = newName;
}}
import java.util.Scanner;
import java.util.*;
User-defined packages,
To create your own package, you need to understand that Java uses a file
system directory to store them. Just like folders on your computer.
package mypack;
class MyPackageClass {
public static void main(String[ ] args) {
System.out.println("This is my package!");
}
}
Java Inheritance-
class Vehicle {
protected String brand = "Ford"; // Vehicle attribute
public void honk() { // Vehicle method
System.out.println("Tuut, tuut!");
}}
class Car extends Vehicle {
private String modelName = "Mustang"; // Car attribute
public static void main(String[] args) {
// Create a myCar object
Car myCar = new Car();
// Call the honk() method (from the Vehicle class) on the myCar object
myCar.honk();
// Display the value of the brand attribute (from the Vehicle class) and the
value of the modelName from the Car class
System.out.println(myCar.brand + " " + myCar.modelName);
}}
Java Polymorphism-
class Animal {
public void animalSound() {
System.out.println("The animal makes a sound");
}}
class Pig extends Animal {
public void animalSound() {
System.out.println("The pig says: wee wee");
}}
class Dog extends Animal {
public void animalSound() {
System.out.println("The dog says: bow wow");
}}
class OuterClass {
int x = 10;
class InnerClass {
int y = 5;
}}
public class Main {
public static void main(String[] args) {
OuterClass myOuter = new OuterClass();
OuterClass.InnerClass myInner = myOuter.new InnerClass();
System.out.println(myInner.y + myOuter.x);
}}
// Outputs 15 (5 + 10)
Java Abstraction-
Data abstraction is the process of hiding certain details and showing only
essential information to the user.
Interfaces-
// interface
interface Animal {
public void animalSound(); // interface method (does not have a body)
public void run(); // interface method (does not have a body)
Java Enums:
To create an enum, use the enum keyword (instead of class or interface), and
separate the constants with a comma. Note that they should be in uppercase
letters:
enum Level{
LOW,
MEDIUM,
HIGH
}
Also,
The Scanner class is used to get user input, and it is found in the java.util
package.
Date
Java ArrayList:
The difference between a built-in array and an ArrayList in Java, is that the
size of an array cannot be modified (if you want to add or remove elements
to/from an array, you have to create a new one). While elements can be
added and removed from an ArrayList whenever you want.
Java LinkedList:
Java HashMap:
A HashMap however, store items in "key/value" pairs, and you can access
them by an index of another type (e.g. a String).
Java HashSet:
Java Iterator:
import java.util.ArrayList;
import java.util.Iterator;
public class Main {
public static void main(String[] args) {
// Make a collection
ArrayList<String> cars = new ArrayList<String>();
cars.add("Volvo");
cars.add("BMW");
cars.add("Ford");
cars.add("Mazda");
Wrapper class provide a way to use primitive data types(int, boolean, etc) as
objects.
Primitive Data Type Wrapper Class
byte Byte
short Short
int Integer
long Long
float Float
double Double
boolean Boolean
char Character
In Java, an exception is an event that disrupts the normal flow of the program.
It is an object which is thrown at runtime.
2) Unchecked Exception
3) Error
-> try (The "try" keyword is used to specify a block where we should place
exception code. The try block must be followed by either catch or finally. It
means, we can't use try block alone.)
-> catch (The "catch" block is used to handle the exception. It must be
preceded by try block which means we can't use catch block alone. It can be
followed by finally block later.)
-> finally (The "finally" block is used to execute the important code of the
program. It is executed whether an exception is handled or not.)
try{
//Block of code to try
}
catch(Exception e) {
//Block of code to handle errors
}
Example:
Finally,
Throw,
Import the java.util.regex package to work with regex this package includes
Pattern class, Matcher class, PatternSyntaxException class.
MultiTasking -
Types,
Creating a thread -
1)
public class Main extends Thread{
}
2)
public class Main implements Runnable{
public void run(){
System.out.println(“This code is running in a thread”);
}
}
Java Lambda:
Syntax,
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
ArrayList<Integer> numbers = new ArrayList<Integer>();
numbers.add(5);
numbers.add(9);
numbers.add(8);
numbers.add(1);
numbers.forEach( (n) -> { System.out.println(n); } );
}
}
Java Files:
The File class from the java.io package allows us to work with files.
Create a file,
Write to a file,
Read a file,
Delete a File,