Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
2 views

Java Basics

The document provides a comprehensive overview of Java programming basics, covering key concepts such as classes, variables, data types (both primitive and non-primitive), constants, loops, functions/methods, time and space complexity, arrays, and 2D arrays. It includes explanations, code examples, and various programming exercises to illustrate these concepts. Additionally, it discusses the importance of functions in reducing code redundancy and improving maintainability.

Uploaded by

vinoddahiya19
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Java Basics

The document provides a comprehensive overview of Java programming basics, covering key concepts such as classes, variables, data types (both primitive and non-primitive), constants, loops, functions/methods, time and space complexity, arrays, and 2D arrays. It includes explanations, code examples, and various programming exercises to illustrate these concepts. Additionally, it discusses the importance of functions in reducing code redundancy and improving maintainability.

Uploaded by

vinoddahiya19
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 52

Index

 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 :-

A function is a block of code which takes some input, performs some


operations and returns some output.

The functions stored inside classes are called methods.

The function we have used is called main.

# Class:-

A class is a group of objects which have common properties. A class can


have some properties and functions (called methods).

The class we have used is Main.

# Variables :-

A variable is a container (storage area) used to hold data. Each variable


should be given a unique name (identifier).
# 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 :

 Primitive Data types : to store simple values

 Non-Primitive Data types : to store complex values

Primitive Data Types :

These are the data types of fixed size.


(1 byte = 8 bits)

Data Meaning Size Range


Type
(in
Bytes
)

byte 2’s 1 -128 to 127


complement
integer

short 2’s 2 -32K to 32K


complement
integer

int Integer 4 -2B to 2B


numbers

Long 2’s 8 -
complement 9,223,372,036,854,775,
integer 808

(larger values) to
9,223,372,036,854,775,
807

float Floating-point 4 Upto 7 decimal digits


double Double 8 Upto 16 decimal digits
Floating-point

char Character 2 a, b, c ..
A, B, C ..

@, #, $ ..

bool Boolean 1 True, false

Non-Primitive Data Types :

These are of variable size & are usually declared with a ‘new’ keyword.

Eg : String, Arrays

# Constants :

A constant is a variable in Java which has a fixed value i.e. it cannot be


assigned a different value once assigned.

# Inputs in java :
Ques. Take two variables a and b and print their sum .
Soln ;

Que. Print the Area of circle.


Que . Print the table of the no input by user.
# Concept of If /else :

# Concept of else if :- If we have multiple conditions then we use else if.


# Concept of Switch :- Used where many conditions are present.

Que. Make a Calculator


Que. Ask the user to enter the number of the month & print the name of
the month.
For eg - For ‘1’ print ‘January’, ‘2’ print ‘February’ & so on.

# 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. Print table of a number input by user using loops.


Que. Print all even numbers till n .

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).

If they enter 0 then stop.

If he/ she scores :

Marks >=90 -> print “This is Good”

89 >= Marks >= 60 -> print “This is also Good”

59 >= Marks >= 0 -> print “This is Good as well”

(Because marks don’t matter but our effort does)

(Hint : use do-while loop but think & understand why)


Que. Print if a number n is prime or not (Input n from the user).

Nested Loops : Loop inside Loop.

# Patterns in Java :
1.Solid Rectangle -
Outer Loop for Rows ; Inner Loop for Columns
2. Hollow Rectangle -

3. Half Pyramid :
4. Inverted half pyramid

5.Inverted Half pyramid -


6. Half pyramid with numbers –

7. Inverted half pyramid with numbers –


8. Floyd’s Triangle -

9. 0-1 Triangle -
10. Butterfly pattern -

11. Solid Rhombus -


12. Number Pyramid -

13. Palindromic Pattern -


14. Diamond -

HW
HW

HW
HW
HW ( Doubt )

# Functions/ Methods in Java:-


A function is a block of code that performs a specific task.

Qs. Why are functions used?

a. 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.

b. Functions make maintenance of code easy as we have to change at


one place if we make future changes to the functionality.

c. Functions make the code more readable and easy to understand.

Qs. What is the difference between functions and methods?

If we can any function directly it is called function but if it is called with


the objects of class then it is called method.

The syntax for function declaration is :

