Showing posts with label JAVA. Show all posts
Showing posts with label JAVA. Show all posts

Wednesday 12 April 2023

Beginner Level Java programs

No comments :

 



Array Examples:


1. Program to find the sum of all elements in an array:


public class ArraySum {

    public static void main(String[] args) {

        int[] arr = {2, 4, 6, 8, 10};

        int sum = 0;


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

            sum += arr[i];

        }


        System.out.println("Sum of elements in array: " + sum);

    }

}



2. Program to find the maximum element in an array:


public class ArrayMax {

    public static void main(String[] args) {

        int[] arr = {2, 4, 6, 8, 10};

        int max = arr[0];


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

            if (arr[i] > max) {

                max = arr[i];

            }

        }


        System.out.println("Maximum element in array: " + max);

    }

}









3. Program to find the minimum element in an array:


public class ArrayMin {

    public static void main(String[] args) {

        int[] arr = {2, 4, 6, 8, 10};

        int min = arr[0];


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

            if (arr[i] < min) {

                min = arr[i];

            }

        }


        System.out.println("Minimum element in array: " + min);

    }

}


4. Program to search for an element in an array:


public class ArraySearch {

    public static void main(String[] args) {

        int[] arr = {2, 4, 6, 8, 10};

        int num = 8;

        boolean found = false;


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

            if (arr[i] == num) {

                found = true;

                break;

            }

        }


        if (found) {

            System.out.println(num + " found in array");

        } else {

            System.out.println(num + " not found in array");

        }

    }

}







5. Program to sort an array in ascending order:


public class ArraySort {

    public static void main(String[] args) {

        int[] arr = {10, 2, 8, 6, 4};

        int temp;


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

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

                if (arr[i] > arr[j]) {

                    temp = arr[i];

                    arr[i] = arr[j];

                    arr[j] = temp;

                }

            }

        }


        System.out.println("Sorted array in ascending order:");

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

            System.out.print(arr[i] + " ");

        }

    }

}




For loop-based programs


6. Program to print the numbers from 1 to 10:


public class PrintNumbers {

    public static void main(String[] args) {

        for (int i = 1; i <= 10; i++) {

            System.out.print(i + " ");

        }

    }

}


7. Program to print the even numbers from 1 to 20:


public class PrintEvenNumbers {

    public static void main(String[] args) {

        for (int i = 2; i <= 20; i += 2) {

            System.out.print(i + " ");

        }

    }

}



8. Program to print the sum of the numbers from 1 to 100:


public class SumNumbers {

    public static void main(String[] args) {

        int sum = 0;


        for (int i = 1; i <= 100; i++) {

            sum += i;

        }


        System.out.println("Sum of numbers from 1 to 100: " + sum);

    }

}



8. Program to print the multiplication table of a number:


import java.util.Scanner;


public class MultiplicationTable {

    public static void main(String[] args) {

        Scanner input = new Scanner(System.in);

        System.out.print("Enter a number: ");

        int num = input.nextInt();


        for (int i = 1; i <= 10; i++) {

            System.out.println(num + " x " + i + " = " + (num * i));

        }

    }

}




9. Program to print a right-angled triangle using asterisks:


import java.util.Scanner;


public class RightTriangle {

    public static void main(String[] args) {

        Scanner input = new Scanner(System.in);

        System.out.print("Enter the height of the triangle: ");

        int height = input.nextInt();


        for (int i = 1; i <= height; i++) {

            for (int j = 1; j <= i; j++) {

                System.out.print("*");

            }

            System.out.println();

        }

    }

}


While loop-based programs


10. Program to print the numbers from 1 to 10:


public class PrintNumbers {

    public static void main(String[] args) {

        int i = 1;


        while (i <= 10) {

            System.out.print(i + " ");

            i++;

        }

    }

}











11. Program to print the sum of the numbers from 1 to 100:


public class SumNumbers {

