Java Basics
Java Basics
Class
Variables
Data Types -
(i) Primitive Data Types
(ii) Non Primitive Data types
Constants
Loops and its types
Nested Loops
Patterns in Java
Functions / Methods
Time Complexity and Space Complexity
Arrays
2D Arrays
String
String Builder
Bit Maniulation
Sorting
Java Basics
# Functions :-
# Class:-
# Variables :-
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.
Long 2’s 8 -
complement 9,223,372,036,854,775,
integer 808
(larger values) to
9,223,372,036,854,775,
807
char Character 2 a, b, c ..
A, B, C ..
@, #, $ ..
These are of variable size & are usually declared with a ‘new’ keyword.
Eg : String, Arrays
# Constants :
# Inputs in java :
Ques. Take two variables a and b and print their sum .
Soln ;
# Loops :
1. for Loop -
2. while loop -
3. Do while loop –
It works for at least one time even if the condition is false.
Que. Print sum of First n natural numbers.
Que. Make a menu driven program. The user can enter 2 numbers, either
1 or 0.
If the user enters 1 then keep taking input from the user for a student’s
marks(out of 100).
# Patterns in Java :
1.Solid Rectangle -
Outer Loop for Rows ; Inner Loop for Columns
2. Hollow Rectangle -
3. Half Pyramid :
4. Inverted half pyramid
9. 0-1 Triangle -
10. Butterfly pattern -
HW
HW
HW
HW
HW ( Doubt )
1. return-type
The return type of a function is the data type of the variable 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’.
2. function_name
3.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 –
int add (int num1, int num2)
4. 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.
0 1 1 2 3 5 8 13 21 .....
Types of notations
# Space Complexity -
# Arrays in Java :-
Arrays in Java are like a list of elements of the same type i.e. a list of
integers, a list of booleans etc.
Qs. Take an array of names as input from the user and print them
on the screen.
import java.util.*;
// Output
for(int i = 0 ; i<names.length ; i++){
System.out.println("Name " +(i+1) + " is :" +names[i] + "
");
}
}
}
if(numbers[i]< min){
min = numbers[i];
}
if(numbers[i]>max) {
max = numbers[i];
}
}
if(isAscending) {
System.out.println("The array is sorted in ascending
order");
} else {
System.out.println("The array is not sorted in ascending
order");
}
}
}
# 2D arrays in Java :-
It is similar to 2D matrices that we studied in 11th and 12th class.
//input
//rows
for(int i=0; i<rows; i++) {
//columns
for(int j=0; j<cols; j++) {
numbers[i][j] = sc.nextInt();
}
}
for(int i=0; i<rows; i++) {
for(int j=0; j<cols; j++) {
System.out.print(numbers[i][j]+" ");
}
System.out.println();
}
}
}
}
}
Qs. Print the spiral order matrix as output for a given matrix of numbers.
import java.util.*;
The while loop is essential to ensure that you only traverse the valid parts
of the matrix and stop when you've processed all elements in the matrix.
In summary, the while loop controls the overall flow and ensures that you
correctly navigate through the matrix without stepping outside its bounds.
Qs. For a given matrix of N x M, print its transpose.
import java.util.*;
public class TwoDMatrix {
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int m = sc.nextInt();
//Output
System.out.println("The transpose of the matrix is : ");
for( int j = 0 ; j<m ; j++){
for(int i = 0 ; i<n ; i++){
System.out.print(matrix[i][j] + " ");
}
System.out.println();
}
}
}
# Strings :-
It's one of the most commonly used data types, and it represents a
sequence of characters like words, sentences, or any text.
Declaration
String name = "Tony";
Taking Input
Scanner sc = new Scanner(System.in);
String name = sc.next();
Compare 2 strings
import java.util.*;
if(name1.compareTo(name2)) {
System.out.println("They are the same string");
} else {
System.out.println("They are different strings");
}
if(name1.equals(name2)) {
System.out.println("They are the same string");
} else {
System.out.println("They are different strings");
}
//DO NOT USE == to check for string equality
//Gives correct answer here
if(name1 == name2) {
System.out.println("They are the same string");
} else {
System.out.println("They are different strings");
}
//Gives incorrect answer here
if(new String("Tony") == new String("Tony")) {
System.out.println("They are the same string");
} else {
System.out.println("They are different strings");
}
}
}
Substring
The substring of a string is a subpart of it.
public class Strings {
public static void main(String args[]) {
String name = "TonyStark";
// .substring (begin index , ending index)
System.out.println(name.substring(0, 4));
}
}
}
}
}
}
Qs.Take an array of Strings input from the user & find the cumulative
(combined) length of all those strings.
import java.util.*;
System.out.println(totlength);
}
}
# String Builder :
Declaration
StringBuilder sb = new StringBuilder("Apna College");
System.out.println(sb);
//delete char
sb.delete(0, 1);
System.out.println(sb);
}
}
Append a char :
Append means to add something at the end.
import java.util.*;
import java.util.*;
System.out.println(sb.length());
}
}
import java.util.*;
sb.setCharAt(front, backChar);
sb.setCharAt(back, frontChar);
}
System.out.println(sb);
}
}
Qs. Input a string from the user. Create a new string called ‘result’ in
which you will replace the letter ‘e’ in the original string with letter ‘i’.
Example :
Code 1 (Replace):
import java.util.*;
import java.util.*;
System.out.println(result);
}
}
Code 3 (StringBuilder):
StringBuilder is mutable, meaning you can change the content of the
StringBuilder object without creating a new object each time. When
you replace a character, it modifies the existing object in place.
Slightly more complex to understand for beginners.
For efficiency and performance
import java.util.*;
public class Strings {
public static void main(String [] args){
Scanner sc = new Scanner(System.in);
StringBuilder sb = new StringBuilder(sc.next());
Qs. Input an email from the user. You have to create a username from the
email by deleting the part that comes after ‘@’. Display that username to
the user.
Example :
import java.util.*;
System.out.println(userName);
}
}
import java.util.*;
Code 3 (StringBuilder):
Efficient because StringBuilder is mutable, and the delete method
directly alters the string without creating a new one. The loop
breaks as soon as the '@' is found, minimizing unnecessary
iterations.
import java.util.*;
public class Strings {
public static void main(String [] args){
Scanner sc = new Scanner (System.in);
StringBuilder sb = new StringBuilder(sc.next());
}
}
Bit Manipulation :
1. Get Bit
Bit Mask = 1<<i
Operation : AND
import java.util.*;
if((bitMask & n) == 0) {
System.out.println("bit was zero");
} else {
System.out.println("bit was one");
}
}
}
2. Set Bit
Bit Mask = 1<<i
Operation : OR
import java.util.*;
3. Clear Bit
Bit Mask = 1<<i
Operation : AND with NOT BM
import java.util.*;
public class Bits {
public static void main(String args[]) {
int n = 5; //0101
int pos = 2;
int bitMask = 1<<pos;
int newBitMask = ~(bitMask);
int newNumber = newBitMask & n;
System.out.println(newNumber);
}
}
4. Update Bit
For 0 ( Clear )
Bit Mask = 1<<i
Operation : AND with NOT BM
For 1 ( Set )
Bit mask = 1<<i
Operation = OR
import java.util.*;
}
}
import java.util.*;
public class Bits {
public static void main(String [] args){
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int count = 0;
for(int i = 0 ; i<n ; i++){
int bitMask = 1<<i;
int oper = n & bitMask;
if(oper!=0){
count = count + 1;
}
}
if(count==1){
System.out.println("The Number is a power of 2");
} else {
System.out.println("The number is not a power of 2");
}
}
}
Logic – The numbers which are a power of 2 only have one “1” .
Hence using
(n-1) if the number is power of 2 , all the digits will be flipped and
the binary AND of n with n-1 will result in zero .
import java.util.*;
public class Bits {
public static void main(String [] args){
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
if(n<=0){
System.out.println("The Number is not a power of 2");
} else if ((n & n -1) == 0 ){
System.out.println("The Number is a power of 2 ");
} else {
System.out.println("The Number is not a power of 2");
}
}
}
import java.util.*;
public class Bits {
public static void main(String [] args){
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int pos = sc.nextInt();
int bitMask = 1<<pos;
import java.util.*;
public class Bits {
public static void main(String [] args){
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int count = 0 ;
int bitMask = 1;
while ( n > 0){
if((n & bitMask) !=0){
count++;
}
n = n>>1;
}
System.out.println(count);
}
}
import java.util.*;
public class Bits {
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int num1 = sc.nextInt();
// System.out.print(binary.reverse());
}
}
Binary to Decimal
import java.util.*;
public class Bits {
public static void main(String[] args, char c){
Scanner sc = new Scanner(System.in);
String binary = sc.nextLine();
int decimal = 0;
int length = binary.length() -1;
System.out.println(decimal);
}
}
# Sorting -
1. Bubble Sort - Idea: if arr[i] > arr[i+1] swap them. To place the
element in their respective position, we have to do the following
operation N-1 times.
Time Complexity: O(N2)
//Bubble sort
// Time Complexity = O(n^2)
printArray(arr);
}
}
2. Selection Sort -
Idea: The inner loop selects the minimum element in the unsorted
array and places the elements in increasing order.
Time complexity: O(N2)
//Selection sort
// Time Complexity = O(n^2)
//Swap
int temp = arr[smallest];
arr[smallest]= arr[i];
arr[i]= temp;
}
printArray(arr);
}
}
3. Insertion Sort -
Idea: Take an element from the unsorted array, place it in its
corresponding position in the sorted part, and shift the elements
accordingly.
//insertion sort
for(int i=1; i<arr.length; i++) {
int current = arr[i];
int j = i - 1;
while(j >= 0 && arr[j] > current) {
//Keep swapping
arr[j+1] = arr[j];
j--;
}
arr[j+1] = current;
}
printArray(arr);
}
}