return-type function_name (parameter 1, parameter2, …… parameter n){


//function_body

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

- It is the unique name of that function.


- It is always recommended to declare a function before it is used.

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.

Qs. Write a function to multiply 2 numbers.

Qs. Write a function to calculate the factorial of a number.


Qs. Write a function to add 2 numbers.

1. Make a function to check if a number is prime or not.


Qs. Make a function to check if a given number n is even or not.

Qs. Make a function to print the table of a given number n.


Que. Write a program to enter the numbers till the user wants and at the
end it should display the count of positive, negative and zeros entered.

Qs. Write a program to print Fibonacci series of n terms where n


is input by user :

0 1 1 2 3 5 8 13 21 .....

In the Fibonacci series, a number is the sum of the previous 2


numbers that came before it.
Qs. Write a function that calculates the Greatest Common Divisor
of 2 numbers.
# Time & Space Complexity :-

Time complexity of an algorithm quantifies the amount of time taken by


an algorithm to run as a function of the length of the input.

Types of notations

1. O-notation: It is used to denote asymptotic upper bound. For a given


function g(n), we denote it by O(g(n)). Pronounced as “big-oh of g of n”. It
is also known as worst case time complexity as it denotes the upper
bound in which the algorithm terminates.

2. Ω-notation: It is used to denote asymptotic lower bound. For a given


function g(n), we denote it by Ω(g(n)). Pronounced as “big-omega of g of
n”. It is also known as best case time complexity as it denotes the lower
bound in which the algorithm terminates.

3. 𝚯-notation: It is used to denote the average time of a program


- Comparison of functions on the basis of time complexity

It follows the following order in case of time complexity:


n 3
O(n ) > O(n!) > O(n ) > O(n ) > O(n.log(n)) > O(n.log(log(n))) > O(n) > O(sqrt(n)) >
2

O(log(n)) > O(1)

Note: Reverse is the order for better performance of a code with


corresponding time complexity, i.e. a program with less time complexity is
more efficient.

# Space Complexity -

Space complexity of an algorithm quantifies the amount of time taken by


a program to run as a function of length of the input. It is directly
proportional to the largest memory your program acquires at any instance
during run time.

For example: int consumes 4 bytes of memory.

# 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.

a) Creating an Array (method 1) - with new keyword


int[] marks = new int[3];
marks[0] = 97;
marks[1] = 98;
marks[2] = 95;
b) Creating an Array (method 2)
int[] marks = {98, 97, 95};

c) Taking an array as an input and printing its elements.


import java.util.*;

public class Arrays{


public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int size = sc.nextInt();

int[] numbers = new int[size];


// Input
for(int i=0 ; i<size ; i++){
numbers[i] = sc.nextInt();
}
// Output
for(int i = 0 ; i<numbers.length ; i++){
System.out.print(numbers[i] + " ");
}
}
}

Qs. Take an array of names as input from the user and print them
on the screen.
import java.util.*;

public class Arrays{


public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int size = sc.nextInt();

String[] names = new String[size];


// Input
for(int i=0 ; i<size ; i++){
names[i] = sc.next();
}

// Output
for(int i = 0 ; i<names.length ; i++){
System.out.println("Name " +(i+1) + " is :" +names[i] + "
");
}
}
}

Qs. Find the maximum & minimum number in an array of integers.


import java.util.*;
public class Arrays{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int size = sc.nextInt();

int numbers[] = new int[size];

for(int i=0 ; i<size ; i++){


numbers[i] = sc.nextInt();
}

// int max = Integer.MIN_VALUE;


// int min = Integer.MAX_VALUE;
// Initialize min and max to the first element of the array
int max = numbers[0];
int min = numbers[0];

for(int i = 0 ; i<numbers.length ; i++){

if(numbers[i]< min){
min = numbers[i];
}
if(numbers[i]>max) {
max = numbers[i];
}
}

System.out.println("Largest number is : " + max);


System.out.println("Smallest number is : " + min);
}
}

Qs. Take an array of numbers as input and check if it is an array sorted in


ascending order.
import java.util.*;
public class Arrays{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int size = sc.nextInt();

int numbers[] = new int[size];

for(int i=0 ; i<size ; i++){


numbers[i] = sc.nextInt();
}

boolean isAscending = true;


for(int i = 0 ; i<numbers.length - 1 ; i++){
if(numbers[i] < numbers[i+1]){
isAscending = true;
} else {
isAscending = false;
break;
}
}

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.

a) Creating a 2D Array - with new keyword