    public static void main(String[] args) {

        int sum = 0;

        int i = 1;


        while (i <= 100) {

            sum += i;

            i++;

        }


        System.out.println("Sum of numbers from 1 to 100: " + sum);

    }

}


12. Program to find the factorial of a number:


import java.util.Scanner;


public class Factorial {

    public static void main(String[] args) {

        Scanner input = new Scanner(System.in);

        System.out.print("Enter a number: ");

        int num = input.nextInt();

        int factorial = 1;

        int i = 1;


        while (i <= num) {

            factorial *= i;

            i++;

        }


        System.out.println("Factorial of " + num + " = " + factorial);

    }

}







Do While loop-based programs


13. Program to print the sum of the numbers from 1 to 100:


 public class SumNumbers {

    public static void main(String[] args) {

        int sum = 0;

        int i = 1;


        do {

            sum += i;

            i++;

        } while (i <= 100);


        System.out.println("Sum of numbers from 1 to 100: " + sum);

    }

}



14. Program to ask the user for a password until it matches a predetermined password:


import java.util.Scanner;


public class Password {

    public static void main(String[] args) {

        Scanner input = new Scanner(System.in);

        String password = "password123";

        String userPassword;


        do {

            System.out.print("Enter the password: ");

            userPassword = input.nextLine();

        } while (!userPassword.equals(password));


        System.out.println("Password accepted!");

    }

}






Class and object-based programs


15. Program to create a simple class and object:


public class MyClass {

    int myVariable;


    public static void main(String[] args) {

        MyClass obj = new MyClass();

        obj.myVariable = 10;

        System.out.println(obj.myVariable);

    }

}


16. Program to create a class with a constructor


public class Person {

    String name;

    int age;


    public Person(String name, int age) {

        this.name = name;

        this.age = age;

    }


    public static void main(String[] args) {

        Person person = new Person("John", 30);

        System.out.println("Name: " + person.name);

        System.out.println("Age: " + person.age);

    }

}


17. Program to create a class with methods


public class Rectangle {

    int length;

    int width;


    public Rectangle(int length, int width) {

        this.length = length;

        this.width = width;

    }


    public int area() {

        return length * width;

    }


    public int perimeter() {

        return 2 * (length + width);

    }


    public static void main(String[] args) {

        Rectangle rect = new Rectangle(5, 7);

        System.out.println("Area: " + rect.area());

        System.out.println("Perimeter: " + rect.perimeter());

    }

}


Read More

Sunday 19 March 2023

50 Common Java Interview Programs

No comments :

 



Here is a list of Java programs commonly asked about during interviews:

1. Fibonacci series

Program to display any given number of integers of the Fibonacci series. In the Fibonacci series, each number is equal to the sum of the two numbers that precede it.

2. Checking for prime number

Program to verify whether a given number is a prime or composite.

3. String palindrome

Program to verify whether a given string is a palindrome or not. A string is a palindrome if it is equal to the reverse of itself.

4. Integer palindrome

Program to verify whether a given integer is a palindrome or not.

5. Armstrong number

Program to verify whether a given number is an Armstrong number. An Armstrong number is equal to the sum of the cubes of its digits.

6. Avoiding deadlocks

Program where a resource can be accessed by more than one thread, without encountering a deadlock. To avoid deadlocks, you are required to procure resources in a certain order and ensure that they are released in reverse order.

7. Factorial

Program to calculate and display the factorial of any given number.

8. Reversing strings

Program to reverse the order of characters in any given string.

9. Removing repeated elements from an array

Program to identify and remove all repeated elements from an array. Arrays could be of various types like integer, character or string.

10. Printing patterns

Program to print a given pattern composed of ASCII characters. The solution is required to employ an effective algorithm, as opposed to directly printing the pattern as it is.

11. Printing repetitive characters in a string

Program to identify and print all repeated characters of a string.

12. Finding the greatest common denominator of two numbers

Program to print the greatest common denominator of any two given numbers.

13. Finding the square root of a number

Program to print a given number's square root without employing the math.sqrt() function.

