Java for DSA Part 1

·

6 min read

Introduction to Java:

  • Java is general purpose and powerful language. It is fundamentally an object oriented programming language.

  • Java is platform independent(portable), you write a program in your system and it can also run on other platform, you just have to take the byte code.

  • Java is strongly typed language, whereas python, javascript are not.

  • Java does automatic memory allocation.

  • There are many other features, keeping in mind that we are preparing for DSA we would focus more on how to write code in java.

What do computers understand?

  • computers understand 0s and 1s (binary code), writing programs in binary is tedious and error prone.

  • So we came up with high level programming languages(c,c++,java,python), which are more closer to the developer, binary code is closer to machine.

  • For running programs written in high level language we have transform them into machine code. For this we have tools like compilers, Interpreters and assemblers.

How does Java code run?

  • Before that we have talk about JDK (Java Development Kit), which helps us write and run java Programs. It has different tools and libraries like JRE, JVM etc

  • JRE is java runtime environment (provide environment to run) which consists JVM (Java virtual Machine- Executes bytecode), this thing makes java platform independent and special.

  • Now how does it run: will illustrate using the picture:

Source code goes through the compiler and we get a .class file which is bytecode. And to execute this JVM produces native code(which is specific to machine/platform).

~java FileName.java

Basic Syntax:

public class Main
{
   public static void main(String args[])
   {

   }
}

Variables:

  • Variables are names for memory locations, where we store data. Using variables we can access, retrieve, and modify stored data.
dataType variableName = value;

or

you can declare variable and assign value afterwards.

dataType variableName;
variableName = value;

Data Types:

  • Data types can be divided into two types: Primitive and non primitive.

  • Primitive types are: byte, short, char, boolean, int, long, float, double

  • Non primitive: String, class, Array, object, Interface

Size of data types:

  • 1 byte is equal to 8 bits, a bit can have one of either states 0 or 1
  1. byte - 1 byte (-128 to 127)

  2. short - 2 bytes

  3. char - 2 bytes

  4. boolean - 1 byte (true or false)

  5. int - 4 bytes

  6. long - 8 bytes

  7. float - 4 bytes

  8. double - 8 bytes

Output:

  • Output in java to the console can be done with the following functions.
System.out.println("Hello there!");

or

System.out.print("Hello there!");

println() -> goes to a new line

print() -> does not go to a new line

\n - can also be used for printing a new line

Input in Java:

  • To take input in java we have different methods, here we will talk about Scanner class.

Step 1: We have to import Scanner class (this should be done at the top of the program)

import java.util.Scanner;

or

import java.util.*;

imports all the utility package.

Step 2: Now we have to create instance/ object of Scanner class

Scanner in = new Scanner(System.in);
  • We have to note something, there are different functions for different data types through which we can take input.
  1. next() - this is for string and it only (captures) takes input till the first space.

  2. nextLine() - this is for string and it take (captures) complete line

  3. nextInt() - this is for int data type.

  4. nextFloat() - this is for float data type.

  5. nextBoolean() - this is for boolean values.

  6. nextDouble() - this is for double values

  7. nextLong() - this is for long values.

  8. nextByte() - this is for byte values.

  9. nextShort() - this is for short values.

  10. next.charAt(0) - this is for char values, 0 inside () tells about the place, 0 is the starting point of the text.

Type Conversion:

  • Type conversion, by that I mean a data type converting to another data type happens in two cases:

    1. When type is compatible eg: int <--> float (but float value changing into int will cause truncation of decimal values)

    2. When destination type is bigger than source type (destination type > source type) byte -> short -> int -> float -> long -> double

Type Casting:

  • By type casting, I mean explicitly converting a dataType.
float val = 23.456f;
int num = (int)val;

Operators:

  • Operators are the symbols that tell the compiler to perform some operation.

Type of operators:

  1. Arithmetic operators (binary, unary and ternary)

  2. Relational operators

  3. Logical operators

  4. Bitwise operators (Bit manipulation)

  5. Assignment operators

Arithmetic Operators:

  • These are used to perform arithmetic operations.

Binary:

+ : used for addition
- : used for subtraction
* : used for multiplication
/ : used for division
% : used to get remainder (modulo)

Unary:

++ : Increment by 1 (a = a+1)
-- : decrement by 1 (a = a-1)
  • There are two types in each unary operators: 1.Pre increment (++a) -> First Changes the value and second uses the value 2.Post increment (a++) -> First uses the value and second changes the value Same for decrement also. Pre decrement (--a) and post decrement(a--)

Relational Operators:

== : Checks equality
!= : Not equal to (check inequality)
>  : Greater than
<  : Less than
>= : greater than equal to
<= : Less than equal to

Logical Operators:

&& : logical AND
|| : logical OR
!  : logical Not (Negation)

Assignment Operators:

= : assigns value of right side operand to left operand
+= : a = a+b -> a+=b
-= : a = a-b -> a-=b
*= : a = a*b -> a*=b
/= : a = a/b -> a/=b
%= : a = a%b -> a%=b

Conditional Statements:

  • Conditional statements get executed when the condition give is true. The conditional statements are:

  • if, else

  • else if

  • ternary operator

  • switch

Syntax of if else:
if(condition){
   // code goes here --> this code runs when the condition is true
} else{
// code --> this code runs when the condition is false
}

eg:
int age = 19
if (age>18){
 System.out.println("U are good to drive");
//this code runs because condition is true
}else{
System.out.println("U should not drive now");
//this code does not run because condition is not false
}
Syntax of else if:
if (condition1){
//code
}else if(condition2){
//code
}else{
//code}
Syntax for ternary operator:
variable = condition ? statement1: statement2;

eg:
boolean largeNum = (145>89) ? true:false;
Syntax of switch:
switch(variable){
case 1: //code
       break;
case 2: //code
       break;
default : //code
         break;

Loops:

  • Loops are used for repetitive tasks. The loops are:

    1. while

    2. for

    3. do while

Syntax of while loop:

initialisation;
while(condition){
//code
updation; //used to avoid looping infinite times
}

eg:
//print 1 to 10
int count = 1;
while(count<=10){
System.out.println(count);
count++;
}
Syntax of For:

for(initialisation; condition; updation){
//code
}

eg:
//print 1 to 10

for(int i =1; i<=10; i++){
System.out.println(i);
}

The only way to learn a language is to code it.

Please forgive me for any errors.