int[][] marks = new int[3][3];

b)Taking a matrix as an input and printing its elements.


a. Taking a matrix as an input and printing its elements.
import java.util.*;

public class TwoDArrays {


public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
int rows = sc.nextInt();
int cols = sc.nextInt();

int[][] numbers = new int[rows][cols];

//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();
}
}
}

c) Searching for an element x in a matrix.


import java.util.*;
public class Arrays{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int rows = sc.nextInt() , cols = sc.nextInt();
int [][] numbers = new int [rows][cols];
//Input
//Rows
for(int i = 0 ; i<rows ; i++){
//Columns
for(int j = 0 ; j<cols ;j++){
numbers[i][j] = sc.nextInt();
}
}
int x = sc.nextInt();
for(int i = 0 ; i<rows ; i++){
for(int j = 0 ; j<cols ;j++){
if(numbers[i][j] ==x) {
System.out.println("Found x at ( " + i + " , " + j
+" )");
}
}

}
}

Qs. Print the spiral order matrix as output for a given matrix of numbers.

import java.util.*;

public class Arrays {


public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int m = sc.nextInt();

int matrix[][] = new int[n][m];


for(int i=0; i<n; i++) {
for(int j=0; j<m; j++) {
matrix[i][j] = sc.nextInt();
}
}

System.out.println("The Spiral Order Matrix is : ");


int rowStart = 0;
int rowEnd = n-1;
int colStart = 0;
int colEnd = m-1;

while( rowStart <= rowEnd && colStart <= colEnd){

for( int col = colStart ; col <= colEnd ; col++){


System.out.print(matrix[rowStart][col] + " ");
}
rowStart++;

for( int row = rowStart ; row <= rowEnd ; row++){


System.out.print(matrix[row][colEnd] + " ");
}
colEnd--;

for( int col = colEnd; col>= colStart ; col--){


System.out.print(matrix[rowEnd][col] + " ");
}
rowEnd--;

for( int row = rowEnd ; row >= rowStart ; row--){


System.out.print(matrix[row][colStart] + " ");
}
colStart++;
}
}
}
Why is the while condition important?
 The matrix traversal works by shrinking the boundaries (top,
bottom, left, right) as you complete each layer of the spiral.
 Without the while loop, the traversal logic inside the loop would
continue indefinitely, leading to an attempt to access elements
outside the valid range of the matrix.
 This would cause an IndexOutOfBoundsException or unexpected
behavior, as you'd be trying to access elements that don't exist.

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();

int matrix [][] = new int[n][m];


//Input
for(int i = 0 ; i<n ; i++){
for(int j = 0 ; j<m ; j++ ){
matrix[i][j] = 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();

Concatenation (Joining 2 strings)


String firstName = "Tony";
String secondName = "Stark";

String fullName = firstName + " " + secondName;


System.out.println(fullName);

Print length of a String


String firstName = "Tony";
String secondName = "Stark";

String fullName = firstName + " " + secondName;


System.out.println(fullName.length());

Access characters of a string


String firstName = "Tony";
String secondName = "Stark";
String fullName = firstName + " " + secondName;

for(int i=0; i<fullName.length(); i++) {


System.out.println(fullName.charAt(i));
}

Compare 2 strings
import java.util.*;

public class Strings {


public static void main(String args[]) {
String name1 = "Tony";
String name2 = "Tony";
// s1 > s2 : +ve value
// s1 = s2 : 0
// s1 < s2 : -ve value

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));

}
}

ParseInt Method of Integer class


public class Strings {
public static void main(String args[]) {
String str = "123";
int number = Integer.parseInt(str);
System.out.println(number);

}
}

ToString Method of String class


public class Strings {
public static void main(String args[]) {
int number = 123;
String str = Integer.toString(number);
System.out.println(str.length());

}
}

ALWAYS REMEMBER : Java Strings are Immutable.

Qs.Take an array of Strings input from the user & find the cumulative
(combined) length of all those strings.

import java.util.*;