14. Reversing an array in place

Program to reverse the order of elements in a string, integer or character array.

15. Reversing the order of words in a sentence

Program to reverse the order of words in any given sentence.

16. Determining leap year

Program to determine whether a given year is a leap year or not.

17. Performing binary search

Program to perform binary search for a given character/integer within a sorted array. In a binary search, the search interval is repeatedly divided into half with every iteration.

18. Checking for anagrams

Program to check if two given strings are anagrams. An anagram is of the same length and is composed of the same characters, but in a different order.

19. Designing a vending machine

Program to create a vending machine interface based on a given set of guidelines. This is a popular OOAD (Object-Oriented Analysis and Design) problem that is frequently asked in Java interviews.

20. Reversing a number

Program to print any given number with the digits in reverse order.

21. Finding the first unique character of a string

Program to identify and print the first unique character in any given string.

22. Finding the middle element of a linked list

Program to print the middle element of a linked list. You may be required to execute this with a single-pass algorithm, meaning the program would read the input only once before running iterations.

23. Performing pre-order traversal

Program to perform pre-order traversal of a hierarchical data structure. Hierarchical data structures like trees can be traversed in multiple ways. Linear data structures like arrays, linked lists, queues and stacks can only be traversed in one logical way.

24. Performing pre-order traversal without recursion

Program to perform pre-order traversal of a tree without recursion. Recursion in Java involves a function/method calling itself within the code.

25. Performing in-order traversal

Program to perform in-order traversal of a hierarchical data structure.

26. Performing in-order traversal without recursion

Program to perform in-order traversal of a tree, employing an iterative solution. Iteration, an alternative to recursion, involves a loop being repeatedly executed till a specific condition is met.

27. Performing post-order traversal

Program to perform post-order traversal of a hierarchical data structure.

28. Performing post-order traversal without recursion

Program to perform post-order traversal of a tree, employing an iterative solution.

29. Printing all leaves of a binary tree

Program to print the values of all leaves in a binary tree. Additionally, you may be asked to print the values in a certain order or hierarchy.

30. Sorting an array using quick-sort

Program to sort a given array of integers using the quick-sort algorithm.

31. Performing insertion sort

Program to sort a given array using the insertion sort algorithm.

32. Performing bubble sort

Program to sort a given array using the bubble sort algorithm.

33. Transposing a matrix

Program to print the transpose of a given matrix. A transpose of a matrix has all its rows and columns interchanged.

34. Printing all permutations of a string

Program to print all character arrangement permutations for any given string.

35. Reversing a string in place

Program to reverse the order of characters in any given string. But, the reversing has to be done in place, meaning the solution is not required to involve creating a duplicate string for reversal.

36. Adding matrices

Program to add any two given matrices and print the result.

37. Multiplying matrices

Program to multiply any two given matrices and print the result.

38. Removing spaces in a string

Program to identify and remove all white spaces in a given string of characters.

39. Reversing a linked list

Program to reverse the order of contents of a singly linked list.

40. Finding the length of a linked list

Program to determine the length of a singly linked list in one iteration of the code.

41. Checking for loops in a linked list

Program to check whether a given linked list contains a loop or not. Corrupt linked lists can sometimes have two nodes pointing to the same location, thereby forming a cycle or loop.

42. Finding the start of looping in a linked list

Program to identify and print the starting instance of looping in a linked list.

43. Finding the middle element of a linked list

Program to determine and print the middle element(s) of a linked list.

44. Finding the nth element from the tail of a linked list

Program to find the nth element from the end of a given linked list, where n is a variable value provided by the user. You may be required to find a solution that does not involve multiple iterations.

45. Converting a linked list to a binary tree

Program to convert a doubly linked list to a binary tree.

46. Sorting a linked list

Program to sort a given linked list in ascending or descending order of values in each node.

47. Performing bucket sort

Program to sort the contents of a given array using the bucket sort algorithm. Bucket sort is a linear sorting algorithm that requires you to know the highest value present in the array before sorting it.

48. Performing counting sort

Program to sort the contents of a given array using the counting sort algorithm. Counting sort is also a linear sorting algorithm like bucket sort, and it helps to know the subtle differences between the two.

49. Performing merge sort

Program to sort the contents of a given array using the merge sort algorithm. You may be required to provide a recursive or iterative solution, depending on what is needed.

50. Checking if two strings are rotations of each other

Program to determine whether any two given strings are rotations of each other. For example, zxy is a rotation of xyz, but zyx is not.

Solutions to the above program will be updated soon.

Read More

Sunday 2 April 2017

Java Concepts required for developing Android apps

No comments :

In the previous posts, we have learned the software setup and emulator creations, which are very mandatory for the Android app development.

In this post i am going to tell about what are the java concepts required to develop android apps.

Yes, the android apps are created using java programming , so we need to learn the some Java Concepts to create Android apps.

The Android app development is done using two things.

1.Java code to implement the app functionality

2. XML code to design the User Interface( UI ).

In java there are lots of concepts but we do not need all the concepts to develop simple android apps.

Following concepts are enough to develop an android app:

A simple Info-graphic:



1. Basic programming Concepts.      ( this is just fundamentals)

2.Data Types 

3.Operators

4.Control Statements(this concept is very important)

 5.OOPS (Object Oriented Programming)

 6. String Handling

 7.Array List 

 8.Basics of Multi threading       (For advanced apps)

9.Basics of Exception Handling (For advanced apps)



If you want to learn java no need of any programming experience before. Just by reading some below post you can easily learn Java.

First you need to be familiar with programming for that purpose read some simple C programming...

1. How to run a C program
2.  How to add 2 numbers in C
3. Decision Control Statements
4. Loop Control Statements

If you are already familiar with this concept just, skip to start learning java.

After becoming familiar with this fundamentals let start to learn about java.

1. How to Run a Java Program
2.How to add 2 numbers in java
3.How to get input from the user
4. Classes and Objects in Java 

If you already know the above concepts just start learning the required concepts.

Practice the above concepts till you become familiar with that.

After that start to learn the Required Java Concepts for developing android applications.

There is a perfect blog to learn all Java concepts that is www.javatpoint.com .

This blog will provide A-Z knowledge in java.

You can learn what you want , try to first complete the above mentioned required java concepts required to develop android apps , then if you want you can learn more.


Read here:

How to develop Android apps






Read More

Saturday 13 February 2016

Data types in Java

No comments :
data-types-in-java

Hello mate, In this post I am going to tell you about the Data types used in Java. In the previous Java tutorials, we have learned about Java variables, objects, classes, methods etc...
Now we are going to learn about the data types used in JAVA.
While coming to the normal way of programming to instruct a machine the knowledge of data types is more important. It’s like knowing alphabets of a language before going to learn a new language. For every programming language, there will be some sort of data types.
Data types are the basic things that need to be known when creating a program for performing some mathematical operations. Data types can be used to specify how data is represented in JAVA. In our previous tutorials “How to get input from the user” and “Addition of two numbers” there was something like “int a,b;”  mentioned that they are integer Data Types. While doing such calculations, it is necessary to mention the type of data. Two types of Data types in Java.
Data-types

 They are,
  1. Primitive Data types
  2. Reference Data types
Primitive Data types:
Primitive Data types are the basic and predefined Data Types in Java. When considering about Data Types Eight primitive Data Types are getting important. They are
 Integer:
  • For representing the whole numbers, integer data type is used. Like integer short, long and byte are also used for representing whole numbers.
  • But they are different in their length.
  • The range of int data type is from -2,147,483,648 to 2,147,483,647.
  • Default integer type value is 0.
  • The size of integer Data Type is 4 bytes.
Example:
int a,b,c;
Here a,b,c are the integer type variables. Naming considerations of these variables are explained in Variables.
Long:
  • If integer data type is not sufficient, long is used to represent large values than the integer.
  • The range of this data type is from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807.
  • The default value of this Data Type is 0L.
  • The size of long Data Type is 8 bytes.