public class Strings {


public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
int size = sc.nextInt();

String [] arr = new String[size];


int totlength = 0;

for(int i = 0 ; i < size; i++){


arr[i] = sc.next();
totlength += arr[i].length();
}

System.out.println(totlength);
}
}

# String Builder :

Declaration
StringBuilder sb = new StringBuilder("Apna College");
System.out.println(sb);

Get A Character from Index


StringBuilder sb = new StringBuilder("Tony");
//Get Char
System.out.println(sb.charAt(0));

Set a Character at Index


StringBuilder sb = new StringBuilder("Tony");
//Set Char
sb.setCharAt(0, 'P');
System.out.println(sb);

Insert a Character at Some Index


import java.util.*;

public class Strings {


public static void main(String args[]) {
StringBuilder sb = new StringBuilder("tony");
//Insert char
sb.insert(0, 'S');
System.out.println(sb);
}
}

Delete char at some Index


import java.util.*;

public class Strings {


public static void main(String args[]) {
StringBuilder sb = new StringBuilder("tony");
//Insert char
sb.insert(0, 'S');
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.*;

public class Strings {


public static void main(String args[]) {
StringBuilder sb = new StringBuilder("Tony");
sb.append(" Stark");
System.out.println(sb);
}
}

Print Length of String

import java.util.*;

public class Strings {


public static void main(String args[]) {
StringBuilder sb = new StringBuilder("Tony");
sb.append(" Stark");
System.out.println(sb);

System.out.println(sb.length());
}
}

Reverse a String (using StringBuilder class)

import java.util.*;

public class Strings {


public static void main(String args[]) {
StringBuilder sb = new StringBuilder("HelloWorld");

for(int i=0; i<sb.length()/2; i++) {


int front = i;
int back = sb.length() - i - 1;

char frontChar = sb.charAt(front);


char backChar = sb.charAt(back);

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 :

original = “eabcdef’ ; result = “iabcdif”

Original = “xyz” ; result = “xyz”

// .replace( ‘old char’ , ‘new char’);

Code 1 (Replace):

 Less memory-efficient than StringBuilder but more efficient than the


concatenation approach. The replace method internally creates a
new string, so it still involves creating an additional string object but
does so in a single pass.

import java.util.*;

public class Strings {


public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
String input = sc.next();
String result = input.replace('e' , 'i');
System.out.println(result);
}
}

Code 2 (String & Concatenation):


 Strings in Java are immutable. Every time you concatenate using
result += ..., a new String object is created. This can lead to higher
memory usage and lower performance, especially if the string is
long or the operation is performed many times.
 Simpler to understand and write, but this simplicity comes at the
cost of performance.

import java.util.*;

public class Strings {


public static void main(String args[]) {
Scanner sc = new Scanner (System.in);
String str = sc.next();
String result = "";

for(int i=0; i<str.length(); i++) {


if(str.charAt(i) == 'e') {
result += 'i';
} else {
result += str.charAt(i);
}
}

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());

for(int i = 0 ; i < sb.length(); i++ ){


if(sb.charAt(i) == 'e'){
sb.setCharAt(i , 'i');
}
}
System.out.println(sb);
}
}

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 :

email = “apnaCollegeJava@gmail.com” ; username = “apnaCollegeJava”

email = “helloWorld123@gmail.com”; username = “helloWorld123”

Code 1 (String with Concatenation):

 Less efficient due to repeated string concatenation (userName


+= ...), which creates a new String object each time. This can be
costly in terms of performance, especially with long email
addresses.

import java.util.*;

public class Strings {


public static void main(String args[]) {
Scanner sc = new Scanner (System.in);
String email = sc.next();
String userName = "";

for(int i=0; i<email.length(); i++) {


if(email.charAt(i) == '@') {
break;
} else {
userName += email.charAt(i);
}
}

System.out.println(userName);
}
}

Code 2 (String with Index Tracking):


 Reasonably efficient. It finds the index of '@' and then uses substring,
which creates a new string, but it does so only once. The loop
breaks after finding the '@', so it doesn't traverse the entire string
needlessly.

import java.util.*;

public class Strings {


public static void main(String args[]) {
Scanner sc = new Scanner (System.in);
System.out.print("Enter Email : ");
String str = sc.nextLine();
int result = 0;

for(int i = 0 ; i < str.length() ; i++){


if(str.charAt(i)== '@'){
result += i;
}
}

System.out.print("Username : " + str.substring(0 , result));


}
}

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());

for(int i = 0 ; i < sb.length(); i++ ){


if(sb.charAt(i)=='@'){
sb.delete(i , sb.length());
}
}
System.out.println(sb);

}
}
Bit Manipulation :