Example:
long g;
Here g is a long type variable. Long Data Types are rarely used in basic programming.
Short:
  • Short can be used for representing short values (whole numbers).
  • Its range is from -32,768 to 32,767.
  • The default value of this Data Type is 0.
  • The size of short Data Type is 2 bytes.
Example:
short k;
Here k is a short type variable.
 Byte:
  • This is the smallest data type for representing whole numbers.
  • Byte Data Type ranges from -128 to 127.
  • Its default value is 0.
  • The size of this Data Type is one byte.
Example:
byte h,g;
Here h and g are byte type variables.
Float:
  • Float and double are used for representing the decimal point numbers such as 2819.248.
  • These data types are also called as Real types.
  • The default value of Float is 0f.
  • The size of this Data Type is 4 bytes.
Example:
float r;
Here r is the float type variable
Double:
  • The double data type is also same as Float, used for representing decimal point numbers larger than Float.
  • Ranges from to.
  • The default value of the double is 0d.
  • The size of this Data Type is 8 bytes.
Example:
double h;
Here h is a double Type variable.
Boolean:
  • The boolean data type can take Boolean values true and false in the form of 0s and 1s.
  • A Boolean variable can be assigned to a Boolean value or to an expression which returns a Boolean value.
  • Its default value is ‘false’.
Example:
boolean d=false;
(OR)
int a=45;
System.out.println((a>40));//which returns a Boolean value as 1(one)which indicates condition is true.
Character:
  • The character is a data type that allows single character (mostly alphabets but it allows any type of letters) to scan and print.
  • The size of character data type is 2 bytes.
  • Its default value is \u0000”.
Example:
char a;
Here a is the Character type variable.
 Literals:
Variables assigned with a particular value are called as literals, the value of the variable is not getting changed throughout the program. Literals are similar to enumerations which are having the same meaning but declaration of enumerations is difficult.
Example:
byte b=40;
char c=’k’;
 Reference Data Types:
Reference data types allow the user to define the size of the data. Using this data type user can dynamically allocate the size. Reference data types in JAVA are,
 Classes:
Classes are known as the reference data types. Variables having class type data are called as objects. These are used for representing real-world situations. Objects are used for accessing the methods inside the class.
Primitive data types would have fixed size in memory and it can’t be changed. In reference data types there is no fixed size, by the use of new operator user can dynamically allocate memory. This new operator is used in the object creation, array declaration etc.
By using this kind of data type, we can define the real world things such as the properties of vehicles and specifically car etc.
Example:
computer c=new computer();
Here c is the object of class computer and we can mention this that c is the variable of type class computer.
 Arrays:
Arrays are the collection of similar data types. For example, an integer array can hold a fixed amount of integer data type variables.
Example(integer array):
int a[]=new int[10];
or
int a[]={20,40,10,50,70,25,35,55,80,30}
Two important terms in the array are elements and index. Elements are the terms represented by the array. The terms inside the ‘{}’ are called the elements of the array. In other words, values inside the array are called as elements. Another term index which is used to access the elements, normally index starts with 0 and ends with the size of the array-1. In the above example a[10], the first element is stored in 0th place of the index that is a[0], the second element is stored in a[1] .... the last element that is 10th element is stored in a[9]th place.
Arrays are one of the important concepts of JAVA. Here we are mentioning that array is one of the reference data types in JAVA, but the array is the vast concept that needs to be clearly known for a programmer so all the aspects of arrays are fully explained in upcoming concepts.
 Interfaces:
The interface in JAVA can be used for replacing the multiple inheritances in C++. Inheritance is the concept of deriving a subclass from the superclass. The subclass is also called as derived class and super class is also called as the base class. Multiple inheritances mean deriving a base class from more than one derived classes. This concept is implemented by interfaces in java. Interfaces can be discussed deeply in the following chapters.
Also read:

Java Classes Methods and Objects


Read More

Friday 22 January 2016

Java Classes Methods and Objects

No comments :


Hello guys , 

In this post I am going to tell about what are classes , methods and objects in Java.

     Classes, Methods and Objects are playing the important key role in creating a JAVA program. A programmer needs to know all about these concepts.

Let me tell the abstract meaning for Classes , methods and objects.

Consider the class as your house door’s locker ,



Consider the method as the things in your home.



and consider the objects as the key




to the locker of your door’s locker( i.e classes).

If you need to access the things (i.e methods)  inside your home (i.e classes)you need to open the door of the house.

In order to open the door of the house we need a key to open the door. 
That key is called as objects. 

This is the basic concept happening in the coding part logically.

Classes:


      A class is defined as an entity that allows data and functions to work together, A class is considered as the user defined reference Data Type. 
     
     Predefined primitive Data Types are only limited and not used to represent real world things. But a class can represent real world entities through objects.

     For example there is no Data Type to describe properties of a car, or a computer etc. A class Data Type only describes these things.

     JAVA program is composed of full of classes, A JAVA program must have a main class containing main() method. Even the main() method also must be inside the class. So classes are more important. A class can have any number of objects.

  JAVA allows accessing of one class’s method from another class, one of the main use of object creation is to initiate a class.

Syntax:


class class_name

{

public method1()

{....}

public method2()
{.....}

public static void main(String args[])
{....}

}


 For the easy for understanding consider the example

class home

{

public fan()

{ ...

}

public static void main(String args[])

{
....

}

}

class home we already seen in the picture


As described above, a class can have several methods. In this example the class home has method method fan.

Methods:

To perform various functions inside the class, various methods are created, if we enter various operations under single method, then that will increase the complexity level like Structural language(C Language). 

For this reason different methods are created based on the usage.

Member function provides the controlled access to the data members (Methods are also called as member functions and Variables are also called as Data Members).

Syntax:

Method_name()

{
//variables

//functions
}

In method name the closed bracket must present"( )"

In our example the method is 

public void fan()

{

System.out.println(“method fan is accessed”);

}

The program after defining the method is given below


import java.io.*;

class house

{

public void fan()

{

System.out.println("method fan is accessed");

}

public static void main(String args[])

{

}

}

Now we are clear about what are classes and methods, let we learn how to access the methods inside the class.


The methods in the class is accessed from the main method public static void main  with the help of the objects ( key ).

OBJECTS:

     The basic definition from all the books and references for object is "Object is a real-world entity" the reason is, objects can represent a name, or a place or any item that a program handles.


    For example if the class is computer( class computer), monitor, keyboard, hardware and software will be objects of computer class.

   While considering Procedural Oriented Programming Languages understanding the programming flow of the large program seems to be more difficult.

 In Object Oriented Languages, programming and understanding the concept of large programs is very easy.
 

  Object Oriented means, all the parts or components are in the form of objects and classes. So what is OBJECT( a main block in JAVA)Object is an instance of a class. 

Using objects we can access the member variables  (Variables of different methods) and member functions ( or methods) of a class.

For Example:

Objects can be like flowers, rose, man or anything that used in the real world.

Objects are the instantiations for class.

Object creation:

class_name object_name=new class_name();

(OR)

class_name  object_name;
object_name = new class_name();


Example:

house h=new house();
      (OR)
house h;
h = new house();

      But exactly the meaning is object created from these above statements does not have any name, here h is the reference variable that holds the address of the object created for class house.


Let us see the full program in detail

import java.io.*;


      class house //  your house

{

         public void fan()   // fan inside your house

{


System.out.println("method fan is accessed");


}


public static void main(String args[])


{


house h=new house();// object creation (i.e key for your house to access fan)


h.fan();// accessing the method fan by the object h


}


}

     I hope now you are clear about the Java Classes, methods and objects.
Also read,

How to run a Java Program






Read More