1. Get Bit
Bit Mask = 1<<i
Operation : AND
import java.util.*;

public class Bits {


public static void main(String args[]) {
int n = 5; //0101
int pos = 3;
int bitMask = 1<<pos;

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.*;

public class Bits {


public static void main(String args[]) {
int n = 5; //0101
int pos = 1;
int bitMask = 1<<pos;

int newNumber = bitMask | n;


System.out.println(newNumber);
}
}

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.*;

public class Bits {


public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
int oper = sc.nextInt();
// oper=1 -> set; oper=0 -> clear
int n = 5;
int pos = 1;

int bitMask = 1<<pos;


if(oper == 1) {
//set
int newNumber = bitMask | n;
System.out.println(newNumber);
} else {
//clear
int newBitMask = ~(bitMask);
int newNumber = newBitMask & n;
System.out.println(newNumber);
}

}
}

Qs. Write a program to find if a number is a power of 2 or not.

 My code :- The numbers which are a power of 2 only have one


“1” .Therefore I have written the code to input a number then
checks all the bits upto n. If there is single “1” found it results that
the number is 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 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");
}
}
}

 Most efficient solution :


Concept of n-1 in binary – If we use (n-1) then the rightmost “1” is
flipped to “0” and all bits on right of this 1 are flipped from “0” to
“1” or “1” to “0”. While the digits on the left of this 1 remains
unchanged.

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");
}
}
}

Qs. Write a program to toggle a bit a position = “pos” in a number “n”.


XOR(^) is ideal for toggling because it inverts the bit at the specified
position. This approach directly handles both cases:

 If the bit is 0, it becomes 1.

 If the bit is 1, it becomes 0.

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;

int toggledNum = n ^ bitMask;


System.out.println(toggledNum);
}
}

Qs. Write a program to count the number of 1’s in a binary representation


of the number.

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);
}
}

Qs. Write 2 functions => decimalToBinary() & binaryToDecimal() to


convert a number from one number system to another.
 DecimalToBinary

import java.util.*;
public class Bits {
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int num1 = sc.nextInt();

StringBuilder binary = new StringBuilder();

while ( num1 > 0){


binary.append(num1 % 2);
num1 = num1 / 2;
}

for( int i = 0 ; i< binary.length() ; i++){


int pos = binary.length()-1-i;
System.out.print(binary.charAt(pos));
}

// 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;

for(int i = length; i >= 0 ; i--){


if(binary.charAt(i)=='1'){ // Check if the bit is 1
int num1 = 1;
for(int j=1; j<=length -i ; j++){
num1 *= 2; // Multiply by 2 for each position shift
}
decimal += num1; // Add to the decimal number
}
}

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)

public class Sorting {

public static void printArray(int arr[] ){


for(int i = 0 ; i<arr.length ; i++){
System.out.print(arr[i] + " ");
}
}

public static void main(String[] args){


int arr[] = {7,8,1,3,2};

//Bubble sort
// Time Complexity = O(n^2)

for(int i = 0 ; i<arr.length-1; i++ ){


for( int j = 0 ; j<arr.length-1-i ; j++){
if(arr[j]> arr[j+1]) {
//Swap
int temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}

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)

public class Sorting {

public static void printArray(int arr[] ){


for(int i = 0 ; i<arr.length ; i++){
System.out.print(arr[i] + " ");
}
}

public static void main(String[] args){


int arr[] = {7,8,1,3,2};

//Selection sort
// Time Complexity = O(n^2)

for(int i = 0 ; i<arr.length-1; i++ ){


int smallest = i;
for( int j = i+1 ; j<arr.length ; j++){
if(arr[j]<arr[smallest]){
smallest=j;
}
}

//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.

public class Sorting {

public static void printArray(int arr[] ){


for(int i = 0 ; i<arr.length ; i++){
System.out.print(arr[i] + " ");
}
}

public static void main(String[] args){


int arr[] = {7,8,1,3,2};

//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);
}
}

You might also like