Search Results
25 items found for ""
- Machine Learning Assignment Unit-4 Sem-5 BCA
Unit : 4 Supervised Learning Subject : Machine Learning Std : BCA Sem-5 1. Define : Supervised Learning. Ans. Supervised learning is the types of machine learning in which machines are trained using well "labelled" training data, and on basis of that data, machines predict the output. The labelled data means some input data is already tagged with the correct output. In supervised learning, the training data provided to the machines work as the supervisor that teaches the machines to predict the output correctly. It applies the same concept as a student learns in the supervision of the teacher. Supervised learning is a process of providing input data as well as correct output data to the machine learning model. The aim of a supervised learning algorithm is to find a mapping function to map the input variable(x) with the output variable(y). How Supervised Learning Works? In supervised learning, models are trained using labelled dataset, where the model learns about each type of data. Once the training process is completed, the model is tested on the basis of test data (a subset of the training set), and then it predicts the output. The working of Supervised learning can be easily understood by the below example and diagram: Suppose we have a dataset of different types of shapes which includes square, rectangle, triangle, and Polygon. Now the first step is that we need to train the model for each shape. If the given shape has four sides, and all the sides are equal, then it will be labelled as a Square. If the given shape has three sides, then it will be labelled as a triangle. If the given shape has six equal sides then it will be labelled as hexagon. Types of supervised Machine learning Algorithms: 1. Regression : Regression algorithms are used if there is a relationship between the input variable and the output variable. It is used for the prediction of continuous variables, such as Weather forecasting, Market Trends, etc. 2. Classification : Classification algorithms are used when the output variable is categorical, which means there are two classes such as Yes-No, Male-Female, True-false, etc. Advantages of Supervised learning: With the help of supervised learning, the model can predict the output on the basis of prior experiences. In supervised learning, we can have an exact idea about the classes of objects. Supervised learning model helps us to solve various real-world problems such as fraud detection, spam filtering, etc. Disadvantages of supervised learning: Supervised learning models are not suitable for handling the complex tasks. Supervised learning cannot predict the correct output if the test data is different from the training dataset. Training required lots of computation times. In supervised learning, we need enough knowledge about the classes of object. 2. Explain types of Supervised Learning Algorithm. Ans. Supervised learning is typically divided into two main categories: regression and classification. In regression, the algorithm learns to predict a continuous output value, such as the price of a house or the temperature of a city. Supervised learning can be further classified into two categories: Regression : Regression is a supervised learning technique used to predict continuous numerical values based on input features. It aims to establish a functional relationship between independent variables and a dependent variable, such as predicting house prices based on features like size, bedrooms, and location. The goal is to minimize the difference between predicted and actual values using algorithms like Linear Regression, Decision Trees, or Neural Networks, ensuring the model captures underlying patterns in the data. Classification : Classification is a type of supervised learning that categorizes input data into predefined labels. It involves training a model on labeled examples to learn patterns between input features and output classes. In classification, the target variable is a categorical value. For example, classifying emails as spam or not. The model’s goal is to generalize this learning to make accurate predictions on new, unseen data. Algorithms like Decision Trees, Support Vector Machines, and Neural Networks are commonly used for classification tasks. Supervised Machine Learning Algorithm : Supervised learning can be further divided into several different types, each with its own unique characteristics and applications. Here are some of the most common types of supervised learning algorithms: Linear Regression: Linear regression is a type of regression algorithm that is used to predict a continuous output value. It is one of the simplest and most widely used algorithms in supervised learning. In linear regression, the algorithm tries to find a linear relationship between the input features and the output value. The output value is predicted based on the weighted sum of the input features. Logistic Regression: Logistic regression is a type of classification algorithm that is used to predict a binary output variable. It is commonly used in machine learning applications where the output variable is either true or false, such as in fraud detection or spam filtering. In logistic regression, the algorithm tries to find a linear relationship between the input features and the output variable. The output variable is then transformed using a logistic function to produce a probability value between 0 and 1. Decision Trees: Decision tree is a tree-like structure that is used to model decisions and their possible consequences. Each internal node in the tree represents a decision, while each leaf node represents a possible outcome. Decision trees can be used to model complex relationships between input features and output variables. A decision tree is a type of algorithm that is used for both classification and regression tasks. Decision Trees Regression: Decision Trees can be utilized for regression tasks by predicting the value linked with a leaf node. Decision Trees Classification: Random Forest is a machine learning algorithm that uses multiple decision trees to improve classification and prevent overfitting. Random Forests: Random forests are made up of multiple decision trees that work together to make predictions. Each tree in the forest is trained on a different subset of the input features and data. The final prediction is made by aggregating the predictions of all the trees in the forest. Random forests are an ensemble learning technique that is used for both classification and regression tasks. Random Forest Regression: It combines multiple decision trees to reduce overfitting and improve prediction accuracy. Random Forest Classifier: Combines several decision trees to improve the accuracy of classification while minimizing overfitting. Support Vector Machine(SVM): The SVM algorithm creates a hyperplane to segregate n-dimensional space into classes and identify the correct category of new data points. The extreme cases that help create the hyperplane are called support vectors, hence the name Support Vector Machine. A Support Vector Machine is a type of algorithm that is used for both classification and regression tasks Support Vector Regression: It is a extension of Support Vector Machines (SVM) used for predicting continuous values. Support Vector Classifier: It aims to find the best hyperplane that maximizes the margin between data points of different classes. K-Nearest Neighbors (KNN): KNN works by finding k training examples closest to a given input and then predicts the class or value based on the majority class or average value of these neighbors. The performance of KNN can be influenced by the choice of k and the distance metric used to measure proximity. However, it is intuitive but can be sensitive to noisy data and requires careful selection of k for optimal results. A K-Nearest Neighbors (KNN) is a type of algorithm that is used for both classification and regression tasks. K-Nearest Neighbors Regression: It predicts continuous values by averaging the outputs of the k closest neighbors. K-Nearest Neighbors Classification: Data points are classified based on the majority class of their k closest neighbors. Gradient Boosting: Gradient Boosting combines weak learners, like decision trees, to create a strong model. It iteratively builds new models that correct errors made by previous ones. Each new model is trained to minimize residual errors, resulting in a powerful predictor capable of handling complex data relationships. A Gradient Boosting is a type of algorithm that is used for both classification and regression tasks. Gradient Boosting Regression: It builds an ensemble of weak learners to improve prediction accuracy through iterative training. Gradient Boosting Classification: Creates a group of classifiers to continually enhance the accuracy of predictions through iterations 3. Explain advantages and disadvantages of Supervised Learning. Ans. Advantages of Supervised Learning : The power of supervised learning lies in its ability to accurately predict patterns and make data-driven decisions across a variety of applications. Here are some advantages listed below: Labeled training data benefits supervised learning by enabling models to accurately learn patterns and relationships between inputs and outputs. Supervised learning models can accurately predict and classify new data. Supervised learning has a wide range of applications, including classification, regression, and even more complex problems like image recognition and natural language processing. Well-established evaluation metrics, including accuracy, precision, recall, and F1-score, facilitate the assessment of supervised learning model performance. Disadvantages of Supervised Learning : Although supervised learning methods have benefits, their limitations require careful consideration during problem formulation, data collection, model selection, and evaluation. Here are some disadvantages listed below: Overfitting: Models can overfit training data, which leads to poor performance on new, unseen data due to the capture of noise. Feature Engineering: Extracting relevant features from raw data is crucial for model performance, but this process can be time-consuming and may require domain expertise. Bias in Models: Training data biases can lead to unfair predictions. Supervised learning heavily depends on labeled training data, which can be costly, time-consuming, and may require domain expertise. 4. Discuss types of dataset in detail. Ans. These input data used to build the model are usually divided into multiple data sets. In particular, three data sets are commonly used in different stages of the creation of the model: training, validation, and test sets. Training data set : A training data set is a data set of examples used during the learning process and is used to fit the parameters (e.g., weights) of, for example, a classifier. For classification tasks, a supervised learning algorithm looks at the training data set to determine, or learn, the optimal combinations of variables that will generate a good predictive model. The goal is to produce a trained (fitted) model that generalizes well to new, unknown data. The fitted model is evaluated using “new” examples from the held-out datasets (validation and test datasets) to estimate the model’s accuracy in classifying new data. To reduce the risk of issues such as over-fitting, the examples in the validation and test datasets should not be used to train the model. Most approaches that search through training data for empirical relationships tend to overfit the data, meaning that they can identify and exploit apparent relationships in the training data that do not hold in general. Validation data set : A validation data set is a data-set of examples used to tune the hyperparameters (i.e. the architecture) of a classifier. It is sometimes also called the development set or the "dev set". An example of a hyperparameter for artificial neural networks includes the number of hidden units in each layer. It, as well as the testing set (as mentioned below), should follow the same probability distribution as the training data set. In order to avoid overfitting, when any classification parameter needs to be adjusted, it is necessary to have a validation data set in addition to the training and test datasets. For example, if the most suitable classifier for the problem is sought, the training data set is used to train the different candidate classifiers, the validation data set is used to compare their performances and decide which one to take and, finally, the test data set is used to obtain the performance characteristics such as accuracy, sensitivity, specificity, F-measure, and so on. The validation data set functions as a hybrid: it is training data used for testing, but neither as part of the low-level training nor as part of the final testing. Test data set : A test data set is a data set that is independent of the training data set, but that follows the same probability distribution as the training data set. If a model fit to the training data set also fits the test data set well, minimal overfitting has taken place (see figure below). A better fitting of the training data set as opposed to the test data set usually points to over-fitting. A test set is therefore a set of examples used only to assess the performance (i.e. generalization) of a fully specified classifier. To do this, the final model is used to predict classifications of examples in the test set. Those predictions are compared to the examples' true classifications to assess the model's accuracy. In a scenario where both validation and test datasets are used, the test data set is typically used to assess the final model that is selected during the validation process. In the case where the original data set is partitioned into two subsets (training and test datasets), the test data set might assess the model only once (e.g., in the holdout method). Note that some sources advise against such a method. However, when using a method such as cross-validation, two partitions can be sufficient and effective since results are averaged after repeated rounds of model training and testing to help reduce bias and variability. 5. Explain Classification in Detail. Ans. Classification is a supervised machine learning method where the model tries to predict the correct label of a given input data. In classification, the model is fully trained using the training data, and then it is evaluated on test data before being used to perform prediction on new unseen data. For instance, an algorithm can learn to predict whether a given email is spam or ham (no spam), as illustrated below. Before diving into the classification concept, we will first understand the difference between the two types of learners in classification: lazy and eager learners. Then we will clarify the misconception between classification and regression. Lazy Learners Vs. Eager Learners : There are two types of learners in machine learning classification: lazy and eager learners. Eager learners are machine learning algorithms that first build a model from the training dataset before making any prediction on future datasets. They spend more time during the training process because of their eagerness to have a better generalization during the training from learning the weights, but they require less time to make predictions. Most machine learning algorithms are eager learners, and below are some examples: Logistic Regression. Support Vector Machine. Decision Trees. Artificial Neural Networks. Lazy learners or instance-based learners, on the other hand, do not create any model immediately from the training data, and this is where the lazy aspect comes from. They just memorize the training data, and each time there is a need to make a prediction, they search for the nearest neighbor from the whole training data, which makes them very slow during prediction. Some examples of this kind are: K-Nearest Neighbor. Case-based reasoning. However, some algorithms, such as BallTrees and KDTrees, can be used to improve the prediction latency. Machine Learning Classification Vs. Regression : There are four main categories of Machine Learning algorithms: supervised, unsupervised, semi-supervised, and reinforcement learning. Even though classification and regression are both from the category of supervised learning, they are not the same. The prediction task is a classification when the target variable is discrete. An application is the identification of the underlying sentiment of a piece of text. The prediction task is a regression when the target variable is continuous. An example can be the prediction of the salary of a person given their education degree, previous work experience, geographical location, and level of seniority. Examples of Machine Learning Classification in Real Life : Healthcare : Training a machine learning model on historical patient data can help healthcare specialists accurately analyze their diagnoses: During the COVID-19 pandemic, machine learning models were implemented to efficiently predict whether a person had COVID-19 or not. Researchers can use machine learning models to predict new diseases that are more likely to emerge in the future. Education : Education is one of the domains dealing with the most textual, video, and audio data. This unstructured information can be analyzed with the help of Natural Language technologies to perform different tasks such as: The classification of documents per category. Automatic identification of the underlying language of students' documents during their application. Analysis of students’ feedback sentiments about a Professor. Transportation : Transportation is the key component of many countries' economic development. As a result, industries are using machine and deep learning models: To predict which geographical location will have a rise in traffic volume. Predict potential issues that may occur in specific locations due to weather conditions. Sustainable agriculture : Agriculture is one of the most valuable pillars of human survival. Introducing sustainability can help improve farmers' productivity at a different level without damaging the environment: By using classification models to predict which type of land is suitable for a given type of seed. Predict the weather to help them take proper preventive measures. Different Types of Classification Tasks in Machine Learning : There are four main classification tasks in Machine learning: binary, multi-class, multi-label, and imbalanced classifications. Binary Classification : In a binary classification task, the goal is to classify the input data into two mutually exclusive categories. The training data in such a situation is labeled in a binary format: true and false; positive and negative; O and 1; spam and not spam, etc. depending on the problem being tackled. For instance, we might want to detect whether a given image is a truck or a boat. Logistic Regression and Support Vector Machines algorithms are natively designed for binary classifications. However, other algorithms such as K-Nearest Neighbors and Decision Trees can also be used for binary classification. Multi-Class Classification : The multi-class classification, on the other hand, has at least two mutually exclusive class labels, where the goal is to predict to which class a given input example belongs to. In the following case, the model correctly classified the image to be a plane. Most of the binary classification algorithms can be also used for multi-class classification. These algorithms include but are not limited to: Random Forest, Naive Bayes, K-Nearest Neighbors, Gradient Boosting, SVM, Logistic Regression. One-versus-one: this strategy trains as many classifiers as there are pairs of labels. If we have a 3-class classification, we will have three pairs of labels, thus three classifiers. One-versus-rest: at this stage, we start by considering each label as an independent label and consider the rest combined as only one label. With 3-classes, we will have three classifiers. Multi-Label Classification : In multi-label classification tasks, we try to predict 0 or more classes for each input example. In this case, there is no mutual exclusion because the input example can have more than one label. Such a scenario can be observed in different domains, such as auto-tagging in Natural Language Processing, where a given text can contain multiple topics. Similarly to computer vision, an image can contain multiple objects, as illustrated below: the model predicted that the image contains: a plane, a boat, a truck, and a dog. It is not possible to use multi-class or binary classification models to perform multi-label classification. However, most algorithms used for those standard classification tasks have their specialized versions for multi-label classification. Imbalanced Classification : For the imbalanced classification, the number of examples is unevenly distributed in each class, meaning that we can have more of one class than the others in the training data. Let’s consider the following 3-class classification scenario where the training data contains: 60% of trucks, 25% of planes, and 15% of boats. The imbalanced classification problem could occur in the following scenario: Fraudulent transaction detections in financial industries Rare disease diagnosis Customer churn analysis 6. Explain Regression in detail. Ans. Machine Learning Regression is a technique for investigating the relationship between independent variables or features and a dependent variable or outcome. It’s used as a method for predictive modelling in machine learning, in which an algorithm is used to predict continuous outcomes. Solving regression problems is one of the most common applications for machine learning models, especially in supervised machine learning. Algorithms are trained to understand the relationship between independent variables and an outcome or dependent variable. The model can then be leveraged to predict the outcome of new and unseen input data, or to fill a gap in missing data. What are the types of regression? There are a range of different approaches used in machine learning to perform regression. Different popular algorithms are used to achieve machine learning regression. The different techniques may include different numbers of independent variables or process different types of data. Distinct types of machine learning regression models may also assume a different relationship between the independent and dependent variables. For example, linear regression techniques assume that the relationship is linear, so wouldn’t be effective with datasets with nonlinear relationships. Some of the most common regression techniques in machine learning can be grouped into the following types of regression analysis: Simple Linear Regression Multiple linear regression Logistic regression Simple Linear Regression : Simple Linear regression is a linear regression technique which plots a straight line within data points to minimise error between the line and the data points. It is one of the most simple and basic types of machine learning regression. The relationship between the independent and dependent variables is assumed to be linear in this case. This approach is simple because it is used to explore the relationship between the dependent variable and one independent variable. Outliers may be a common occurrence in simple linear regression because of the straight line of best fit. Multiple Linear regression : Multiple linear regression is a technique used when more than one independent variable is used. Polynomial regression is an example of a multiple linear regression technique. It is a type of multiple linear regression, used when there is more than one independent variable. It achieves a better fit in the comparison to simple linear regression when multiple independent variables are involved. The result when plotted on two dimensions would be a curved line fitted to the data points. Logistic regression : Logistic regression is used when the dependent variable can have one of two values, such as true or false, or success or failure. Logistic regression models can be used to predict the probability of a dependent variable occurring. Generally, the output values must be binary. A sigmoid curve can be used to map the relationship between the dependent variable and independent variables. 7. Explain Decision tree in brief. Ans. A decision tree is a non-parametric supervised learning algorithm, which is utilized for both classification and regression tasks. It has a hierarchical, tree structure, which consists of a root node, branches, internal nodes and leaf nodes. As you can see from the diagram above, a decision tree starts with a root node, which does not have any incoming branches. The outgoing branches from the root node then feed into the internal nodes, also known as decision nodes. Based on the available features, both node types conduct evaluations to form homogenous subsets, which are denoted by leaf nodes, or terminal nodes. The leaf nodes represent all the possible outcomes within the dataset. As an example, let’s imagine that you were trying to assess whether or not you should go surf, you may use the following decision rules to make a choice: This type of flowchart structure also creates an easy to digest representation of decision-making, allowing different groups across an organization to better understand why a decision was made. Decision tree learning employs a divide and conquer strategy by conducting a greedy search to identify the optimal split points within a tree. This process of splitting is then repeated in a top-down, recursive manner until all, or the majority of records have been classified under specific class labels. Whether or not all data points are classified as homogenous sets is largely dependent on the complexity of the decision tree. Smaller trees are more easily able to attain pure leaf nodes—i.e. data points in a single class. However, as a tree grows in size, it becomes increasingly difficult to maintain this purity, and it usually results in too little data falling within a given subtree. When this occurs, it is known as data fragmentation, and it can often lead to overfitting. As a result, decision trees have preference for small trees, which is consistent with the principle of parsimony in Occam’s Razor; that is, “entities should not be multiplied beyond necessity.” Said differently, decision trees should add complexity only if necessary, as the simplest explanation is often the best. To reduce complexity and prevent overfitting, pruning is usually employed; this is a process, which removes branches that split on features with low importance. The model’s fit can then be evaluated through the process of cross-validation. Another way that decision trees can maintain their accuracy is by forming an ensemble via a random forest algorithm; this classifier predicts more accurate results, particularly when the individual trees are uncorrelated with each other. 8. How does the Decision Tree algorithm Work ? Explain. Ans. In a decision tree, for predicting the class of the given dataset, the algorithm starts from the root node of the tree. This algorithm compares the values of root attribute with the record (real dataset) attribute and, based on the comparison, follows the branch and jumps to the next node. For the next node, the algorithm again compares the attribute value with the other sub-nodes and move further. It continues the process until it reaches the leaf node of the tree. The complete process can be better understood using the below algorithm: Step-1: Begin the tree with the root node, says S, which contains the complete dataset. Step-2: Find the best attribute in the dataset using Attribute Selection Measure (ASM). Step-3: Divide the S into subsets that contains possible values for the best attributes. Step-4: Generate the decision tree node, which contains the best attribute. Step-5: Recursively make new decision trees using the subsets of the dataset created in step -3. Continue this process until a stage is reached where you cannot further classify the nodes and called the final node as a leaf node. Attribute Selection Measures : While implementing a Decision tree, the main issue arises that how to select the best attribute for the root node and for sub-nodes. So, to solve such problems there is a technique which is called as Attribute selection measure or ASM. By this measurement, we can easily select the best attribute for the nodes of the tree. There are two popular techniques for ASM, which are: Information Gain Gini Index 1. Information Gain: Information gain is the measurement of changes in entropy after the segmentation of a dataset based on an attribute. It calculates how much information a feature provides us about a class. According to the value of information gain, we split the node and build the decision tree. A decision tree algorithm always tries to maximize the value of information gain, and a node/attribute having the highest information gain is split first. It can be calculated using the below formula: ➡️ Information Gain= Entropy(S)- [(Weighted Avg) *Entropy(each feature) 2. Gini Index: Gini index is a measure of impurity or purity used while creating a decision tree in the CART(Classification and Regression Tree) algorithm. An attribute with the low Gini index should be preferred as compared to the high Gini index. It only creates binary splits, and the CART algorithm uses the Gini index to create binary splits. Gini index can be calculated using the below formula: ➡️ Gini Index= 1- ∑jPj2 9. Explain advantages and disadvantages of Decision Tree. Ans. Advantages of the Decision Tree : It is simple to understand as it follows the same process which a human follow while making any decision in real-life. It can be very useful for solving decision-related problems. It helps to think about all the possible outcomes for a problem. There is less requirement of data cleaning compared to other algorithms. Disadvantages of the Decision Tree : The decision tree contains lots of layers, which makes it complex. It may have an overfitting issue, which can be resolved using the Random Forest algorithm. For more class labels, the computational complexity of the decision tree may increase.
- E-Commerce & SEO Technology Lab Manual BCA Sem-5
Subject: E-Commerce & SEO Technology Lab Manual BCA Sem-5 EXPERIMENT: 1 Aim: SEO Tasks :On page SEO and one time tasks On Page SEO Elements: Keyword Research, Title Tags, Meta tags, ALT tags, Header Tags (H1,H2), URL Structure, Internal Linking, Description: It shows the on Page SEO elements. ➡️ Steps: 1. Identify Target Keywords: Target keywords—i.e., relevant search queries—are crucial to on-page optimization. After all, the goal is to rank for relevant keywords and become more visible in search results. Perform keyword research to find what words and phrases people use to find pages like yours. Those data points include: Intent: The type of search intent or motivation behind each search Volume: Keyword search volume, the average number of monthly searches KD%: Keyword difficulty, a measure of how hard it will be to rank in the top 10 unpaid Google results 2. Optimize the Title Tag : The title tag is the page title that appears in the SERP. It should tell Google what your page is about. And entice users to click through. The title tag is one of the most important elements for on-page optimization. So make sure to include the page’s primary keyword (the main search term you want to rank for). Ideally, at the start. Tip: SEMrush's On Page SEO Checker checks your title tag for target keywords and keyword stuffing. Also, aim for a title tag length of 50 to 60 characters (including spaces). 3. Write a Meta Description That Boosts Clicks : The meta description is the page description that appears in the SERP. The meta description isn’t a direct ranking factor. It’s part of this on-page optimization checklist because it’s key to standing out on the SERP and attracting more clicks. Use it to explain what the user will get from your page and why it’s worth visiting. And make sure it includes your primary keyword. Note: Google may generate its own title tags and meta descriptions for your pages. Optimizing them can reduce the risk of this happening. We recommend sticking to a maximum of 120 characters (including spaces) for your meta descriptions. This reduces the risk of Google truncating them in desktop and mobile SERPs. Tip: SEMrush's On Page SEO Checker will check your meta description for target keywords and keyword stuffing. It will also flag if Google is rewriting your description in the search results. 4. Write Your Headline in an H1 Tag : Every page should have one H1 tag that contains the on-page title (or headline). It’s one of the simplest yet important tasks in this on-page SEO checklist. The H1 differs from a title tag because the H1 appears on your page. Not the SERP. The H1 tag should be similar to the title tag. As it’s also there to tell Google and users what the page is about. However, there’s rarely a character limit here. Just focus on creating an H1 that makes sense on your page and encourages visitors to stay. And include your primary keyword, at least. Tip: SEMrush's On Page SEO Checker checks your H1 tag for target keywords and keyword stuffing. 5. Check the URL Slug: The URL slug should be concise, clear, and descriptive. Here are some tips to keep in mind: Consider using your page’s primary keyword as the URL slug Separate words using a hyphen (“-”) Avoid mentioning years that might change (e.g., “best-headphones-2023”) If you change your URL slug, make sure to redirect the old version Check out our dedicated guide for more advice on creating SEO-friendly URLs. 6. Improve Navigation with Internal Links: Internal links are links between pages on your site. They help Google and users to find their way around. For example, Soak&Sleep has internal links to its “single duvets” and “single mattresses” categories in its “single bedding” page description. Notice how these internal links are attached to descriptive anchor text—not generic text like “Click here.” This helps Google (and users) understand what the linked page is about. Tip: Working on informational pages? Consider adding external links to your on-page optimization checklist as well. Linking out to high-quality resources indicates that you’ve done your research and have readers’ best interests in mind. Post Practical Questions: 1. Which of the following is NOT an on-page SEO task? ➡️ E (A) Keyword research (B) Title tags (C) Meta tags (D) ALT tags (E) Off-page SEO 2. Which of the following is the most important on-page SEO task? ➡️ B (A) Keyword research (B) Title tags (C) Meta tags (D) ALT tags (E) Header tags EXPERIMENT : 2 Aim: SEO Tasks : On page SEO and one time tasks On Page SEO Elements: Relevant keywords in inbound link, Content, Keyword density, Site Maps, Robots.txt, usability. ➡️ Steps: 1. Content: The content of a site must contain keywords chosen for a particular web page. These could be targeted keywords or long tail keywords or synonyms. Just make sure the keyword density is not too high, which means use them only when they make sense to the human reader. Explanation: It is often a best practice to keep your content more than 500 or 1000 words on the website as search engines love longer content. But that does not mean that you have to turn your business website into a blog with fillers everywhere. Keep your content length as long as possible but also at the same time take care that the readers get exactly what information they need without having to scroll through a long essay. If you see this research about content length affecting SERPs, you will find that the threshold is higher. But we are sure Google knows the difference between a blog and a business website while ranking them on this particular signal. This is what Google has to say about avoiding thin content, just to make things clearer. As far as, keyword density is concerned ther is no exact number to define it but all you need to know is in your average two to four paragraph content on a webpage, use keywords whenever they are relevant to the human reader. To know more about keyword density we recommend you watch this video from Google engineer Matt Cutts who talks about ideal keyword density. You can always use latent semantic indexing keywords that search engines also use to analyze the relevancy of your content to your target keywords. Read more about latent semantic indexing keywords. 2. Site Maps: Every site must have a sitemap. However, even if sites don't have one, they get indexed by search engines. The presence of  a sitemap makes it a tad easier to find and index pages, for the search engines. Explanation: A sitemap helps tell the search engines two important things: the location of all the internal links and the priority of different pages in a website. The former improves indexing of all internal pages hence paving way to search engine visibility to internal pages while the latter helps understand the information architecture. A sitemap location can also be specified in robots.txt file, which is usually the first file a search engine crawler looks for while crawling a site. Learn more about XML Sitemaps. 3. Robots.txt : Robots.txt is a file which, if present, on your website is the first file to be crawled by search engines. This contains information about pages that should not be indexed. It generally consists of information for search engines to guide them to crawl and index the site efficiently, including the sitemap location. Explanation: The presence of robots.txt does not directly affect your website's SEO. If you do have a robots.txt, make sure that no page that you want to be indexed, is blocked. If you have crawling issues reported on Google Search Console, make sure you double check your robots.txt file. Also, to increase the crawl rate of search engine bots, you can avoid unnecessary pages from being indexed by specifying them on your site's robots.txt file. Learn more from the Beginners Guide for Robots.txt. 4. Usability: Usability is a ranking factor for search engines and is controlled by on page elements. Explanation: Apart from the answers to the above questions there are more factors that affect the usability of a site. How a certain search engine user engages with the link that is returned in search is taken into consideration. For instance, image that you are a searcher and you click on a link and immediately click the back button. Your  engagement with that site is poor. This may be due to poor user-experience and such engagement metrics may cause lowering of search ranking. 5. Keyword Density: Keyword density is the proportion of times a term or phrase occurs on a web page. Search engines may mistake the keyword frequency for term stuffing when the keyword frequency is significantly over the optimal level. Consequently, we must ensure that the keyword density for any significant or secondary search keywords is not excessive. For example, if a term occurs five times in a 200-word piece, the density is 2.5 percent. Although there is no perfect keyword density, 3–4% is recommended practice for SEO. 6. Inbound Links : Inbound links, also known as backlinks, occur when another website links back to your site. Google views inbound links as an indicator that your site has high-quality content, making these links one of the most important elements in search engine optimization (SEO). In the early days of SEO, inbound links were merely a numbers game; the sites with the most links ranked the highest in the search results. This eventually led to people using spammy link building techniques to put their websites ahead of the competition, forcing Google to rethink how their algorithms responded to inbound links. Post Practical Questions: 1. What is On page SEO? ➡️ On-page SEO (sometimes called on-site SEO) is the process of optimizing parts of your webpages so they rank higher on search engines and get more search engine traffic. This includes updating on-page content, title tags, internal links, and more. Search engines like Google look at keywords and other on-page SEO cues to check whether a page matches a user’s search intent. And if the search engine decides the page will be useful to the user, it will display it higher in search results. 2.Which of the following is NOT an on-page SEO element? ➡️ (A) Relevant keywords in inbound links (B) Content (C) Keyword density (D) Site Maps (E) Robots.txt EXPERIMENT : 3 Aim: SEO Tasks : Off page SEO and Perpetual tasks: Profile Creation , Social Sharing ,Social Book-marking , Block Posting ,Image Sharing , Forum Comment. Description: It contains the off page SEO tasks ➡️ Steps: 1. Profile Creation: The process of creating a profile in SEO, or search engine optimization, typically involves several steps. These steps include conducting keyword research, optimizing website content, building backlinks, and monitoring and analyzing website traffic. First, keyword research is conducted to identify the most relevant and high-traffic keywords for a website. This can be done using tools like Google AdWords Keyword Planner or SEMrush. These tools allow you to enter a website or keyword and see the search volume, competition, and related keywords for that term. Once the keywords have been identified, the next step is to optimize the website content for those keywords. This involves incorporating the keywords in the title tags, meta descriptions, header tags, and throughout the website content. Building backlinks is another important step in the profile creation process. Backlinks are links from other websites to your website. The more backlinks a website has, the higher it will rank in search engine results. Backlinks can be built through a variety of methods, including guest blogging, social media, and outreach. Finally, monitoring and analyzing website traffic is important to track the effectiveness of the SEO campaign. This can be done using tools like Google Analytics or SEMrush. These tools allow you to track website traffic, bounce rate, and conversions. By following these steps, you can create a strong SEO profile for your website and improve your search engine rankings. 2. Social Book-Marking : Social bookmarking is a method of saving and organizing web pages or other digital content that you want to keep track of, and then sharing those bookmarks with others. In terms of SEO, social bookmarking can be beneficial because it can help to increase the visibility and exposure of your website or content. When you submit a webpage or blog post to a social bookmarking site, other users may see it and decide to share it with their own followers, which can lead to more backlinks and more traffic to your site. Additionally, many social bookmarking sites use tagging or categorization systems, which can help to optimize your content for specific keywords. 3. Social Sharing : Definition: Social sharing describes when social media users broadcast web content on a social network to their connections, groups, or specific individuals. One of the primary aims of corporate social media marketing strategies is to generate brand awareness by leveraging their existing audience to share content. Social sharing and brand : Beyond product recommendations and sales or promotions, social sharing is also a critical place to define a brand. Consumers don't only visit a company's website to understand who they are and what they offer — they also go to their Facebook Page or Twitter feed. Social media gives businesses a chance to define what they stand for, what they are trying to achieve, and how it helps the community. Social media is much more interactive than a website. Seeing how a company engages with its customers is more substantive than simply making a website claim. Most importantly, when users share a company's posts or content, it validates them in the eyes of consumers. Social proof is invaluable for a business' reputation and has the tendency to increase exponentially when a foundation is established. 4. Block Posting: Simply put, content blocks are building blocks used to integrate different forms of content to a webpage or blog post, adding functionality and visual appeal. Content blocks can be anything from plain text and images to call-to-action buttons and event count-down clocks. If you’ve ever worked on or run your own website, you’re probably already familiar with popular block-based blog builders like Elementor, Gutenberg, or Visual Composer. With these editors, each piece of content on the page–from video embeds to introductory paragraphs–is made of a different block that you can re-arrange within your post by dragging and dropping. Page builders offer several default blocks like a paragraph, heading, button, list, etc. but you can also add new blocks by installing block plugins. 5. Image Sharing : Image sharing can be beneficial for SEO in several ways. First, it can help to increase the number of backlinks to your website, which can help to improve your search engine rankings. Additionally, images can help to break up text on a webpage and make it more visually appealing, which can help to keep visitors on your site for longer and reduce bounce rates. To share images for SEO, you can use a variety of methods. One of the most popular is to use social media platforms like Instagram, Pinterest, and Flickr to share your images and include a link back to your website. Additionally, you can use image sharing websites like Imager and imgbb to share your images and include a link back to your website. It's also important to optimize your images for SEO by including relevant keywords in the file name, alt tags, and captions. This will help search engines to understand the context of your images and display them in relevant search results. It's also a good idea to make sure that your images are compressed, so they load quickly on your website, which can help to improve the user experience and reduce bounce rates. 6. Forum Comment: Forum posting refers to generating quality inbound links by participating in online discussion forums. It allows you to post new posts and reply to old ones to drive traffic to your site. There are a number of forum websites which offer a platform for online discussion, i.e. message board, discussion groups, discussion forums and bulletin boards are some of the popular types of forum websites. You need to sign up on these websites only then you can submit topics for discussion. Post Practical Questions: Q. 1 Explain Social Book Marking? ➡️ Social bookmarking is a method of saving and organizing web pages or other digital content that you want to keep track of, and then sharing those bookmarks with others. In terms of SEO, social bookmarking can be beneficial because it can help to increase the visibility and exposure of your website or content. When you submit a webpage or blog post to a social bookmarking site, other users may see it and decide to share it with their own followers, which can lead to more backlinks and more traffic to your site. Additionally, many social bookmarking sites use tagging or categorization systems, which can help to optimize your content for specific keywords. EXPERIMENT: 4 Aim: SEO Tasks : Off page SEO and Perpetual tasks: Document Comment ,Question Answer Posting ,Blog Comment , Directory Submission , Article Bookmarking ,Content Sharing Steps: 1. Blog Comment: Blog commenting in an off-page SEO type isn’t as popular as it once was, but it’s still a terrific strategy to improve traffic and obtain more backlinks. Keep in mind that blogs are still a popular resource for those wanting to learn about what matters most in their field while looking for sites to comment on. When you write blog comments on high-authority websites, you improve the chances that they will accept a link back to your site. However, you must leave only useful blog comments or risk losing the trust of your followers. Guest blogging is another method for increasing traffic to your website. 2. Directory Submission: Another popular off-page SEO tactic that will be present in 2022 is blog directory submissions. You may acquire backlinks and enhance traffic to your website by submitting your blog to these directories. When submitting your blog to these directories, keep in mind that if they approve your blog for inclusion in their directory, you will need to supply some information about your blog for them to post. There are no actual disadvantages to submitting your blog to a directory. Remember that it may take some time for the moderator to approve your blog, so be patient! Submit your blog to directories to improve blog traffic and receive backlinks. 3. Questions & Answers Posting: Query and answer sites, like article directories, require you to submit your question or response. The primary distinction is that you now have the option of including a link at the conclusion of your submission! Many individuals who use these websites are looking for answers about specific topics, which helps you to increase traffic to your website by contributing information. You have to select a question or response pertaining to your expertise and offer further information. If you can think of anything to ask, question and answer sites are wonderful for growing your website traffic! 4. Document Comment: Off-page SEO is all about getting your material out there on the internet and into people’s lives. You may share a superb document with others who do not have access to the original. 5. Article Bookmarking: Another prevalent off-page SEO type or technique that will stay popular in 2022 is article submission. You might want to think about employing article submission platforms to increase the visibility of your company and website. Several article submission websites are accessible for usage; however, not all of them regularly accept fresh articles. You should publish your content to a variety of directories, including high-quality directories that will undoubtedly be prominent in 2022. When submitting an article to these sites, make sure to add at least one backlink to your website. This will give your company more exposure and enhance the probability that people will visit it! 6. Content Sharing: SEO content is online content designed to rank in search engines (like Google). Also, content written for SEO is typically optimized around a specific keyword. And when it comes to search engine optimization, make no mistake: Content is KEY. In fact, HubSpot reports that businesses that regularly publish blog posts get 350% more traffic than those that don’t publish content on a regular basis. Post Practical Questions: 1. Explain article bookmarking? ➡️ There are many SEO benefits to social bookmarking. Search engine algorithms scour through the bookmarked websites and make a link to be indexed. This helps websites earn credibility points from search engines and get better rankings. EXPERIMENT: 5 Aim: Study about Free SEO Tools: Keyword Suggestion Tool Keyword List Generator Keyword List Cleaner Robots. Text Tools Meta Tag Generator Server Header Checker Link Suggestion Tool Spider Test Tool Keyword Density Analyzer Page Comparison Tool Ad Group Generator Keyword Wrapper Typo Generator Description: Study about free SEO tools Steps: WORKING
- Android Assignment-2 BCA Sem-5
Subject: Android Assignment-2 Unit: 2 Android Application Basics BCA Semester: 5 1. Write a note on android life cycle. Ans. Android Activity Lifecycle is controlled by 7 methods of android.app.Activity class. The android Activity is the subclass of ContextThemeWrapper class. An activity is the single screen in android. It is like window or frame of Java. By the help of activity, you can place all your UI components or widgets in a single screen. The 7 lifecycle method of Activity describes how activity will behave at different states. Android Activity Lifecycle methods File: activity_main.xml Android Activity Lifecycle Example File: MainActivity.java package example.javatpoint.com.activitylifecycle; import android.app.Activity; import android.os.Bundle; import android.util.Log; public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Log.d("lifecycle","onCreate invoked"); } @Override protected void onStart() { super.onStart(); Log.d("lifecycle","onStart invoked"); } @Override protected void onResume() { super.onResume(); Log.d("lifecycle","onResume invoked"); } @Override protected void onPause() { super.onPause(); Log.d("lifecycle","onPause invoked"); } @Override protected void onStop() { super.onStop(); Log.d("lifecycle","onStop invoked"); } @Override protected void onRestart() { super.onRestart(); Log.d("lifecycle","onRestart invoked"); } @Override protected void onDestroy() { super.onDestroy(); Log.d("lifecycle","onDestroy invoked"); } } Output: You will not see any output on the emulator or device. You need to open logcat. 2. Explain Manifest File in detail. Ans. Every project in Android includes a Manifest XML file, which is AndroidManifest.xml, located in the root directory of its project hierarchy. The manifest file is an important part of our app because it defines the structure and metadata of our application, its components, and its requirements. This file includes nodes for each of the Activities, Services, Content Providers, and Broadcast Receivers that make the application, and using Intent Filters and Permissions determines how they coordinate with each other and other applications. The manifest file also specifies the application metadata, which includes its icon, version number, themes, etc., and additional top-level nodes can specify any required permissions, and unit tests, and define hardware, screen, or platform requirements. The manifest comprises a root manifest tag with a package attribute set to the project’s package. It should also include an xmls:android attribute that will supply several system attributes used within the file. We use the versionCode attribute is used to define the current application version in the form of an integer that increments itself with the iteration of the version due to update. Also, the versionName attribute is used to specify a public version that will be displayed to the users. We can also specify whether our app should install on an SD card of the internal memory using the install Location attribute. A typical manifest file looks as: XML Code: A manifest file includes the nodes that define the application components, security settings, test classes, and requirements that make up the application. Some of the manifest sub-node tags that are mainly used are: 1. manifest: The main component of the AndroidManifest.xml file is known as manifest. Additionally, the packaging field describes the activity class’s package name. It must contain an element with the xmlns:android and package attribute specified. XML CODE: 2. uses-sdk : It is used to define a minimum and maximum SDK version by means of an API Level integer that must be available on a device so that our application functions properly, and the target SDK for which it has been designed using a combination of minSdkVersion, maxSdkVersion, and targetSdkVersion attributes, respectively. It is contained within the element. XML Code: 3. uses-permission : It outlines a system permission that must be granted by the user for the app to function properly and is contained within the element. When an application is installed (on Android 5.1 and lower devices or Android 6.0 and higher), the user must grant the application permissions. XML Code: 4. application : A manifest can contain only one application node. It uses attributes to specify the metadata for your application (including its title, icon, and theme). During development, we should include a debuggable attribute set to true to enable debugging, then be sure to disable it for your release builds. The application node also acts as a container for the Activity, Service, Content Provider, and Broadcast Receiver nodes that specify the application components. The name of our custom application class can be specified using the android:name attribute. XML Code: 5. uses-library : It defines a shared library against which the application must be linked. This element instructs the system to add the library’s code to the package’s class loader. It is contained within the element. XML Code: 6. activity : The Activity sub-element of an application refers to an activity that needs to be specified in the AndroidManifest.xml file. It has various characteristics, like label, name, theme, launchMode, and others. In the manifest file, all elements must be represented by . Any activity that is not declared there won’t run and won’t be visible to the system. It is contained within the element. XML Code: 7. intent-filter : It is the sub-element of activity that specifies the type of intent to which the activity, service, or broadcast receiver can send a response. It allows the component to receive intents of a certain type while filtering out those that are not useful for the component. The intent filter must contain at least one element. XML Code: 8. action : It adds an action for the intent-filter. It is contained within the element. XML Code: 9. category : It adds a category name to an intent-filter. It is contained within the element. XML Code: 10. uses-configuration : The uses-configuration components are used to specify the combination of input mechanisms that are supported by our application. It is useful for games that require particular input controls. XML Code: 11. uses-features : It is used to specify which hardware features your application requires. This will prevent our application from being installed on a device that does not include a required piece of hardware such as NFC hardware, as follows: XML Code: 12. permission : It is used to create permissions to restrict access to shared application components. We can also use the existing platform permissions for this purpose or define your own permissions in the manifest. XML Code: 3. Explain any 10 different types of resources file andriod. Ans. 1. Bool : A Boolean value defined in XML. file location:res/values/filename.xml The filename is arbitrary. The element's name is used as the resource ID. resource reference: In Java: R.bool.bool_name In XML: @[package:]bool/bool_name Syntax: [true | false] 2. Color : A color value defined in XML. The color is specified using an RGB value and alpha channel. You can use a color resource any place that accepts a hexadecimal color value. You can also use a color resource when a drawable resource is expected in XML, such as android:drawable="@color/green". file location: res/values/colors.xml The filename is arbitrary. The element's name is used as the resource ID. resource reference: In Java: R.color.color_name In XML: @[package:]color/color_name syntax: hex_color 3. Dimension : A dimension value defined in XML. A dimension is specified with a number followed by a unit of measure, such as 10px, 2in, or 5sp. The following units of measure are supported by Android: dp : Density-independent pixels: an abstract unit that is based on the physical density of the screen. These units are relative to a 160 dpi (dots per inch) screen, on which 1 dp is roughly equal to 1 px. When running on a higher density screen, the number of pixels used to draw 1 dp is scaled up by a factor appropriate for the screen's dpi. sp: Scale-independent Pixels - This is like the dp unit, but it is also scaled by the user's font size preference. It is recommend you use this unit when specifying font sizes, so they will be adjusted for both the screen density and the user's preference. pt: Points: 1/72 of an inch based on the physical size of the screen, assuming a 72 dpi density screen. px: Pixels: corresponds to actual pixels on the screen. We don't recommend using this unit, because the actual representation can vary across devices. Different devices can have a different number of pixels per inch and might have more or fewer total pixels available on the screen. mm: Millimeters: based on the physical size of the screen. in: Inches: based on the physical size of the screen. file location: res/values/filename.xml The filename is arbitrary. The element's name is used as the resource ID. resource reference: In Java: R.dimen.dimension_name In XML: @[package:]dimen/dimension_name syntax: dimension 4. ID : A unique resource ID defined in XML. Using the name you provide in the element, the Android developer tools create a unique integer in your project's R.java class, which you can use as an identifier for an application resources, such as a View in your UI layout, or a unique integer for use in your application code, such as an ID for a dialog or a result code. file location:res/values/filename.xml The filename is arbitrary. resource reference: In Java: R.id.name In XML: @[package:]id/name syntax: 5. Integer : An integer defined in XML. file location: res/values/filename.xml The filename is arbitrary. The element's name is used as the resource ID. resource reference: In Java: R.integer.integer_name In XML: @[package:]integer/integer_name syntax: integer 6. Integer array : An array of integers defined in XML. file location: res/values/filename.xml The filename is arbitrary. The element's name is used as the resource ID. compiled resource datatype: Resource pointer to an array of integers. resource reference: In Java: R.array.integer_array_name In XML: @[package:]array/integer_array_name syntax: integer 7. Typed array : A TypedArray defined in XML. You can use this to create an array of other resources, such as drawables. The array isn't required to be homogeneous, so you can create an array of mixed resource types, but be aware of what and where the data types are in the array so that you can properly obtain each item with the TypedArray class's get...() methods. file location: res/values/filename.xml The filename is arbitrary. The element's name is used as the resource ID. compiled resource datatype: Resource pointer to a TypedArray. resource reference: In Java: R.array.array_name In XML: @[package:]array/array_name syntax: resource 8. Layout resource: A layout resource defines the architecture for the UI in an Activity or a component of a UI. file location: res/layout/filename.xml The filename is used as the resource ID. compiled resource datatype: Resource pointer to a View (or subclass) resource reference: In Java: R.layout.filename In XML: @[package:]layout/filename syntax: 9. String: A single string that can be referenced from the application or from other resource files (such as an XML layout). file location: res/values/filename.xml The filename is arbitrary. The element's name is used as the resource ID. compiled resource datatype: Resource pointer to a String. resource reference: In Java: R.string.string_name In XML: @string/string_name syntax: text_string 10. Style resource : A style resource defines the format and look for a UI. A style can be applied to an individual View (from within a layout file) or to an entire Activity or application (from within the manifest file). file location: res/values/filename.xml The filename is arbitrary. The element's name will be used as the resource ID. resource reference: In XML: @[package:]style/style_name syntax: 4. Explain Menu and Scroll View. Ans. Android Menus: In android, Menu is an important part of the UI component which is used to provide some common functionality around the application. With the help of menu, users can experience a smooth and consistent experience throughout the application. In order to use menu, we should define it in a separate XML file and use that file in our application based on our requirements. Also, we can use menu APIs to represent user actions and other options in our android application activities. How to define Menu in XML File? Android Studio provides a standard XML format for the type of menus to define menu items. We can simply define the menu and all its items in XML menu resource instead of building the menu in the code and also load menu resource as menu object in the activity or fragment used in our android application. Here, we should create a new folder menu inside of our project directory (res/menu) to define the menu and also add a new XML file to build the menu with the following elements. Below is the example of defining a menu in the XML file (menu_example.xml). Way to create menu directory and menu resource file: To create the menu directory just right-click on res folder and navigate to res->New->Android Resource Directory. Give resource directory name as menu and resource type also menu. one directory will be created under res folder. To create xml resource file simply right-click on menu folder and navigate to New->Menu Resource File. Give name of file as menu_example. One menu_example.xml file will be created under menu folder. It is the root element that helps in defining Menu in XML file and it also holds multiple elements. It is used to create a single item in the menu. It also contains nested element in order to create a submenu. It is optional and invisible for elements to categorize the menu items so they can share properties like active state, and visibility. activity_main.xml : If we want to add a submenu in menu item, then we need to add a element as the child of an . Below is the example of defining a submenu in a menu item. XML Code: Android Different Types of Menus : In android, we have three types of Menus available to define a set of options and actions in our android applications. The Menus in android applications are the following: Android Options Menu Android Context Menu Android Popup Menu Android Options Menu is a primary collection of menu items in an android application and is useful for actions that have a global impact on the searching application. Android Context Menu is a floating menu that only appears when the user clicks for a long time on an element and is useful for elements that affect the selected content or context frame. Android Popup Menu displays a list of items in a vertical list which presents the view that invoked the menu and is useful to provide an overflow of actions related to specific content. Android Scroll View : ScrollView is a view group that we can use to create vertically scrollable views. There is only one direct child in a scroll view. Because a ScrollView can only scroll vertically, you'll need to use a Horizontal Scroll View to create a horizontally scrollable view. The ScrollView tag is used to create a Scroll View in an android application. For example: In the above example, Scroll View has one child, which is a TextView widget. Here the android:orientation of the Text View widget is set to vertical. It defines whether to display child views in a row or column. Attributes of Scroll View : Following are some of the important attributes of a Scroll View: android:id: A Unique id to identify any widget android:layout_width: It defines the width of the layout android:layout_height: It sets the layout's height android:layout_marginStart: The amount of space needed at the start of the widget android:layout_marginEnd: It represents the amount of space needed on the End of the widget android:inputType: This allows you to define the input method's behaviour android:text: Specifies the default text displayed in the field app:layout_constraintTop_toTopOf: Align the desired view's top with the top of another Horizontal Scroll View : Horizontal Scroll View is used to add horizontal scroll ability in an android application. We can use the Horizontal Scroll View tag to create the same. 5. Working with permissions android explain? Ans. Restricted data, such as system state and users' contact information Restricted actions, such as connecting to a paired device and recording audio Workflow for using permissions : If your app offers functionality that might require access to restricted data or restricted actions, determine whether you can get the information or perform the actions without needing to declare permissions. You can fulfill many use cases in your app, such as taking photos, pausing media playback, and displaying relevant ads, without needing to declare any permissions. Types of permissions : Android categorizes permissions into different types, including install-time permissions, runtime permissions, and special permissions. Each permission's type indicates the scope of restricted data that your app can access, and the scope of restricted actions that your app can perform, when the system grants your app that permission. The protection level for each permission is based on its type and is shown on the permissions API reference page. Install-time permissions: Install-time permissions give your app limited access to restricted data or let your app perform restricted actions that minimally affect the system or other apps. When you declare install-time permissions in your app, an app store presents an install-time permission notice to the user when they view an app's details page, as shown in figure 2. The system automatically grants your app the permissions when the user installs your app. Normal permissions: These permissions allow access to data and actions that extend beyond your app's sandbox but present very little risk to the user's privacy and the operation of other apps. The system assigns the normal protection level to normal permissions. Signature permissions: The system grants a signature permission to an app only when the app is signed by the same certificate as the app or the OS that defines the permission. Runtime permissions: Runtime permissions, also known as dangerous permissions, give your app additional access to restricted data or let your app perform restricted actions that more substantially affect the system and other apps. Therefore, you need to request runtime permissions in your app before you can access the restricted data or perform restricted actions. Don't assume that these permissions have been previously granted—check them and, if needed, request them before each access. Special permissions: Special permissions correspond to particular app operations. Only the platform and OEMs can define special permissions. Additionally, the platform and OEMs usually define special permissions when they want to protect access to particularly powerful actions, such as drawing over other apps. Permission groups: Permissions can belong to permission groups. Permission groups consist of a set of logically related permissions. For example, permissions to send and receive SMS messages might belong to the same group, as they both relate to the application's interaction with SMS.
- Android Lab Manual Sem-5 BCA
Subject - Android Semester - 5 BCA Table Of Content (Click to View) Experiment: 1 Experiment: 2 Experiment: 3 Experiment: 4 Experiment: 5 Experiment: 6 Experiment: 7 Experiment: 8 Experiment: 9 Experiment: 10 Experiment- 1 Aim: Create a Program of Activity Lifecycle? Description: It shows the actual features of Android activity lifecycle goes through six major lifecycle stages or callbacks. These are: onCreate() , onStart() , onResume() , onPause() , onStop() , and onDestroy() . Steps: 1. onCreate(): import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.Toast; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Bundle containing previous frozen state setContentView(R.layout.activity_main); // The content view pointing to the id of layout // in the file activity_main.xml Toast toast = Toast.makeText(getApplicationContext(), "onCreate Called", Toast.LENGTH_LONG).show(); } } 2. onStart(): import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.Toast; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Bundle containing previous frozen state setContentView(R.layout.activity_main); // The content view pointing to the id of layout // in the file activity_main.xml Toast toast = Toast.makeText(getApplicationContext(), "onCreate Called", Toast.LENGTH_LONG).show(); } protected void onStart() { // It will show a message on the screen // then onStart is invoked Toast toast = Toast.makeText(getApplicationContext(), "onStart Called", Toast.LENGTH_LONG).show(); } } 3. onResume(): import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.Toast; import com.example.share.R; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { // Bundle containing previous frozen state super.onCreate(savedInstanceState); // The content view pointing to the id of layout // in the file activity_main.xml setContentView(R.layout.activity_main); Toast toast = Toast.makeText(getApplicationContext(), "onCreate Called", Toast.LENGTH_LONG).show(); } protected void onResume() { // It will show a message on the screen // then onResume is invoked Toast toast = Toast.makeText(getApplicationContext(), "onResume Called", Toast.LENGTH_LONG).show(); } } 4. onPause(): import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.Toast; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { // Bundle containing previous frozen state super.onCreate(savedInstanceState); // The content view pointing to the id of layout // in the file activity_main.xml setContentView(R.layout.activity_main); Toast toast = Toast.makeText(getApplicationContext(), "onCreate Called", Toast.LENGTH_LONG).show(); } protected void onPause() { // It will show a message on the screen // then onPause is invoked Toast toast = Toast.makeText(getApplicationContext(), "onPause Called", Toast.LENGTH_LONG).show(); } } 5. onStop(): import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.Toast; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { // Bundle containing previous frozen state super.onCreate(savedInstanceState); // The content view pointing to the id of layout // in the file activity_main.xml setContentView(R.layout.activity_main); Toast toast = Toast.makeText(getApplicationContext(), "onCreate Called", Toast.LENGTH_LONG).show(); } protected void onStop() { // It will show a message on the screen // then onStop is invoked Toast toast = Toast.makeText(getApplicationContext(), "onStop Called", Toast.LENGTH_LONG).show(); } } 6. onDestroy(): import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.Toast; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { // Bundle containing previous frozen state super.onCreate(savedInstanceState); // The content view pointing to the id of layout // in the file activity_main.xml setContentView(R.layout.activity_main); Toast toast = Toast.makeText(getApplicationContext(), "onCreate Called", Toast.LENGTH_LONG).show(); } protected void onDestroy() { // It will show a message on the screen // then onDestroy is invoked Toast toast = Toast.makeText(getApplicationContext(), "onDestroy Called", Toast.LENGTH_LONG).show(); } } Post Practical Questions: 1. Android system initiates its program within an Activity starting with a call on ? ➡️ C a) offCreate() callback b) onDrop() callback c) onCreate() callback 2.Which callback is called when the activity becomes visible to the user? ➡️ B a) onCreate() b) onStart() c) onResume() 3. Which callback is called when the activity is no longer visible? ➡️ B a) onRestart() b) onStop() c) onPause() 4. Which callback is called when the activity restarts after stopping it? ➡️ A a) onRestart() b) onPause() c) onStart() EXPERIMENT: 2 Aim: Create a program in Context and show different color and size of text? Description: In the below program you will see that we have created a textView dynamically and passed context. This context is used to get the information about the environment. Steps: This example demonstrates how do I change font color of TextView in android. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main.xml Step 3 − Add the following code to src/MainActivity.java import android.graphics.Color; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.TextView; public class MainActivity extends AppCompatActivity {@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState); setContentView(R.layout.activity_main);TextView textView1 = findViewById(R.id.textView1); textView1.setTextColor(Color.BLUE);TextView textView2 = findViewById(R.id.textView2); textView2.setTextColor(Color.parseColor("#006400"));}} Step 4 − Add the following code to androidManifest.xml This example demonstrates how do I change the font size of TextView in android. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main.xml Step 3 − Add the following code to src/MainActivity.java import android.support.v7.app.AppCompatActivity; import android.os.Bundle; public class MainActivity extends AppCompatActivity {@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState); setContentView(R.layout.activity_main);}} Step 4 − Add the following code to androidManifest.xml Post Practical Questions: 1. What is a context in android? ➡️ Context is used to create new components or objects like views and it is used to start activity and services. 2. The property that is used for formatting font is ➡️ B a)Color b) typeface c) ImageView 3. What is the default font size in Android? ➡️ B a) 12sp b) 14sp c) 16sp EXPERIMENT : 3 Aim: Create option menu and shows in notify in toast? Description: Android Option Menus are the primary menus of android. They can be used for settings, search, delete item etc. Here, you will inflating the menu by calling the inflate() method of Menu Inflater class. To perform event handling on menu items, you need to override onOptionsItemSelected() method of Activity class. Steps: Android Option Menu Example: File: activity_main.xml File: context_main.xml File: menu_main.xml File: MainActivity.java package example.javatpoint.com.optionmenu; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuItem; import android.widget.Toast; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); switch (id){ case R.id.item1: Toast.makeText(getApplicationContext(),"Item 1 Selected",Toast.LENGTH_LONG).show(); return true; case R.id.item2: Toast.makeText(getApplicationContext(),"Item 2 Selected",Toast.LENGTH_LONG).show(); return true; case R.id.item3: Toast.makeText(getApplicationContext(),"Item 3 Selected",Toast.LENGTH_LONG).show(); return true; default: return super.onOptionsItemSelected(item); } } } Post Practical Questions: Q. 1 Explain Toast class and option menu? ➡️ Toast Class: Toast class is used to show notification for a particular interval of time. After sometime it disappears. It doesn't block the user interaction. Toast Option Menu: Android Toast can be used to display information for the short period of time. A toast contains message to be displayed quickly and disappears after sometime. The android. widget. EXPERIMENT: 4 Aim: Create a program of animation with XML file? Description: An animation defined in XML that modifies properties of the target object, such as background color or alpha value, over a set amount of time. Steps: Here is the modified code of res/layout/activity_main.xml. Here abc indicates about logo of tutorials point Here is the code of res/anim/myanimation.xml. Here is the code of res/anim/clockwise.xml. Here is the code of res/anim/fade.xml. Here is the modified code of res/values/string.xml. My Application Here is the default code of AndroidManifest.xml. Post Practical Questions: 1. Explain XML Layout Attributes ? ➡️ Each layout file must contain exactly one root element, which must be a View or ViewGroup object. Once you've defined the root element, you can add additional layout objects or widgets as child elements to gradually build a View hierarchy that defines your layout. EXPERIMENT: 5 Aim: Create a program with button and chronometer? Description: The Chronometer is a subclass of TextView. This class helps us to add a timer in our app. You can give Timer start time in the elapsedRealTime() timebase and it start counting from that. If we don’t give base time then it will use the time at which time we call start() method. By default a chronometer displays the current timer value in the form of MM:SS or H:MM:SS. Steps: Step by Step Implementation: Step 1: Create a New Project in Android Studio To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Step 2: Working with the activity_main.xml file Navigate to app > res > layout > activity_main.xml and add the code below. Comments are added in the code to get to know in detail. Step 3: Working with the MainActivity file Navigate to app > java > your app’s package name > Main Activity file and add the below code to it. Comments are added in the code to get to know in detail. package com.gtappdevelopers.kotlingfgproject; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.Chronometer; import androidx.appcompat.app.AppCompatActivity; public class MainActivity extends AppCompatActivity { // on below line we are creating variables. private Chronometer chronometer; private Button chronometerBtn; boolean isRunning = false; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // on below line we are initializing our variables. chronometer = findViewById(R.id.idCMmeter); chronometerBtn = findViewById(R.id.idBtnChronometer); // on below line we are adding click listener for our button chronometerBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // on below line we are checking if // chronometer is running or not. if (isRunning) { // in this condition chronometer is running // on below line we are updating text for button chronometerBtn.setText("Start Chronometer"); // on below line we are updating boolean variable isRunning = false; // on below line we are stopping chronometer chronometer.stop(); } else { // in this condition chronometer is running // on below line we are updating text for button chronometerBtn.setText("Stop Chronometer"); // on below line we are updating boolean variable isRunning = true; // on below line we are starting chronometer chronometer.start(); } } }); } } Post Practical Questions: 1. Write it down the Android ChronoMeter Attributes ? ➡️ This attribute specifies a time format string for Chronometer. By default, Chronometer displays time in the format of "MM:SS" when the time is less than 1 hour, or "H:MM:SS" if the time is more than 1 hour. EXPERIMENT: 6 Aim: Create a program of Grid View and shows multiple subjects names? Description: Android Grid View shows items in two-dimensional scrolling grid (rows & columns) and the grid items are not necessarily predetermined but they automatically inserted to the layout using a List Adapter. Steps: XML Attributes of GridView: android:numColumns: This attribute of GridView will be used to decide the number of columns that are to be displayed in Grid. android:horizontalSpacing: This attribute is used to define the spacing between two columns of GridView. android:verticalSpacing: This attribute is used to specify the spacing between two rows of GridView. Step By Step Implementation: Step:1 Create a new Project in Android Studio: To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. The code for that has been given in both Java and Kotlin Programming Language for Android. Step:2 Add the Required Dependencies : Add the Google Repository to your settings.Gradle File. dependencyResolutionManagement { repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS) repositories { // add the following google() mavenCentral() } } Step:3 Working with the XML files : Create an XML Layout for each item of GridView : Create an XML file for each grid item to be displayed in GridView. Click on the app > res > layout > Right-Click > Layout Resource file and then name the file as card_item. Below is the code for the card_item.xml file. Step:5 Create a Model Class for Storing Data : Now click on app > java > apps package name > Right-Click on it. Then Click on New > Java Class. Name your Java/Kotlin Class file as CourseModel. Below is the code for the java > apps package name > Right-Click on it. Then Click on New > Java Class. Name your Java Class file as CourseGVAdapter. Below is the code for the CourseGVAdapter file. import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.ImageView; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import java.util.ArrayList; public class CourseGVAdapter extends ArrayAdapter { public CourseGVAdapter(@NonNull Context context, ArrayList courseModelArrayList) { super(context, 0, courseModelArrayList); } @NonNull @Override public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) { View listitemView = convertView; if (listitemView == null) { // Layout Inflater inflates each item to be displayed in GridView. listitemView = LayoutInflater.from(getContext()).inflate(R.layout.card_item, parent, false); } CourseModel courseModel = getItem(position); TextView courseTV = listitemView.findViewById(R.id.idTVCourse); ImageView courseIV = listitemView.findViewById(R.id.idIVcourse); courseTV.setText(courseModel.getCourse_name()); courseIV.setImageResource(courseModel.getImgid()); return listitemView; } } Step: 7 Working with the MainActivity File: Go to the MainActivity File and refer to the following code. Below is the code for the MainActivity File. Comments are added inside the code to understand the code in more detail. import android.os.Bundle; import android.widget.GridView; import androidx.appcompat.app.AppCompatActivity; import java.util.ArrayList; public class MainActivity extends AppCompatActivity { GridView coursesGV; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); coursesGV = findViewById(R.id.idGVcourses); ArrayList courseModelArrayList = new ArrayList(); courseModelArrayList.add(new CourseModel("DSA", R.drawable.ic_gfglogo)); courseModelArrayList.add(new CourseModel("JAVA", R.drawable.ic_gfglogo)); courseModelArrayList.add(new CourseModel("C++", R.drawable.ic_gfglogo)); courseModelArrayList.add(new CourseModel("Python", R.drawable.ic_gfglogo)); courseModelArrayList.add(new CourseModel("Javascript", R.drawable.ic_gfglogo)); courseModelArrayList.add(new CourseModel("DSA", R.drawable.ic_gfglogo)); CourseGVAdapter adapter = new CourseGVAdapter(this, courseModelArrayList); coursesGV.setAdapter(adapter); } } Post Practical Questions: 1. Explain Custom ArrayAdapter in GridView? ➡️ Android already provides the implementation for an ArrayAdapter, which can be used with just a single line demonstrated below. They are used when Whenever we have a list of single items we can use ArrayAdapter. For instance, a list of phone contacts, countries, or names. The problem with or limitation of this method is we cannot use complex layouts eg. Imagine we were building an app like Netflix or prime where each element is made up of many elements eg an ImageView, TextView, etc. Such complex views are not possible with the simple implementation of the ArrayAdapter for this we need to create our custom Adapter by extending the ArrayAdapter class. The following code shows the structure of the Custom ArrayAdapter. EXPERIMENT: 7 Aim: Create Simple Login Page with 3 attempt? Description: Define a button with login text and set its onClick Property. After that define the function mentioned in the onClick property in the java file. In the java file, inside the method of onClick get the username and passwords text using getText() and toString() method and match it with the text using equals() function. Steps: Following is the content of the modified main activity file src/MainActivity.java. package com.example.sairamkrishna.myapplication; import android.app.Activity; import android.graphics.Color; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; public class MainActivity extends Activity { Button b1,b2; EditText ed1,ed2; TextView tx1; int counter = 3; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); b1 = (Button)findViewById(R.id.button); ed1 = (EditText)findViewById(R.id.editText); ed2 = (EditText)findViewById(R.id.editText2); b2 = (Button)findViewById(R.id.button2); tx1 = (TextView)findViewById(R.id.textView3); tx1.setVisibility(View.GONE); b1.setOnClickListener(new View.OnClickListener() { @Overridepublic void onClick(View v) { if(ed1.getText().toString().equals("admin") && ed2.getText().toString().equals("admin")) { Toast.makeText(getApplicationContext(), "Redirecting...",Toast.LENGTH_SHORT).show(); }else{ Toast.makeText(getApplicationContext(), "Wrong Credentials",Toast.LENGTH_SHORT).show(); tx1.setVisibility(View.VISIBLE); tx1.setBackgroundColor(Color.RED); counter--; tx1.setText(Integer.toString(counter)); if (counter == 0) { b1.setEnabled(false); } } } }); b2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { finish(); } }); } } Following is the modified content of the xml res/layout/activity_main.xml. Following is the content of the res/values/string.xml. My Application Following is the content of AndroidManifest.xml file. Post Practical Questions: 1. How many orientations does android support? ➡️ D a) 1 b) 2 c) 3 d) 4 2. How to get current location in android? ➡️ D a) Using with GPRS b) SQLite c) Network servers d) Location Provider EXPERIMENT: 8 Aim: Create Simple Database Program with fatch data from SQLite Database with (name, phone, email, street, place)? Steps: Following is the content of the modified MainActivity.java. package com.example.sairamkrishna.myapplication; import android.content.Context; import android.content.Intent; import android.support.v7.app.ActionBarActivity; import android.os.Bundle; import android.view.KeyEvent; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.AdapterView.OnItemClickListener; import android.widget.ListView; import java.util.ArrayList; import java.util.List; public class MainActivity extends ActionBarActivity { public final static String EXTRA_MESSAGE = "MESSAGE"; private ListView obj; DBHelper mydb; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mydb = new DBHelper(this); ArrayList array_list = mydb.getAllCotacts(); ArrayAdapter arrayAdapter=new ArrayAdapter(this,android.R.layout.simple_list_item_1, array_list); obj = (ListView)findViewById(R.id.listView1); obj.setAdapter(arrayAdapter); obj.setOnItemClickListener(new OnItemClickListener(){ @Override public void onItemClick(AdapterView arg0, View arg1, int arg2,long arg3) { // TODO Auto-generated method stub int id_To_Search = arg2 + 1; Bundle dataBundle = new Bundle(); dataBundle.putInt("id", id_To_Search); Intent intent = new Intent(getApplicationContext(),DisplayContact.class); intent.putExtras(dataBundle); startActivity(intent); } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item){ super.onOptionsItemSelected(item); switch(item.getItemId()) { case R.id.item1:Bundle dataBundle = new Bundle(); dataBundle.putInt("id", 0); Intent intent = new Intent(getApplicationContext(),DisplayContact.class); intent.putExtras(dataBundle); startActivity(intent); return true; default: return super.onOptionsItemSelected(item); } } public boolean onKeyDown(int keycode, KeyEvent event) { if (keycode == KeyEvent.KEYCODE_BACK) { moveTaskToBack(true); } return super.onKeyDown(keycode, event); } } Following is the modified content of display contact activity DisplayContact.java package com.example.sairamkrishna.myapplication; import android.os.Bundle; import android.app.Activity; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.database.Cursor; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; public class DisplayContact extends Activity { int from_Where_I_Am_Coming = 0; private DBHelper mydb ; TextView name ; TextView phone; TextView email; TextView street; TextView place; int id_To_Update = 0; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_display_contact); name = (TextView) findViewById(R.id.editTextName); phone = (TextView) findViewById(R.id.editTextPhone); email = (TextView) findViewById(R.id.editTextStreet); street = (TextView) findViewById(R.id.editTextEmail); place = (TextView) findViewById(R.id.editTextCity); mydb = new DBHelper(this); Bundle extras = getIntent().getExtras(); if(extras !=null) { int Value = extras.getInt("id"); if(Value>0){ //means this is the view part not the add contact part. Cursor rs = mydb.getData(Value); id_To_Update = Value; rs.moveToFirst(); String nam = rs.getString(rs.getColumnIndex(DBHelper.CONTACTS_COLUMN_NAME)); String phon = rs.getString(rs.getColumnIndex(DBHelper.CONTACTS_COLUMN_PHONE)); String emai = rs.getString(rs.getColumnIndex(DBHelper.CONTACTS_COLUMN_EMAIL)); String stree = rs.getString(rs.getColumnIndex(DBHelper.CONTACTS_COLUMN_STREET)); String plac = rs.getString(rs.getColumnIndex(DBHelper.CONTACTS_COLUMN_CITY)); if (!rs.isClosed()) { rs.close(); } Button b = (Button)findViewById(R.id.button1); b.setVisibility(View.INVISIBLE); name.setText((CharSequence)nam); name.setFocusable(false); name.setClickable(false); phone.setText((CharSequence)phon); phone.setFocusable(false); phone.setClickable(false); email.setText((CharSequence)emai); email.setFocusable(false); email.setClickable(false); street.setText((CharSequence)stree); street.setFocusable(false); street.setClickable(false); place.setText((CharSequence)plac); place.setFocusable(false); place.setClickable(false); } } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. Bundle extras = getIntent().getExtras(); if(extras !=null) { int Value = extras.getInt("id"); if(Value>0){ getMenuInflater().inflate(R.menu.display_contact, menu); } else{ getMenuInflater().inflate(R.menu.menu_main menu); } } return true; } public boolean onOptionsItemSelected(MenuItem item) { super.onOptionsItemSelected(item); switch(item.getItemId()) { case R.id.Edit_Contact: Button b = (Button)findViewById(R.id.button1); b.setVisibility(View.VISIBLE); name.setEnabled(true); name.setFocusableInTouchMode(true); name.setClickable(true); phone.setEnabled(true); phone.setFocusableInTouchMode(true); phone.setClickable(true); email.setEnabled(true); email.setFocusableInTouchMode(true); email.setClickable(true); street.setEnabled(true); street.setFocusableInTouchMode(true); street.setClickable(true); place.setEnabled(true); place.setFocusableInTouchMode(true); place.setClickable(true); return true; case R.id.Delete_Contact: AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setMessage(R.string.deleteContact) .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { mydb.deleteContact(id_To_Update); Toast.makeText(getApplicationContext(), "Deleted Successfully", Toast.LENGTH_SHORT).show(); Intent intent = new Intent(getApplicationContext(),MainActivity.class); startActivity(intent); } }) .setNegativeButton(R.string.no, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { // User cancelled the dialog } }); AlertDialog d = builder.create(); d.setTitle("Are you sure"); d.show(); return true; default: return super.onOptionsItemSelected(item); } } public void run(View view) { Bundle extras = getIntent().getExtras(); if(extras !=null) { int Value = extras.getInt("id"); if(Value>0){ if(mydb.updateContact(id_To_Update,name.getText().toString(), phone.getText().toString(), email.getText().toString(), street.getText().toString(), place.getText().toString())){ Toast.makeText(getApplicationContext(), "Updated", Toast.LENGTH_SHORT).show(); Intent intent = new Intent(getApplicationContext(),MainActivity.class); startActivity(intent); } else{ Toast.makeText(getApplicationContext(), "not Updated", Toast.LENGTH_SHORT).show(); } } else{ if(mydb.insertContact(name.getText().toString(), phone.getText().toString(), email.getText().toString(), street.getText().toString(), place.getText().toString())){ Toast.makeText(getApplicationContext(), "done",Toast.LENGTH_SHORT).show();} else{ Toast.makeText(getApplicationContext(), "not done", Toast.LENGTH_SHORT).show(); } Intent intent = new Intent(getApplicationContext(),MainActivity.class); startActivity(intent); } } } } Following is the content of Database class DBHelper.java package com.example.sairamkrishna.myapplication; import java.util.ArrayList; import java.util.HashMap; import java.util.Hashtable; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.DatabaseUtils; import android.database.sqlite.SQLiteOpenHelper; import android.database.sqlite.SQLiteDatabase; public class DBHelper extends SQLiteOpenHelper { public static final String DATABASE_NAME = "MyDBName.db"; public static final String CONTACTS_TABLE_NAME = "contacts"; public static final String CONTACTS_COLUMN_ID = "id"; public static final String CONTACTS_COLUMN_NAME = "name"; public static final String CONTACTS_COLUMN_EMAIL = "email"; public static final String CONTACTS_COLUMN_STREET = "street"; public static final String CONTACTS_COLUMN_CITY = "place"; public static final String CONTACTS_COLUMN_PHONE = "phone"; private HashMap hp; public DBHelper(Context context) { super(context, DATABASE_NAME , null, 1); } @Override public void onCreate(SQLiteDatabase db) { // TODO Auto-generated method stub db.execSQL("create table contacts " + "(id integer primary key, name text,phone text,email text, street text,place text)" ); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { // TODO Auto-generated method stub db.execSQL("DROP TABLE IF EXISTS contacts"); onCreate(db); } public boolean insertContact (String name, String phone, String email, String street,String place) { SQLiteDatabase db = this.getWritableDatabase(); ContentValues contentValues = new ContentValues(); contentValues.put("name", name); contentValues.put("phone", phone); contentValues.put("email", email); contentValues.put("street", street); contentValues.put("place", place); db.insert("contacts", null, contentValues); return true; } public Cursor getData(int id) { SQLiteDatabase db = this.getReadableDatabase(); Cursor res = db.rawQuery( "select * from contacts where id="+id+"", null ); return res; } public int numberOfRows(){ SQLiteDatabase db = this.getReadableDatabase(); int numRows = (int) DatabaseUtils.queryNumEntries(db, CONTACTS_TABLE_NAME); return numRows; } public boolean updateContact (Integer id, String name, String phone, String email, String street,String place) { SQLiteDatabase db = this.getWritableDatabase(); ContentValues contentValues = new ContentValues(); contentValues.put("name", name); contentValues.put("phone", phone); contentValues.put("email", email); contentValues.put("street", street); contentValues.put("place", place); db.update("contacts", contentValues, "id = ? ", new String[] { Integer.toString(id) } ); return true; } public Integer deleteContact (Integer id) { SQLiteDatabase db = this.getWritableDatabase(); return db.delete("contacts", "id = ? ", new String[] { Integer.toString(id) }); } public ArrayList getAllCotacts() { ArrayList array_list = new ArrayList(); //hp = new HashMap(); SQLiteDatabase db = this.getReadableDatabase(); Cursor res = db.rawQuery( "select * from contacts", null ); res.moveToFirst(); while(res.isAfterLast() == false){ array_list.add(res.getString(res.getColumnIndex(CONTACTS_COLUMN_NAME))); res.moveToNext(); } return array_list; } } Following is the content of the res/layout/activity_main.xml Following is the content of the res/layout/activity_display_contact.xml Following is the content of the res/value/string.xml Address Book Settings Hello world! Add New Edit Contact Delete Contact DisplayContact Name Phone Email Street City/State/Zip Save Contact Are you sure, you want to delete it. Yes No Following is the content of the res/menu/main_menu.xml Following is the content of the res/menu/display_contact.xml This is the defualt AndroidManifest.xml of this project Post Practical Questions: 1. In SQLite, files are ____ directly to disk. ➡️ C a) Read b) Written c) Both a and b d) None of the above 2. SQLite is written in ➡️ B a) C b) ANSI-C c) JAVA d) None of these 3. SQLite is a ____ database resource. ➡️ D a) Interface b) Non-interface c) Portable d) Non-portable EXPERIMENT: 9 Aim: Create an Implicit and Explicit intents Program? Description: Types of Android Intents There are two types of intents in android: implicit and explicit. 1) Implicit Intent: Implicit Intent doesn't specifiy the component. In such case, intent provides information of available components provided by the system that is to be invoked. Intent intent=new Intent(Intent.ACTION_VIEW); intent.setData(Uri.parse("http://www.javatpoint.com")); startActivity(intent); 2) Explicit Intent: Explicit Intent specifies the component. In such case, intent provides the external class to be invoked. Intent i = new Intent(getApplicationContext(), ActivityTwo.class); startActivity(i); Steps: Implicit Intent: Creating an Android App to Open a Webpage Using Implicit Intent Step 1: Create a New Project in Android Studio To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Create an XML file and Java File. Please refer to the pre-requisites to learn more about this step. Step 2: Working with the XML Files Next, go to the activity_main.xml file, which represents the UI of the project. Below is the code for the activity_main.xml file. Comments are added inside the code to understand the code in more detail. Syntax: android:id="@+id/id_name" XML Code: Step 3: Working with the MainActivity File Now, we will create the Backend of the App. For this, Open the MainActivity file and instantiate the component (Button) created in the XML file using the findViewById() method. This method binds the created object to the UI Components with the help of the assigned ID. Syntax: ComponentType object = (ComponentType) findViewById(R.id.IdOfTheComponent); JAVA Code: import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { EditText editText; Button button; super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); button = findViewById(R.id.btn); editText = (EditText) findViewById(R.id.editText); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { String url=editText.getText().toString(); Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url)); startActivity(intent); } }); } } Explicit Intent How to create an Android App to move to the next activity using Explicit Intent(with Example) Step 1: Create a New Project in Android Studio To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Step 2: Working with the activity_main.xml File Next, go to the activity_main.xml file, which represents the UI of the project. Below is the code for the activity_main.xml file. Comments are added inside the code to understand the code in more detail. Syntax: android:id="@+id/id_name" XML Code: Step 3: Working with the MainActivity File Now, we will create the Backend of the App. For this, Open the MainActivity file and instantiate the component (Button, TextView) created in the XML file using the findViewById() method. This method binds the created object to the UI Components with the help of the assigned ID. Syntax: ComponentType object = (ComponentType) findViewById(R.id.IdOfTheComponent); Intent i = new Intent(getApplicationContext(), ); startActivity(i); JAVA Code: import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.os.Bundle; import android.view.View; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } public void newsScreen(View view) { Intent i = new Intent(getApplicationContext(), MainActivity2.class); startActivity(i); } } Step 4: Working with the activity_main2.xml File Now we have to create a second activity as a destination activity. The steps to create the second activity are File > new > Activity > Empty Activity. Next, go to the activity_main2.xml file, which represents the UI of the project. Below is the code for the activity_main2.xml file. Comments are added inside the code to understand the code in more detail. XML Code: Step 5: Working with the MainActivity2 File Now, we will create the Backend of the App. For this, Open the MainActivity file and instantiate the component (Button, TextView) created in the XML file using the findViewById() method. This method binds the created object to the UI Components with the help of the assigned ID. Syntax: ComponentType object = (ComponentType) findViewById(R.id.IdOfTheComponent); Intent i = new Intent(getApplicationContext(), ); startActivity(i); JAVA Code: import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.os.Bundle; import android.view.View; public class MainActivity2 extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main2); } public void homeScreen(View view) { Intent i = new Intent(getApplicationContext(), MainActivity.class); startActivity(i); } } Post Practical Questions: 1. If you want to navigate from one activity to another then android provides you which class ➡️ C a) startActivity b) Object c) Intent d) Adapter 2.The types of intents in android is\are distinguishes data classes or concepts. ➡️ D a) Explicit intents b) Implicit intents c) Start intents d) Option A and B are correct. 3.Suppose that there are two activities in an application named ActivityOne and ActivityTwo. You want to invoke ActivityTwo from ActivityOne. What code you will write? ➡️ A a) Intent intent=new Intent (this, ActivityTwo.class); startActivity(intent); b) startActivity(new Intent(this, ActivityTwo.class)); c) Option A and B are correct. d) None of the above. EXPERIMENT : 10 Aim: Make a Scientific Calculator Android App using Android Studio using multiple buttons? Steps: Step 1: Create a New Project To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language. Step 2: Adding new colors to the colors.xml file Navigate to the app > res > values > colors.xml file and add the below code to it for different colors. Comments are added in the code to get to know in more detail. XML Code: #0F9D58 #0F9D58 #0F9D58 #FF03DAC5 #FF018786 #FF000000 #FFFFFFFF #292D36 #272B33 #22252D #ffa500 Step 3: Working with the activity_main.xml file Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file. XML Code: Step 4: Working with the MainActivity.kt file Go to the MainActivity.kt file and refer to the following code. Below is the code for the MainActivity.kt file. Comments are added inside the code to understand the code in more detail. Kotlin Code: import android.os.Bundle import android.widget.Button import android.widget.TextView import android.widget.Toast import androidx.appcompat.app.AppCompatActivity class MainActivity : AppCompatActivity() { // creating variables for our text view and button lateinit var tvsec: TextView lateinit var tvMain: TextView lateinit var bac: Button lateinit var bc: Button lateinit var bbrac1: Button lateinit var bbrac2: Button lateinit var bsin: Button lateinit var bcos: Button lateinit var btan: Button lateinit var blog: Button lateinit var bln: Button lateinit var bfact: Button lateinit var bsquare: Button lateinit var bsqrt: Button lateinit var binv: Button lateinit var b0: Button lateinit var b9: Button lateinit var b8: Button lateinit var b7: Button lateinit var b6: Button lateinit var b5: Button lateinit var b4: Button lateinit var b3: Button lateinit var b2: Button lateinit var b1: Button lateinit var bpi: Button lateinit var bmul: Button lateinit var bminus: Button lateinit var bplus: Button lateinit var bequal: Button lateinit var bdot: Button lateinit var bdiv: Button override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // initializing all our variables. tvsec = findViewById(R.id.idTVSecondary) tvMain = findViewById(R.id.idTVprimary) bac = findViewById(R.id.bac) bc = findViewById(R.id.bc) bbrac1 = findViewById(R.id.bbrac1) bbrac2 = findViewById(R.id.bbrac2) bsin = findViewById(R.id.bsin) bcos = findViewById(R.id.bcos) btan = findViewById(R.id.btan) blog = findViewById(R.id.blog) bln = findViewById(R.id.bln) bfact = findViewById(R.id.bfact) bsquare = findViewById(R.id.bsquare) bsqrt = findViewById(R.id.bsqrt) binv = findViewById(R.id.binv) b0 = findViewById(R.id.b0) b9 = findViewById(R.id.b9) b8 = findViewById(R.id.b8) b7 = findViewById(R.id.b7) b6 = findViewById(R.id.b6) b5 = findViewById(R.id.b5) b4 = findViewById(R.id.b4) b3 = findViewById(R.id.b3) b2 = findViewById(R.id.b2) b1 = findViewById(R.id.b1) bpi = findViewById(R.id.bpi) bmul = findViewById(R.id.bmul) bminus = findViewById(R.id.bminus) bplus = findViewById(R.id.bplus) bequal = findViewById(R.id.bequal) bdot = findViewById(R.id.bdot) bdiv = findViewById(R.id.bdiv) // adding on click listener to our all buttons. b1.setOnClickListener { // on below line we are appending // the expression to our text view. tvMain.text = (tvMain.text.toString() + "1") } b2.setOnClickListener { // on below line we are appending // the expression to our text view. tvMain.text = (tvMain.text.toString() + "2") } b3.setOnClickListener { // on below line we are appending // the expression to our text view. tvMain.text = (tvMain.text.toString() + "3") } b4.setOnClickListener { tvMain.text = (tvMain.text.toString() + "4") } b5.setOnClickListener { tvMain.text = (tvMain.text.toString() + "5") } b6.setOnClickListener { tvMain.text = (tvMain.text.toString() + "6") } b7.setOnClickListener { tvMain.text = (tvMain.text.toString() + "7") } b8.setOnClickListener { tvMain.text = (tvMain.text.toString() + "8") } b9.setOnClickListener { tvMain.text = (tvMain.text.toString() + "9") } b0.setOnClickListener { tvMain.text = (tvMain.text.toString() + "0") } bdot.setOnClickListener { tvMain.text = (tvMain.text.toString() + ".") } bplus.setOnClickListener { tvMain.text = (tvMain.text.toString() + "+") } bdiv.setOnClickListener { tvMain.text = (tvMain.text.toString() + "/") } bbrac1.setOnClickListener { tvMain.text = (tvMain.text.toString() + "(") } bbrac2.setOnClickListener { tvMain.text = (tvMain.text.toString() + ")") } bpi.setOnClickListener { // on clicking on pi button we are adding // pi value as 3.142 to our current value. tvMain.text = (tvMain.text.toString() + "3.142") tvsec.text = (bpi.text.toString()) } bsin.setOnClickListener { tvMain.text = (tvMain.text.toString() + "sin") } bcos.setOnClickListener { tvMain.text = (tvMain.text.toString() + "cos") } btan.setOnClickListener { tvMain.text = (tvMain.text.toString() + "tan") } binv.setOnClickListener { tvMain.text = (tvMain.text.toString() + "^" + "(-1)") } bln.setOnClickListener { tvMain.text = (tvMain.text.toString() + "ln") } blog.setOnClickListener { tvMain.text = (tvMain.text.toString() + "log") } bminus.setOnClickListener { // on clicking on minus we are checking if // the user has already a minus operation on screen. // if minus operation is already present // then we will not do anything. val str: String = tvMain.text.toString() if (!str.get(index = str.length - 1).equals("-")) { tvMain.text = (tvMain.text.toString() + "-") } } bmul.setOnClickListener { // if mul sign is not present in our // text view then only we are adding // the multiplication operator to it. val str: String = tvMain.text.toString() if (!str.get(index = str.length - 1).equals("*")) { tvMain.text = (tvMain.text.toString() + "*") } } bsqrt.setOnClickListener { if (tvMain.text.toString().isEmpty()) { // if the entered number is empty we are displaying an error message. Toast.makeText(this, "Please enter a valid number..", Toast.LENGTH_SHORT).show() } else { val str: String = tvMain.text.toString() // on below line we are calculation // square root of the given number. val r = Math.sqrt(str.toDouble()) // on below line we are converting our double // to string and then setting it to text view. val result = r.toString() tvMain.setText(result) } } bequal.setOnClickListener { val str: String = tvMain.text.toString() // on below line we are calling an evaluate // method to calculate the value of expressions. val result: Double = evaluate(str) // on below line we are getting result // and setting it to text view. val r = result.toString() tvMain.setText(r) tvsec.text = str } bac.setOnClickListener { // on clicking on ac button we are clearing // our primary and secondary text view. tvMain.setText("") tvsec.setText("") } bc.setOnClickListener { // on clicking on c button we are clearing // the last character by checking the length. var str: String = tvMain.text.toString() if (!str.equals("")) { str = str.substring(0, str.length - 1) tvMain.text = str } } bsquare.setOnClickListener { if (tvMain.text.toString().isEmpty()) { // if the entered number is empty we are displaying an error message. Toast.makeText(this, "Please enter a valid number..", Toast.LENGTH_SHORT).show() } else { // on below line we are getting the expression and then calculating the square of the number val d: Double = tvMain.getText().toString().toDouble() // on below line we are calculating the square. val square = d * d // after calculating the square we // are setting it to text view. tvMain.setText(square.toString()) // on below line we are setting // the d to secondary text view. tvsec.text = "$d²" } } bfact.setOnClickListener { if (tvMain.text.toString().isEmpty()) { // if the entered number is empty we are displaying an error message. Toast.makeText(this, "Please enter a valid number..", Toast.LENGTH_SHORT).show() } else { // on below line we are getting int value // and calculating the factorial value of the entered number. val value: Int = tvMain.text.toString().toInt() val fact: Int = factorial(value) tvMain.setText(fact.toString()) tvsec.text = "$value`!" } } } fun factorial(n: Int): Int { // this method is use to find factorial return if (n == 1 || n == 0) 1 else n * factorial(n - 1) } fun evaluate(str: String): Double { return object : Any() { // on below line we are creating variable // for tracking the position and char pos. var pos = -1 var ch = 0 // below method is for moving to next character. fun nextChar() { // on below line we are incrementing our position // and moving it to next position. ch = if (++pos < str.length) str[pos].toInt() else -1 } // this method is use to check the extra space // present int the expression and removing it. fun eat(charToEat: Int): Boolean { while (ch == ' '.toInt()) nextChar() // on below line we are checking the char pos // if both is equal then we are returning it to true. if (ch == charToEat) { nextChar() return true } return false } // below method is to parse our // expression and to get the ans // in this we are calling a parse // expression method to calculate the value. fun parse(): Double { nextChar() val x = parseExpression() if (pos < str.length) throw RuntimeException("Unexpected: " + ch.toChar()) return x } // in this method we will only perform addition and // subtraction operation on the expression. fun parseExpression(): Double { var x = parseTerm() while (true) { if (eat('+'.toInt())) x += parseTerm() // addition else if (eat('-'.toInt())) x -= parseTerm() // subtraction else return x } } // in below method we will perform // only multiplication and division operation. fun parseTerm(): Double { var x = parseFactor() while (true) { if (eat('*'.toInt())) x *= parseFactor() // multiplication else if (eat('/'.toInt())) x /= parseFactor() // division else return x } } // below method is use to parse the factor fun parseFactor(): Double { //on below line we are checking for addition // and subtraction and performing unary operations. if (eat('+'.toInt())) return parseFactor() // unary plus if (eat('-'.toInt())) return -parseFactor() // unary minus // creating a double variable for ans. var x: Double // on below line we are creating // a variable for position. val startPos = pos // on below line we are checking // for opening and closing parenthesis. if (eat('('.toInt())) { // parentheses x = parseExpression() eat(')'.toInt()) } else if (ch >= '0'.toInt() && ch <= '9'.toInt() || ch == '.'.toInt()) { // numbers while (ch >= '0'.toInt() && ch <= '9'.toInt() || ch == '.'.toInt()) nextChar() // on below line we are getting sub string from our string using start and pos. x = str.substring(startPos, pos).toDouble() } else if (ch >= 'a'.toInt() && ch <= 'z'.toInt()) { // on below function we are checking for the operator in our expression. while (ch >= 'a'.toInt() && ch <= 'z'.toInt()) nextChar() val func = str.substring(startPos, pos) // calling a method to parse our factor. x = parseFactor() // on below line we are checking for square root. x = if (func == "sqrt") Math.sqrt(x) // on below line we are checking for sin function // and calculating sin function using Math class. else if (func == "sin") Math.sin( Math.toRadians(x) // on below line we are calculating the cos value ) else if (func == "cos") Math.cos( Math.toRadians(x) // on below line we are calculating // the tan value of our expression. ) else if (func == "tan") Math.tan(Math.toRadians(x)) // on below line we are calculating // log value of the expression. else if (func == "log") Math.log10(x) // on below line we are calculating // ln value of expression. else if (func == "ln") Math.log(x) // f we get any error then // we simply return the exception. else throw RuntimeException( "Unknown function: $func" ) } else { // if the condition not satisfy then we are returning the exception throw RuntimeException("Unexpected: " + ch.toChar()) } // on below line we are calculating the power of the expression. if (eat('^'.toInt())) x = Math.pow(x, parseFactor()) // exponentiation return x } // at last calling a parse for our expression. }.parse() } } BEST OF LUCK
- Machine Learning Assign.-1 BCA sem-5
Subject: Machine Learning Assignment: 1 (BCA Sem-5) Unit: 1 Introduction to Machine Learning 1. Define machine learning and explain how it differs from traditional programming. Ans. Machine Learning is a branch of artificial intelligence that develops algorithms by learning the hidden patterns of the datasets used it to make predictions on new similar type data, without being explicitly programmed for each task. Traditional Machine Learning combines data with statistical tools to predict an output that can be used to make actionable insights. Machine learning is used in many different applications, from image and speech recognition to natural language processing, recommendation systems, fraud detection, portfolio optimization, automated task, and so on. Machine learning models are also used to power autonomous vehicles, drones, and robots, making them more intelligent and adaptable to changing environments. A typical machine learning tasks are to provide a recommendation. Recommender systems are a common application of machine learning, and they use historical data to provide personalized recommendations to users. In the case of Netflix, the system uses a combination of collaborative filtering and content-based filtering to recommend movies and TV shows to users based on their viewing history, ratings, and other factors such as genre preferences. 2. Describe the main type of Machine Learning: Supervised Learning, Unsupervised Learning and Reinforcement Learning. Include one-real world example for each type. Ans. Types of Machine Learning: Supervised Machine Learning Unsupervised Machine Learning Reinforcement Machine Learning 1. Supervised Machine Learning: Supervised learning is a type of machine learning in which the algorithm is trained on the labeled dataset. It learns to map input features to targets based on labeled training data. In supervised learning, the algorithm is provided with input features and corresponding output labels, and it learns to generalize from this data to make predictions on new, unseen data. There are two main types of supervised learning: Regression: Regression is a type of supervised learning where the algorithm learns to predict continuous values based on input features. The output labels in regression are continuous values, such as stock prices, and housing prices. The different regression algorithms in machine learning are: Linear Regression, Polynomial Regression, Ridge Regression, Decision Tree Regression, Random Forest Regression, Support Vector Regression, etc Classification: Classification is a type of supervised learning where the algorithm learns to assign input data to a specific category or class based on input features. The output labels in classification are discrete values. Classification algorithms can be binary, where the output is one of two possible classes, or multiclass, where the output can be one of several classes. The different Classification algorithms in machine learning are: Logistic Regression, Naive Bayes, Decision Tree, Support Vector Machine (SVM), K-Nearest Neighbors (KNN), etc. 2. Unsupervised Machine Learning: Unsupervised learning is a type of machine learning where the algorithm learns to recognize patterns in data without being explicitly trained using labeled examples. The goal of unsupervised learning is to discover the underlying structure or distribution in the data. There are two main types of unsupervised learning: Clustering: Clustering algorithms group similar data points together based on their characteristics. The goal is to identify groups, or clusters, of data points that are similar to each other, while being distinct from other groups. Some popular clustering algorithms include K-means, Hierarchical clustering, and DBSCAN. Dimensionality reduction: Dimensionality reduction algorithms reduce the number of input variables in a dataset while preserving as much of the original information as possible. This is useful for reducing the complexity of a dataset and making it easier to visualize and analyze. Some popular dimensionality reduction algorithms include Principal Component Analysis (PCA), t-SNE, and Autoencoders. 3. Reinforcement Machine Learning: Reinforcement learning is a type of machine learning where an agent learns to interact with an environment by performing actions and receiving rewards or penalties based on its actions. The goal of reinforcement learning is to learn a policy, which is a mapping from states to actions, that maximizes the expected cumulative reward over time. There are two main types of reinforcement learning: Model-based reinforcement learning: In model-based reinforcement learning, the agent learns a model of the environment, including the transition probabilities between states and the rewards associated with each state-action pair. The agent then uses this model to plan its actions in order to maximize its expected reward. Some popular model-based reinforcement learning algorithms include Value Iteration and Policy Iteration. Model-free reinforcement learning: In model-free reinforcement learning, the agent learns a policy directly from experience without explicitly building a model of the environment. The agent interacts with the environment and updates its policy based on the rewards it receives. Some popular model-free reinforcement learning algorithms include Q-Learning, SARSA, and Deep Reinforcement Learning. 3. Explain the steps involved in the machine learning modeling flow. Briefly describe each step. Ans. Machine learning life cycle involves seven major steps, which are given below: 1. Gathering Data: Data Gathering is the first step of the machine learning life cycle. The goal of this step is to identify and obtain all data-related problems. In this step, we need to identify the different data sources, as data can be collected from various sources such as files, database, internet, or mobile devices. It is one of the most important steps of the life cycle. The quantity and quality of the collected data will determine the efficiency of the output. The more will be the data, the more accurate will be the prediction. This step includes the below tasks: Identify various data sources Collect data Integrate the data obtained from different sources By performing the above task, we get a coherent set of data, also called as a dataset. It will be used in further steps. 2. Data preparation: After collecting the data, we need to prepare it for further steps. Data preparation is a step where we put our data into a suitable place and prepare it to use in our machine learning training. In this step, first, we put all data together, and then randomize the ordering of data. This step can be further divided into two processes: Data exploration: It is used to understand the nature of data that we have to work with. We need to understand the characteristics, format, and quality of data. A better understanding of data leads to an effective outcome. In this, we find Correlations, general trends, and outliers. Data pre-processing: Now the next step is preprocessing of data for its analysis. 3. Data Wrangling: Data wrangling is the process of cleaning and converting raw data into a useable format. It is the process of cleaning the data, selecting the variable to use, and transforming the data in a proper format to make it more suitable for analysis in the next step. It is one of the most important steps of the complete process. Cleaning of data is required to address the quality issues. It is not necessary that data we have collected is always of our use as some of the data may not be useful. In real-world applications, collected data may have various issues, including: Missing Values Duplicate data Invalid data Noise So, we use various filtering techniques to clean the data. It is mandatory to detect and remove the above issues because it can negatively affect the quality of the outcome. 4. Data Analysis: Now the cleaned and prepared data is passed on to the analysis step. This step involves: Selection of analytical techniques Building models Review the result The aim of this step is to build a machine learning model to analyze the data using various analytical techniques and review the outcome. It starts with the determination of the type of the problems, where we select the machine learning techniques such as Classification, Regression, Cluster analysis, Association, etc. then build the model using prepared data, and evaluate the model. 5. Train Model: Now the next step is to train the model, in this step we train our model to improve its performance for better outcome of the problem. We use datasets to train the model using various machine learning algorithms. Training a model is required so that it can understand the various patterns, rules, and, features. 6. Test Model: Once our machine learning model has been trained on a given dataset, then we test the model. In this step, we check for the accuracy of our model by providing a test dataset to it. Testing the model determines the percentage accuracy of the model as per the requirement of project or problem. 7. Deployment: The last step of machine learning life cycle is deployment, where we deploy the model in the real-world system. If the above-prepared model is producing an accurate result as per our requirement with acceptable speed, then we deploy the model in the real system. But before deploying the project, we will check whether it is improving its performance using available data or not. The deployment phase is similar to making the final report for a project. 4. Compare and contrast Supervised Learning and Unsupervised Learning. How do they differ in terms of data, training process, and typical use cases? Ans. 5. What is Reinforcement Learning? Provide an example scenario where reinforcement learning could be applied. Ans. Reinforcement learning is an area of Machine Learning. It is about taking suitable action to maximize reward in a particular situation. It is employed by various software and machines to find the best possible behavior or path it should take in a specific situation. Reinforcement learning differs from supervised learning in a way that in supervised learning the training data has the answer key with it so the model is trained with the correct answer itself whereas in reinforcement learning, there is no answer but the reinforcement agent decides what to do to perform the given task. In the absence of a training dataset, it is bound to learn from its experience. Reinforcement Learning (RL) is the science of decision making. It is about learning the optimal behavior in an environment to obtain maximum reward. In RL, the data is accumulated from machine learning systems that use a trial-and-error method. Data is not part of the input that we would find in supervised or unsupervised machine learning. Reinforcement learning uses algorithms that learn from outcomes and decide which action to take next. After each action, the algorithm receives feedback that helps it determine whether the choice it made was correct, neutral or incorrect. It is a good technique to use for automated systems that have to make a lot of small decisions without human guidance. Reinforcement learning is an autonomous, self-teaching system that essentially learns by trial and error. It performs actions with the aim of maximizing rewards, or in other words, it is learning by doing in order to achieve the best outcomes. Types of Reinforcement: There are two types of Reinforcement: Positive: Positive Reinforcement is defined as when an event, occurs due to a particular behavior, increases the strength and the frequency of the behavior. In other words, it has a positive effect on behavior. Negative: Negative Reinforcement is defined as strengthening of behavior because a negative condition is stopped or avoided. Example: The problem is as follows: We have an agent and a reward, with many hurdles in between. The agent is supposed to find the best possible path to reach the reward. The following problem explains the problem more easily. The above image shows the robot, diamond, and fire. The goal of the robot is to get the reward that is the diamond and avoid the hurdles that are fired. The robot learns by trying all the possible paths and then choosing the path which gives him the reward with the least hurdles. Each right step will give the robot a reward and each wrong step will subtract the reward of the robot. The total reward will be calculated when it reaches the final reward that is the diamond. Main points in Reinforcement learning – Input: The input should be an initial state from which the model will start Output: There are many possible outputs as there are a variety of solutions to a particular problem Training: The training is based upon the input, The model will return a state and the user will decide to reward or punish the model based on its output. The model keeps continues to learn. The best solution is decided based on the maximum reward. 6. List and briefly explain three challenges that machine learning faces. How might these challenges impact the accuracy and effectiveness of machine learning models? Ans. we will discuss seven major challenges faced by machine learning professionals. Let’s have a look. 1. Poor Quality of Data: Data plays a significant role in the machine learning process. One of the significant issues that machine learning professionals face is the absence of good quality data. Unclean and noisy data can make the whole process extremely exhausting. We don’t want our algorithm to make inaccurate or faulty predictions. Hence the quality of data is essential to enhance the output. Therefore, we need to ensure that the process of data preprocessing which includes removing outliers, filtering missing values, and removing unwanted features, is done with the utmost level of perfection. 2. Underfitting of Training Data: This process occurs when data is unable to establish an accurate relationship between input and output variables. It simply means trying to fit in undersized jeans. It signifies the data is too simple to establish a precise relationship. To overcome this issue: Maximize the training time Enhance the complexity of the model Add more features to the data Reduce regular parameters Increasing the training time of model 3. Machine Learning is a Complex Process: The machine learning industry is young and is continuously changing. Rapid hit and trial experiments are being carried on. The process is transforming, and hence there are high chances of error which makes the learning complex. It includes analyzing the data, removing data bias, training data, applying complex mathematical calculations, and a lot more. Hence it is a really complicated process which is another big challenge for Machine learning professionals. 4. Slow Implementation: This is one of the common issues faced by machine learning professionals. The machine learning models are highly efficient in providing accurate results, but it takes a tremendous amount of time. Slow programs, data overload, and excessive requirements usually take a lot of time to provide accurate results. Further, it requires constant monitoring and maintenance to deliver the best output.
- E-Commerce Technology & SEO Assignment BCA sem-5
UNIT : 1 Overview of E-Commerce 1. Definition E-commerce. Ans. E-commerce stands for electronic commerce. E-commerce is the activity of purchasing or selling products via the internet. E-commerce offers almost everything to buy, making it extremely competitive. Some notable examples of successful e-commerce businesses are Amazon, Flipkart, eBay, and Myntra. E-commerce utilizes technology like mobile commerce, electronic funds transfers, supply chain management, inventory management systems, internet marketing, online transaction processing, EDI(Electronic data interchange), and automated data collection mechanisms. 2. What are the functions and significance E-Commerce? Ans. E-Commerce Functions: These are the typical functions of an e-commerce system available both on back office and front office: Registration Basket Payment Product management Orders Management VAT and shipping costs Registration: In order to make a purchase, users must register with the site, providing all the information needed for shipping and billing. The data will be stored on a database and will be available from the back office. Basket: The basket is a tool that, like a shopping basket, allows users to select the products they want and then go to the checkout for payment. Managing the basket means: Summarizing user requests within the possibilities offered by the catalogue Checking the basket and possibly cancel/modify the items placed in it. Starting the payment process for the selected products Payment: The payment system is a mechanism that facilitates dialogue between the parties involved in financial transactions: the bank, the store and you with your credit card. After filling the order, the customer enters his/her credit card number that travels along a channel solely accessible to the bank. The bank checks the customer’s account and decides whether or not to authorise the payment. Product management: This is the main part of the e-commerce system and provides all the features required for product placement, order fulfilment, etc…,key to the management of online sales. In detail the features in the system are: Product code Category Subcategory Product name Description Image, zoom Sizes available Price ‘Pieces’ in stock The products can be searched by category and subcategory. Order management: The order is the card that summarizes all the delivery and order information to enable correct delivery. It includes: List of products purchased User information Details of place of delivery Delivery time information Payment information VAT and shipping costs: In addition to the cost of products purchased, the system manages the VAT(Value added tax) and the shipping charges. The e-commerce module is able to manage VAT rates in countries within and outside the EU. Shipping costs both fixed and variable based on the weight and volume of the shipment. Discounts: Discounts and promotions are managed for a single product or product category. This second phase of the site requires a detailed analysis of your current storage and order management systems with which it will be necessary to integrate. Significance and Scope of E-commerce: The scope of e-commerce encompasses a wide range of online transactions and activities, including Cross-border e-commerce: Cross-border e-commerce refers to the buying and selling of goods and services across national borders. With the rise of e-commerce, it is becoming easier for businesses and consumers to engage in cross-border transactions, even if they are located in different countries. Digital goods and services: Digital goods and services refer to products that are delivered and consumed in a digital form. Examples include software, music, e-books, and online courses. The ease of delivery and the low costs associated with distributing digital goods make them an attractive option for both businesses and consumers. E-marketing and advertising: E-marketing and advertising refers to the use of digital channels to promote and sell products. This includes activities such as email marketing, search engine optimization, social media marketing, and online advertising. 3. Explain the scope of E-Commerce and growth in India. Ans. Scope of E-Commerce: 1.Business Growth: Every business owner wants to see growth in the business. It seems so easy when saying it, but it takes dedicated time and effort to see the expansion. Product vendors and service providers can increase their revenue by making a website of their own or else list the items on other e-commerce websites to reach the vast audience. 2. Different Ecommerce Marketplaces: The Ecommerce marketplaces like Amazon, Paytm, Snapdeal, Shop clues, Flipkart, etc. have their own policies to operate in the market. By agreeing with their terms and conditions, Sellers can list the items in almost every category they are interested in. Creating more listings in the inventory also makes it possible to get good sales on the ecommerce platform. This is one of the best opportunities sellers will get to showcase their products to large audiences. 3. Offers and Discounts: Offers and discounts are also one of the reasons for soar in scope of ecommerce industry. People look for huge discounts and special promo codes when they want to shop online. As a result, they visit numerous ecommerce sites to get the best deal for them. Online sellers can promote their products on Instagram and facebook with coupon codes and target the audience to generate the additional sales. 4. Fast Shipping: There are many shipping service companies which deliver the items in a very short amount of time. However, sellers have to pay high fees for it. Customers generally want their products to arrive in a very short period of time. Nowadays, the delays in shipping only happen because of bad environmental conditions. The shipping service companies have good manpower to process all their operations in a timely manner. 5. Reach to More Audience: The best advantage of having your own website or on the ecommerce website is that your business is not limited to just a single place. The customers can visit your website through any part of the world and purchase your items or services. There are people all around the globe who regularly shops online. Social media have played a huge role in expanding e-business. 6. Advertising: In the initial stage of selling your products online, Advertising is the best and first priority option to go with. However, the advertising budget will totally depend on the sellers. Sellers can generate more sales with advertising. On the other hand promotion also helps in reaching a larger audience. It is very easy to advertise on Google, Facebook, Instagram. 7. B2C and B2B Offering: The scope of ecommerce has been extended to the next level when dealing online. Sellers can offer both pricing b2b and b2b both when listing items on the e-commerce website like Amazon. Business customers are able to see bulk pricing if they are on the platform for bulk purchasing. In this way sellers can get both type of customers at the same time. Growth of E-commerce in India After China and the US, India had the third-largest online shopper base of 150 million in FY21 and is expected to be 350 million by FY26. 4. What is E-Business? Give the difference E-Business and E-Commerce. Ans. E-Business (electronic business) is any process that a business organization conducts over a computer-mediated network. Business organizations include any for-profit, governmental, or nonprofit entity. Their processes include production-, customer-, and internal- or management-focused business processes. E-Business Vs. E-commerce 5. Explain the features of E-Commerce Technology. Ans. 1. Ubiquity: There is a physical space in the traditional business market. Where for example, the customer has to go to buy Clothes, Shoes etc. Whereas in E-commerce this is not the case. E-commerce is everywhere. Due to E-commerce, both the time and effort of the people are reduced. 2. Global Reach: Business transactions in E-commerce can also be done outside the country. Which makes it even more convenient and effective. You can scale up the E-commerce business as per your wish. This is the most accessible way to take your business globally. In E-commerce, the whole world is your market. There is potential of market scale within the E-commerce business. 3.Universal Standards : Universal Standards are standards shared by all the nations around world. These are technical standards of Internet for conducting e-commerce. 4. Richness: E-commerce is also as rich as Television Technology. Advertising and branding is an important part of commerce. E-commerce can Deliver Video, Audio, Animation, Billboards and Signs etc. 5. Interactivity: The technology of E-commerce business is interactive. In this business and consumer can communicate with each other. 6. What are the advantages and disadvantages of E-Commerce. Ans. Advantages : Available 24/7 Provides a global reach No need for intermediaries Provides user with options to compare and select best option Reduces paper work Lowers the transaction cost Disadvantages: Lack of personal touch Requires an initial setup cost for hardware, software etc. Sometimes there are problems with order fulfillment or returns Security is a key concern -Identify Theft -Malware -Denial of Services 7. What are the types of E-Business? Explain each type in details. Ans. B2C: In B2C model, a business website is a place where all the transactions take place directly between a business organization and a consumer. In the B2C model, a consumer goes to the website, selects a catalog, orders the catalog, and an email is sent to the business organization. After receiving the order, goods are dispatched to the customer. Following are the key features of the B2C model − Heavy advertising required to attract customers. High investments in terms of hardware/software. Support or good customer care service. B2B: A website following the B2B business model sells its products to an intermediate buyer who then sells the products to the final customer. As an example, a wholesaler places an order from a company's website and after receiving the consignment, it sells the end product to the final customer who comes to buy the product at the wholesaler's retail outlet. B2B identifies both the seller as well as the buyer as business entities. B2B covers a large number of applications, which enables business to form relationships with their distributors, re-sellers, suppliers, etc. C2C: A website following the C2C business model helps consumers to sell their assets like residential property, cars, motorcycles, etc., or rent a room by publishing their information on the website. Website may or may not charge the consumer for its services. Another consumer may opt to buy the product of the first customer by viewing the post/advertisement on the website. Social Ecommerce: Social commerce is the use of social media platforms like Facebook and Instagram to market and sell products and services. Shoppers can use social commerce to: Discover brands Research products Interact with customer support Purchase items Social commerce is a more convenient and interactive shopping experience which may explain why it’s becoming increasingly popular. Estimates show that the global value of social commerce will reach about $2.9 trillion by 2026: M-Commerce: Buying and selling products and services through mobile devices are the new trend. A housewife can purchase her kitchen appliances from the comfort of her living room, a busy person can order lunch from office, one can use mobile platforms to sell goods and services − all with a few clicks. Local E-commerce: A customer orders a product from a seller, and the merchant delivers the goods to the customer from the nearest location. This significantly cuts the time and expense of logistics while also establishing a degree of confidence between the two parties. This is primarily due to the fact that the consumer is purchasing from a nearby, or local, merchant or shop. Local commerce is classified as Offline-to-Online commerce (O2O). The word “O2O” refers to the possibility (should be the reality) for retailers with physical stores to market and sell to local online customers the same way online pure-plays do. 8. Explain the concept of social E-Commerce and M-Commerce. Ans. Social E-Commerce: Social commerce is the use of social media platforms like Facebook and Instagram to market and sell products and services. Shoppers can use social commerce to: Discover brands Research products Interact with customer support Purchase items Social commerce is a more convenient and interactive shopping experience which may explain why it’s becoming increasingly popular. Estimates show that the global value of social commerce will reach about $2.9 trillion by 2026: Social commerce is booming because social media usage is. Research shows the typical social media user now spends about 15% of their waking life on social platforms, with 10% of US adults having an addiction to at least one app. Social commerce is a simple way to promote and sell products. For example, while scrolling on Instagram you may see a set of skin care products, tap Shop Now, add it to your shopping cart, and check out within the app. M-Commerce: Buying and selling products and services through mobile devices are the new trend. A housewife can purchase her kitchen appliances from the comfort of her living room, a busy person can order lunch from office, one can use mobile platforms to sell goods and services − all with a few clicks. What is M-Commerce? Mobile commerce or simply M-Commerce means engaging users in a buy or sell process via a mobile device. For instance, when someone buys an Android app or an iPhone app, that person is engaged in m-commerce. There are a number of content assets that can be bought and sold via a mobile device such as games, applications, ringtones, subscriptions etc. Benefits of M-Commerce: The probability of your potential customers owning a Smartphone is very high, so you can safely assume that you will get much more positive response from mobile devices than your website. M-commerce is recommended for every business irrespective of its type, scale, and size. 9. Explain Local E-Commerce. Ans. Local E-commerce: A customer orders a product from a seller, and the merchant delivers the goods to the customer from the nearest location. This significantly cuts the time and expense of logistics while also establishing a degree of confidence between the two parties. This is primarily due to the fact that the consumer is purchasing from a nearby, or local, merchant or shop. Local commerce is classified as Offline-to-Online commerce (O2O). The word “O2O” refers to the possibility (should be the reality) for retailers with physical stores to market and sell to local online customers the same way online pure-plays do.
- Android Unit-1 Assignment Sem-5 BCA
UNIT-1 Introduction to Mobile Operating System 1. What is the life cycle of Android activity? Ans.• To work with an activity in Android, you typically: 1. Create an activity class by extending the Activity class or one of its subclasses. 2. Define the layout of the activity's user interface using XML or programmatically. 3. Implement the lifecycle methods (onCreate, onStart, onResume, etc.) to manage the activity's behavior and handle user interactions. 4. Handle events and user input within the activity, such as button clicks, menu selections, etc. 5. Perform any necessary data processing or communication with other components or services. 6. Update the UI and handle state changes as needed. 7. Handle the activity's lifecycle callbacks (onPause, onStop, onDestroy, etc.) to release resources and save or restore state when necessary. The activity lifecycle in Android refers to the sequence of states and methods that an activity goes through during its lifespan. Understanding the activity lifecycle is crucial for managing the behavior and state of an activity. The following are the key states and methods involved in the activity lifecycle: 1. onCreate(): This method is called when the activity is first created. It is typically used to initialize activity resources, set up the user interface, and perform any necessary setup tasks. 2. onStart(): This method is called when the activity becomes visible to the user. At this point, the activity is not yet in the foreground, but it's about to be. 3. onResume(): This method is called when the activity is about to start interacting with the user. The activity is now in the foreground and has user focus. 4. onPause(): This method is called when the activity is partially visible but is losing focus. It is often used to release resources or save transient data. 5. onStop(): This method is called when the activity is no longer visible to the user. It may be invoked either when another activity comes to the foreground or when the activity is being destroyed. 6. onRestart(): This method is called when the activity is being restarted after being stopped. It is followed by onStart() and onResume() to bring the activity back to the foreground. 7. onDestroy(): This method is called when the activity is being destroyed. It is the final call that the activity receives before it is removed from memory. During the lifecycle, the activity may also be affected by various system events and callbacks, such as: • onSaveInstanceState(): This method is called before an activity is paused or stopped to allow saving its current state. It is commonly used to save important data that needs to persist across configuration changes or process death. • onRestoreInstanceState(): This method is called after an activity has been recreated due to a configuration change or process death. It allows the activity to restore its previously saved state. 2. What is Android? Ans. Android is an open source and Linux-based Operating System for mobile devices such as smartphones and tablet computers. Android was developed by the Open Handset Alliance, led by Google, and other companies. Android offers a unified approach to application development for mobile devices which means developers need only develop for Android, and their applications should be able to run on different devices powered by Android. The first beta version of the Android Software Development Kit (SDK) was released by Google in 2007 where as the first commercial version, Android 1.0, was released in September 2008. On June 27, 2012, at the Google I/O conference, Google announced the next Android version, 4.1 Jelly Bean. Jelly Bean is an incremental update, with the primary aim of improving the user interface, both in terms of functionality and performance. The source code for Android is available under free and open source software licenses. Google publishes most of the code under the Apache License version 2.0 and the rest, Linux kernel changes, under the GNU General Public License version 2. Why Android? Open Source Larger Developer and community reach Increased Marketing Inter app Integration Reduced Cost of Development Higher Success ratio Rich Development Environment 3. What are the features of Android architecture? Ans. Android architecture contains different number of components to support any android device needs. Android software contains an open-source Linux Kernel having collection of number of C/C++ libraries which are exposed through an application framework services. Among all the components Linux Kernel provides main functionality of operating system functions to smartphones and Dalvik Virtual Machine (DVM) provide platform for running an android application. The main components of android architecture are following:- Applications Application Framework Android Runtime Platform Libraries Linux Kernel Pictorial representation of android architecture with several main components and their sub components – 4. What is Google Android SDK? Which are the tools placed in the Android SDK? Ans. • The Android SDK (Software Development Kit) is a collection of tools, libraries, and resources required for Android development. It includes the necessary APIs and documentation for building Android applications. • After configuring the Android SDK in Android Studio, you can explore its contents, including: • Android API levels: Different versions of the Android platform, each providing new features and capabilities. • Build Tools: Tools for compiling, packaging, and signing Android applications. • Libraries: Pre-built libraries for common functionalities like database access (SQLite), networking (OkHttp), and user interface (AppCompat). • Documentation: Comprehensive documentation on various aspects of Android development, including APIs, guidelines, and best practices. • Samples and Templates: Sample projects and templates that demonstrate Android development techniques and provide a starting point for your own projects. Android SDK tools: SDK tools are platform-independent and are required to create any Android app, regardless the version you are developing for. Some of these include: Build tools, Debugging tools and Image tools, among others. Now, some of the most important SDK tools are Android SDK Manager, which provides you resources, platforms and other useful components needed to build apps and manage SDK packages. The Android Virtual Device Manager, that provides a graphical user interface to test your app on a virtual device. The Dalvik Debug Monitor Server (ddms) to debug your Android apps. Or the Draw 9-patch, which allows you to create resizable bitmap images for your app. 5. History & Versions Android Operating Systems? Ans. Android Version History The version history of the Android mobile operating system began with the public release of its first beta on November 5, 2007. The first commercial version, Android 1.0, was released on September 23, 2008. The operating system is developed by Google on a yearly cycle since at least 2011. New major releases are announced at Google I/O along with its first public beta to supported Google Pixel devices. The stable version is then released later in the year. 6. Exploring the Android SDK in brief? Ans. Android SDK stands for Android Software Development Kit which is developed by Google for Android Platform. With the help of Android SDK, we can create android Apps easily. About Android SDK: Android SDK is a collection of libraries and Software Development tools that are essential for Developing Android Applications. Whenever Google releases a new version or update of Android Software, a corresponding SDK also releases with it. In the updated or new version of SDK, some more features are included which are not present in the previous version. Android SDK consists of some tools which are very essential for the development of Android Application. These tools provide a smooth flow of the development process from developing and debugging. Android SDK is compatible with all operating systems such as Windows, Linux, macOS, etc. Components of Android SDK: Android SDK Components play a major role in the Development of Android applications. Below are the important components: 1. Android SDK Tools: Android SDK tool is an important component of Android SDK. It consists of a complete set of development and debugging tools. Below are the SDK developer tools: Android SDK Build tool. Android Emulator. Android SDK Platform-tools. Android SDK Tools. 2. Android SDK Build-Tools: Android SDK build tools are used for building actual binaries of Android App. The main functions of Android SDK Build tools are built, debug, run and test Android applications. The latest version of the Android SDK Build tool is 30.0.3. While downloading or updating Android in our System, one must ensure that its latest version is download in SDK Components. 3. Android Emulator: An Android Emulator is a device that simulates an Android device on your system. Suppose we want to run our android application that we code. One option is that we will run this on our Android Mobile by Enabling USB Debugging on our mobile. Another option is using Android Emulator. In Android Emulator the virtual android device is shown on our system on which we run the Android application that we code. 4. Android SDK Platform-tools: Android SDK Platform-tools is helpful when we are working on Project and they will show the error messages at the same time. It is specifically used for testing. It includes: Android Debug Bridge (ADB), is a command-line tool that helps to communicate with the device. It allows us to perform an action such as Installing App and Debugging App etc. Fastboot allows you to flash a device with a new system image. Systrace tools help to collect and inspect timing information. It is very crucial for App Debugging. 5. Android SDK Tools: Android SDK tool is a component of SDK tool. It consists of a set of tools which and other Utilities which are crucial for the development of Android Application. It contains the complete set of Debugging and Development tools for android. 6. SDK Platforms : These are numbered according to the android version. The new version of the SDK platform has more features and more compatible but the old version is less compatible with fewer features. Like in Android 11.0(R) have more compatible and have more feature but the below versions like Android 10.0(Q), Android4.4(KitKat) have less feature and is less compatible. 7. SDK Update Sites: In SDK Update Sites, some sites are embedded in it which will check for Android SDK Updates Tools. In this, one must ensure we don’t unclick the button below because these are checked by default which will check for updates if we will unclick it then it doesn’t check updates for those. 🤞BEST OF LUCK 🤞
- Data Mining Que. Bank Sem-4 BCA
Download In PDF Document file (Last Page) 1)What is Data Warehouse? Explain it with Key Feature. Ans. Data warehousing provides architectures and tools for business executives to systematically organize, understand, and use their data to make strategic decisions. A data warehouse refers to a database that is maintained separately from an organization’s operational databases. Data warehouse systems allow for the integration of a variety of application systems. They support information processing by providing a solid platform of consolidated historical data for analysis. According to William H. Inmon, a leading architect in the construction of data warehouse systems, “A data warehouse is a subject-oriented, integrated, time-variant, and nonvolatile collection of data in support of management’s decision making process” The four keywords, subject-oriented, integrated, time-variant, and nonvolatile, distinguish data warehouses from other data repository systems, such as relational database systems, transaction processing systems, and file systems. Subject-oriented: ▪ A data warehouse is organized around major subjects, such as customer, supplier, product, and sales. ▪ Rather than concentrating on the day-to-day operations and transaction processing of an organization, a data warehouse focuses on the modeling and analysis of data for decision makers. ▪ Data warehouses typically provide a simple and concise view around particular subject issues by excluding data that are not useful in the decision support process. Integrated: ▪ A data warehouse is usually constructed by integrating multiple heterogeneous sources, such as relational databases, flat files, and on-line transaction records. ▪ Data cleaning and data integration techniques are applied to ensure consistency in naming conventions, encoding structures, attribute measures, and so on. Time-variant: ▪ Data are stored to provide information from a historical perspective (e.g., the past 5–10 years). ▪ Every key structure in the data warehouse contains, either implicitly or explicitly, an element of time. Nonvolatile: ▪ A data warehouse is always a physically separate store of data transformed from the application data found in the operational environment. ▪ Due to this separation, a data warehouse does not require transaction processing, recovery, and concurrency control mechanisms. ▪ It usually requires only two operations in data accessing: initial loading of data and access of data. 2) Explain Data Warehouse Design Process in Detail. Ans. A data warehouse can be built using a top-down approach, a bottom-up approach, or a combination of both. Top Down Approach: ▪ The top-down approach starts with the overall design and planning. ▪ It is useful in cases where the technology is mature and well known, and where the business problems that must be solved are clear and well understood. Bottom up Approach: ▪ The bottom-up approach starts with experiments and prototypes. ▪ This is useful in the early stage of business modeling and technology development. ▪ It allows an organization to move forward at considerably less expense and to evaluate the benefits of the technology before making significant commitments. Combined Approach: ▪ In the combined approach, an organization can exploit the planned and strategic nature of the top-down approach while retaining the rapid implementation and opportunistic application of the bottom-up approach. The warehouse design process consists of the following steps: • Choose a business process to model, for example, orders, invoices, shipments, inventory, account administration, sales, or the general ledger. • If the business process is organizational and involves multiple complex object collections, a data warehouse model should be followed. However, if the process is departmental and focuses on the analysis of one kind of business process, a data mart model should be chosen. • Choose the grain of the business process. The grain is the fundamental, atomic level of data to be represented in the fact table for this process, for example, individual transactions, individual daily snapshots, and so on. • Choose the dimensions that will apply to each fact table record. Typical dimensions are time, item, customer, supplier, warehouse, transaction type, and status. • Choose the measures that will populate each fact table record. Typical measures are numeric additive quantities like dollars sold and units sold. 3) What is Business Intelligence? Explain Business Intelligence in today’s perspective. Ans. While there are varying definitions for BI, Forrester defines it broadly as a “set of methodologies, processes, architectures, and technologies that transform raw data into meaningful and useful information that allows business users to make informed business decisions with real-time data that can put a company ahead of its competitors”. In other words, the high-level goal of BI is to help a business user turn business related data into actionable knowledge. BI traditionally focused on reports, dashboards, and answering predefined questions. Today BI also includes a focus on deeper, exploratory, and interactive analyses of the data using Business Analytics such as data mining, predictive analytics, statistical analysis, and natural language processing solutions. BI systems evolved by adding layers of data staging to increase the accessibility of the business data to business users. Data from the operational systems and ERP were extracted, transformed into a more consumable form (e.g., column names labeled for human rather than computer consumption, errors corrected, duplication eliminated). Data from a warehouse were then loaded into OLAP cubes, as well as data marts stored in data warehouses. OLAP cubes facilitated the analysis of data over several dimensions. Data marts present a subset of the data in the warehouse, tailored to a specific line of business. Using Business Intelligence, the business user, with the help of an IT specialist who had set up the system for her, could now more easily access and analyze the data through a BI system. 4) What do you mean by data mart? What are the different types of data mart? Ans. Data marts contain a subset of organization-wide data that is valuable to specific groups of people in an organization. A data mart contains only those data that is specific to a particular group. Data marts improve end-user response time by allowing users to have access to the specific type of data they need to view most often by providing the data in a way that supports the collective view of a group of users. A data mart is basically a condensed and more focused version of a data warehouse that reflects the regulations and process specifications of each business unit within an organization. Each data mart is dedicated to a specific business function or region. For example, the marketing data mart may contain only data related to items, customers, and sales. Data marts are confined to subjects. Listed below are the reasons to create a data mart: ▪ To speed up the queries by reducing the volume of data to be scanned. ▪ To partition data in order to impose access control strategies. ▪ To segment data into different hardware platforms. ▪ Easy access to frequently needed data ▪ Creates collective view by a group of users ▪ Improves end-user response time ▪ Lower cost than implementing a full data warehouse ▪ Contains only business essential data and is less cluttered. Three basic types of data marts are dependent, independent, and hybrid. The categorization is based primarily on the data source that feeds the data mart. Dependent data marts draw data from a central data warehouse that has already been created. Independent data marts, in contrast, are standalone systems built by drawing data directly from operational or external sources of data or both. Hybrid data marts can draw data from operational systems or data warehouses 1. Dependent Data Marts: A dependent data mart allows you to unite your organization's data in one data warehouse. This gives you the usual advantages of centralization. Figure illustrates a dependent data mart. 2. Independent Data Marts: An independent data mart is created without the use of a central data warehouse. This could be desirable for smaller groups within an organization. Figure illustrates an independent data mart. 3. Hybrid Data Marts: A hybrid data mart allows you to combine input from sources other than a data warehouse. This could be useful for many situations, especially when you need ad hoc integration, such as after a new group or product is added to the organization. Figure illustrates a hybrid data mart. 5) Explain usage of Data warehousing for information processing, analytical processing, and data Mining. Ans. Data warehouses are used in a wide range of applications for Business executives to perform data analysis and make strategic decisions. In many firms, data warehouses are used as an integral part of a plan-execute-assess “closed-loop” feedback system for enterprise management. Data warehouses are used extensively in banking and financial services, consumer goods and retail distribution sectors, and controlled manufacturing, such as demand based production. Business users need to have the means to know what exists in the data warehouse (through metadata), how to access the contents of the data warehouse, how to examine the contents using analysis tools, and how to present the results of such analysis. There are three kinds of data warehouse applications: 1. Information processing: It supports querying, basic statistical analysis, and reporting using crosstabs, tables, charts, or graphs. A current trend in data warehouse information processing is to construct low-cost Web-based accessing tools that are then integrated with Web browsers. Information processing, based on queries, can find useful information. However, answers to such queries reflect the information directly stored in databases or computable by aggregate functions. They do not reflect sophisticated patterns or regularities buried in the database. Therefore, information processing is not data mining. 2. Analytical processing: It supports basic OLAP operations, including slice-and-dice, drill-down, roll-up, and pivoting. It generally operates on historical data in both summarized and detailed forms. The major strength of on-line analytical processing over information processing is the multidimensional data analysis of data warehouse data. It can derive information summarized at multiple granularities from user-specified subsets of a data warehouse. 3. Data mining: It supports knowledge discovery by finding hidden patterns and associations, constructing analytical models, performing classification and prediction, and presenting the mining results using visualization tools. It may analyze data existing at more detailed granularities than the summarized data provided in a data warehouse. It may also analyze transactional, spatial, textual, and multimedia data that are difficult to model with current multidimensional database technology. 6) Explain three tier data warehouse architecture in brief. Bottom tier: • The bottom tier is a warehouse database server that is almost always a relational database system. • Back-end tools and utilities are used to feed data into the bottom tier from operational databases or other external sources. • These tools and utilities perform data extraction, cleaning, and transformation, as well as load and refresh functions to update the data warehouse. • The data are extracted using application program interfaces known as gateways. • A gateway is supported by the underlying DBMS and allows client programs to generate SQL code to be executed at a server. • Examples of gateways include ODBC (Open Database Connection) and OLEDB (Open Linking and Embedding for Databases) by Microsoft and JDBC (Java Database Connection). • This tier also contains a metadata repository, which stores information about the data warehouse and its contents. Middle tier: • The middle tier is an OLAP server that is typically implemented using either. • A relational OLAP (ROLAP) model, that is, an extended relational DBMS that maps operations on multidimensional data to standard relational operations or, • A multidimensional OLAP (MOLAP) model, that is, a special-purpose server that directly implements multidimensional data and operations. Top tier: • The top tier is a front-end client layer, which contains query and reporting tools, analysis tools, and/or data mining tools. From the architecture point of view, there are three data warehouse models: 1. Enterprise warehouse: • An enterprise warehouse collects all of the information about subjects spanning the entire organization. • It provides corporate-wide data integration, usually from one or more operational systems or external information providers, and is cross-functional in scope. • It typically contains detailed data as well as summarized data, • It can range in size from a few gigabytes to hundreds of gigabytes, terabytes, or beyond. 2. Data mart: • A data mart contains a subset of corporate-wide data that is of value to a specific group of users. 3. Virtual warehouse: • A virtual warehouse is a set of views over operational databases. For efficient query processing, only some of the possible summary views may be materialized. 7) Differentiate between OLTP and OLAP systems. Ans. 8) What is application of concept hierarchy? Draw concept hierarchy for location (country, state, city, and street) and time (year, quarter, month, week, day). OR What do you mean by concept hierarchy? Show its application with suitable example. Ans. • A concept hierarchy defines a sequence of mappings from a set of low-level concepts to higher-level, more general concepts. • Consider a concept hierarchy for the dimension location. City values for location include Vancouver, Toronto, New York, and Chicago. • Each city, however, can be mapped to the province or state to which it belongs. • For example, Vancouver can be mapped to British Columbia, and Chicago to Illinois. • The provinces and states can in turn be mapped to the country to which they belong, such as Canada or the USA. • These mappings form a concept hierarchy for the dimension location, mapping a set of low-level concepts (i.e., cities) to higher-level, more general concepts (i.e., countries). • The concept hierarchy described above is illustrated in following Figure. • Concept hierarchies may be provided manually by system users, domain experts, or knowledge engineers, or may be automatically generated based on statistical analysis of the data distribution. • Many concept hierarchies are implicit within the database schema. • For example, suppose that the dimension location is described by the attributes number, street, city, province or state, zipcode, and country. • These attributes are related by a total order, forming a concept hierarchy such as “street < city < province or state < country”. This hierarchy is shown in following Figure (a). • Alternatively, the attributes of a dimension may be organized in a partial order, forming a lattice. An example of a partial order for the time dimension based on the attributes day, week, month, quarter, and year is “day <{ month (l-s)” if support_count(l) / support_count(s) >= min_conf where min_conf is minimum confidence threshold. Back to Example: o We had L = {{I1}, {I2}, {I3}, {I4}, {I5}, {I1, I2}, {I1, I3}, {I1, I5}, {I2, I3}, {I2, I4}, {I2, I5}, {I1, I2, I3}, {I1, I2, I5}}. o Let’s take l = {I1, I2, I5}. – It’s all nonempty subsets are {I1, I2}, {I1, I5}, {I2, I5}, {I1}, {I2}, {I5}. o Let minimum confidence threshold is, say 70%. o The resulting association rules are shown below, each listed with its confidence. o R1: I1 ^ I2 -> I5 Confidence = sc{I1, I2, I5}/sc{I1,I2} = 2/4 = 50% (R1 is Rejected) o R2: I1 ^ I5 -> I2 Confidence = sc{I1, I2, I5}/sc{I1,I5} = 2/2 = 100% (R2 is Selected) o R3: I2 ^ I5 -> I1 Confidence = sc{I1, I2, I5}/sc{I2,I5} = 2/2 = 100% (R3 is Selected) o R4: I1 -> I2 ^ I5 Confidence = sc{I1, I2, I5}/sc{I1} = 2/6 = 33% (R4 is Rejected) o R5: I2 -> I1 ^ I5 Confidence = sc{I1, I2, I5}/{I2} = 2/7 = 29% (R5 is Rejected) o R6: I5 -> I1 ^ I2 Confidence = sc{I1, I2, I5}/ {I5} = 2/2 = 100% (R6 is Selected) o In this way, we have found three strong association rules. Methods to Improve Apriori’s Efficiency o Hash-based itemset counting: A k-itemset whose corresponding hashing bucket count is below the threshold cannot be frequent. o Transaction reduction: A transaction that does not contain any frequent k-itemset is useless in subsequent scans. o Partitioning: Any itemset that is potentially frequent in DB must be frequent in at least one of the partitions of DB. o Sampling: mining on a subset of given data, lower support threshold + a method to determine the completeness. o Dynamic itemset counting: add new candidate itemsets only when all of their subsets are estimated to be frequent. 20) Explain Concept of Market Basket Analysis. Ans. Market Basket Analysis is a modelling technique based upon the theory that if you buy a certain group of items, you are more (or less) likely to buy another group of items. For example, if you are in a store and you buy a milk and don't buy a bread, you are more likely to buy eggs at the same time than somebody who didn't buy bread. The set of items a customer buys is referred to as an itemset, and market basket analysis seeks to find relationships between purchases. Typically, the relationship will be in the form of a rule: e.g IF {milk, eggs} THEN {bread}. The probability that a customer will buy milk without an eggs (i.e. that the antecedent is true) is referred to as the support for the rule. The conditional probability that a customer will purchase bread is referred to as the confidence. The algorithms for performing market basket analysis are fairly straightforward. The complexities mainly arise in exploiting taxonomies, avoiding combinatorial explosions (a supermarket may stock 10,000 or more line items), and dealing with the large amounts of transaction data that may be available. A major difficulty is that a large number of the rules found may be trivial for anyone familiar with the business. Although the volume of data has been reduced, we are still asking the user to find a needle in a haystack. Requiring rules to have a high minimum support level and a high confidence level risks missing any exploitable result we might have found. One partial solution to this problem is differential market basket analysis, as described below. ❖ How is it used? o In retailing, most purchases are bought on impulse. Market basket analysis gives clues as to what a customer might have bought if the idea had occurred to them. o As a first step, therefore, market basket analysis can be used in deciding the location and promotion of goods inside a store. If, as has been observed, purchasers of Barbie dolls have are more likely to buy candy, then high-margin candy can be placed near to the Barbie doll display. Customers who would have bought candy with their Barbie dolls had they thought of it will now be suitably tempted. o But this is only the first level of analysis. Differential market basket analysis can find interesting results and can also eliminate the problem of a potentially high volume of trivial results. o In differential analysis, we compare results between different stores, between customers in different demographic groups, between different days of the week, different seasons of the year, etc. o If we observe that a rule holds in one store, but not in any other (or does not hold in one store, but holds in all others), then we know that there is something interesting about that store. Perhaps its clientele is different, or perhaps it has organized its displays in a novel and more lucrative way. Investigating such differences may yield useful insights which will improve company sales. ❖ Application Areas: o Although Market Basket Analysis conjures up pictures of shopping carts and supermarket shoppers, it is important to realize that there are many other areas in which it can be applied. These include: • Analysis of credit card purchases. • Analysis of telephone calling patterns. • Identification of fraudulent medical insurance claims. (Consider cases where common rules are broken). • Analysis of telecom service purchases. Best of Luck
- Python Programming BCA sem-4
1. What is Python? Ans. Python is an interpreted, object-oriented, high-level programming language with dynamic semantics. Its high-level built in data structures, combined with dynamic typing and dynamic binding, make it very attractive for Rapid Application Development, as well as for use as a scripting or glue language to connect existing components together. Python's simple, easy to learn syntax emphasizes readability and therefore reduces the cost of program maintenance. Python supports modules and packages, which encourages program modularity and code reuse. The Python interpreter and the extensive standard library are available in source or binary form without charge for all major platforms, and can be freely distributed. Often, programmers fall in love with Python because of the increased productivity it provides. Since there is no compilation step, the edit-test-debug cycle is incredibly fast. Debugging Python programs is easy: a bug or bad input will never cause a segmentation fault. Instead, when the interpreter discovers an error, it raises an exception. When the program doesn't catch the exception, the interpreter prints a stack trace. A source level debugger allows inspection of local and global variables, evaluation of arbitrary expressions, setting breakpoints, stepping through the code a line at a time, and so on. The debugger is written in Python itself, testifying to Python's introspective power. On the other hand, often the quickest way to debug a program is to add a few print statements to the source: the fast edit-test-debug cycle makes this simple approach very effective. 2. Explain features of Python. Ans. Python provides many useful features which make it popular and valuable from the other programming languages. It supports object-oriented programming, procedural programming approaches and provides dynamic memory allocation. We have listed below a few essential features. 1) Easy to Learn and Use: Python is easy to learn as compared to other programming languages. Its syntax is straightforward and much the same as the English language. There is no use of the semicolon or curly-bracket, the indentation defines the code block. It is the recommended programming language for beginners. 2) Expressive Language: Python can perform complex tasks using a few lines of code. A simple example, the hello world program you simply type print("Hello World"). It will take only one line to execute, while Java or C takes multiple lines. 3) Interpreted Language: Python is an interpreted language; it means the Python program is executed one line at a time. The advantage of being interpreted language, it makes debugging easy and portable. 4) Cross-platform Language: Python can run equally on different platforms such as Windows, Linux, UNIX, and Macintosh, etc. So, we can say that Python is a portable language. It enables programmers to develop the software for several competing platforms by writing a program only once. 5) Free and Open Source: Python is freely available for everyone. It is freely available on its official website www.python.org. It has a large community across the world that is dedicatedly working towards make new python modules and functions. Anyone can contribute to the Python community. The open-source means, "Anyone can download its source code without paying any penny." 6) Object-Oriented Language: Python supports object-oriented language and concepts of classes and objects come into existence. It supports inheritance, polymorphism, and encapsulation, etc. The object-oriented procedure helps to programmer to write reusable code and develop applications in less code. 7) Extensible: It implies that other languages such as C/C++ can be used to compile the code and thus it can be used further in our Python code. It converts the program into byte code, and any platform can use that byte code. 8) Large Standard Library: It provides a vast range of libraries for the various fields such as machine learning, web developer, and also for the scripting. There are various machine learning libraries, such as Tensor flow, Pandas, Numpy, Keras, and Pytorch, etc. Django, flask, pyramids are the popular framework for Python web development. 9) GUI Programming Support: Graphical User Interface is used for the developing Desktop application. PyQT5, Tkinter, Kivy are the libraries which are used for developing the web application. 10) Integrated: It can be easily integrated with languages like C, C++, and JAVA, etc. Python runs code line by line like C,C++ Java. It makes easy to debug the code. 11. Embeddable: The code of the other programming language can use in the Python source code. We can use Python source code in another programming language as well. It can embed other language into our code. 12. Dynamic Memory Allocation: In Python, we don't need to specify the data-type of the variable. When we assign some value to the variable, it automatically allocates the memory to the variable at run time. Suppose we are assigned integer value 15 to x, then we don't need to write int x = 15. Just write x = 15. 3. Explain PVM. Ans. We know that computers understand only machine code that comprises 1s and 0s. Since computer understands only machine code, it is imperative that we should convert any program into machine code before it is submitted to the computer for execution. For this purpose, we should take the help of a compiler. A compiler normally converts the program source code into machine code. A Python compiler does the same task but in a slightly different manner. It converts the program source code into another code, called byte code. Each Python program statement is converted into a group of byte code instructions. Then what is byte code? Byte code represents the fixed set of instructions created by Python developers representing all types of operations. The size of each byte code instruction is 1 byte (or 8bits) and hence these are called byte code instructions. Python organization says that there may be newer instructions added to the existing byte code instructions from time to time. We can find byte code instructions in the .pyc file. Following Figure shows the role of virtual machine in converting byte code instructions into machine code: The role of Python Virtual Machine (PVM) is to convert the byte code instructions into machine code so that the computer can execute those machine code instructions and display the final output. To carry out this conversion, PVM is equipped with an interpreter. The interpreter converts the byte code into machine code and sends that machine code to the computer processor for execution. Since interpreter is playing the main role, often the Python Virtual Machine is also called an interpreter. 4. Comparison between c and Python. Ans. 5. Comparison between Java and Python. Ans. 6. List out datatypes in python explain any two datatypes with example. Ans. Data types are the classification or categorization of data items. It represents the kind of value that tells what operations can be performed on a particular data. Since everything is an object in Python programming, data types are actually classes and variables are instances (object) of these classes. The following are the standard or built-in data types in Python: Numeric Sequence Type Boolean Set Dictionary Binary Types( memoryview, bytearray, bytes) Boolean Data Type in Python: Data type with one of the two built-in values, True or False. Boolean objects that are equal to True are truthy (true), and those equal to False are falsy (false). But non-Boolean objects can be evaluated in a Boolean context as well and determined to be true or false. It is denoted by the class bool. Note – True and False with capital ‘T’ and ‘F’ are valid Booleans otherwise python will throw an error. # Python program to # demonstrate Boolean type print(type(True)) print(type(False)) print(type(true)) Output: Numeric Data Type in Python: The numeric data type in Python represents the data that has a numeric value. A numeric value can be an integer, a floating number, or even a complex number. These values are defined as Python int, Python float, and Python complex classes in Python. Integers – This value is represented by int class. It contains positive or negative whole numbers (without fractions or decimals). In Python, there is no limit to how long an integer value can be. Float – This value is represented by the float class. It is a real number with a floating-point representation. It is specified by a decimal point. Optionally, the character e or E followed by a positive or negative integer may be appended to specify scientific notation. Complex Numbers – Complex number is represented by a complex class. It is specified as (real part) + (imaginary part)j. For example – 2+3j Note – type() function is used to determine the type of data type. # Python program to # demonstrate numeric value a = 5 print("Type of a: ", type(a)) b = 5.0 print("\nType of b: ", type(b)) c = 2 + 4j print("\nType of c: ", type(c)) Output: Type of a: Type of b: Type of c: 7. What is the difference between list and tuple? Ans. 8. Explain variable in python with example. Ans. Python Variable is containers that store values. Python is not “statically typed”. We do not need to declare variables before using them or declare their type. A variable is created the moment we first assign a value to it. A Python variable is a name given to a memory location. It is the basic unit of storage in a program. Example of Variable in Python: An Example of a Variable in Python is a representational name that serves as a pointer to an object. Once an object is assigned to a variable, it can be referred to by that name. In layman’s terms, we can say that Variable in Python is containers that store values. Here we have stored “Geeksforgeeks” in a var which is variable, and when we call its name the stored information will get printed. Var = "Geeksforgeeks" print(Var) Output: Geeksforgeeks Rules for Python variables: A Python variable name must start with a letter or the underscore character. A Python variable name cannot start with a number. A Python variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ ). Variable in Python names are case-sensitive (name, Name, and NAME are three different variables). The reserved words(keywords) in Python cannot be used to name the variable in Python. Example : # valid variable name geeks = 1 Geeks = 2 Ge_e_ks = 5 _geeks = 6 geeks_ = 7 _GEEKS_ = 8 print(geeks, Geeks, Ge_e_ks) print(_geeks, geeks_, _GEEKS_) Output: 1 2 5 6 7 8 Variables Assignment in Python: Here, we have assigned a number, a floating point number, and a string to a variable such as age, salary, and name. Ex. # An integer assignment age = 45 # A floating point salary = 1456.8 # A string name = "John" print(age) print(salary) print(name) Output: 45 1456.8 John Declaration and Initialization of Variables: Let’s see how to declare the variable and print the variable. Ex. # declaring the var Number = 100 # display print( Number) Output: 100 Redeclaring variables in Python: We can re-declare the Python variable once we have declared the variable already. Ex. # declaring the var Number = 100 # display print("Before declare: ", Number) # re-declare the var Number = 120.3 print("After re-declare:", Number) Output: Before declare: 100 After re-declare: 120.3 Python Assign Values to Multiple Variables : Also, Python allows assigning a single value to several variables simultaneously with “=” operators. For example: a = b = c = 10 print(a) print(b) print(c) Output: 10 10 10 Assigning different values to multiple variables: Python allows adding different values in a single line with “,” operators. a, b, c = 1, 20.2, "GeeksforGeeks" print(a) print(b) print(c) Output: 1 20.2 GeeksforGeeks Can we use the same name for different types? If we use the same name, the variable starts referring to a new value and type. Ex. a = 10 a = "GeeksforGeeks" print(a) Output: GeeksforGeeks How does + operator work with variables? The Python plus operator + provides a convenient way to add a value if it is a number and concatenate if it is a string. If a variable is already created it assigns the new value back to the same variable. Ex. a = 10 b = 20 print(a+b) a = "Geeksfor" b = "Geeks" print(a+b) Output: 30 GeeksforGeeks Can we use + for different Datatypes also? No use for different types would produce an error. Ex. a = 10 b = "Geeks" print(a+b) Output : TypeError: unsupported operand type(s) for +: 'int' and 'str' Global and Local Python Variables: Local variables in Python are the ones that are defined and declared inside a function. We can not call this variable outside the function. Ex. # This function uses global variable s def f(): s = "Welcome geeks" print(s) f() Output: Welcome geeks Global variables in Python are the ones that are defined and declared outside a function, and we need to use them inside a function. Ex. # This function has a variable with # name same as s. def f(): print(s) # Global scope s = "I love Geeksforgeeks" f() Output: I love Geeksforgeeks 9. List out the rules for identifiers. Ans. Identifier is a user-defined name given to a variable, function, class, module, etc. The identifier is a combination of character digits and an underscore. They are case-sensitive i.e., ‘num’ and ‘Num’ and ‘NUM’ are three different identifiers in python. It is a good programming practice to give meaningful names to identifiers to make the code understandable. We can also use the Python string isidentifier() method to check whether a string is a valid identifier or not. Rules for Naming Python Identifiers: It cannot be a reserved python keyword. It should not contain white space. It can be a combination of A-Z, a-z, 0-9, or underscore. It should start with an alphabet character or an underscore ( _ ). It should not contain any special character other than an underscore ( _ ). Examples of Python Identifiers: Valid identifiers: var1 _var1 _1_var var_1 Invalid Identifiers !var1 1var 1_var var#1 var 1 10. Explain Keyword in Python. Ans. Python has a set of keywords that are reserved words that cannot be used as variable names, function names, or any other identifiers: 11. Explain type conversion with example. Ans. In this tutorial, we will learn about the Python Type conversion with the help of examples. In programming, type conversion is the process of converting data of one type to another. For example: converting int data to str. There are two types of type conversion in Python. Implicit Conversion - automatic type conversion Explicit Conversion - manual type conversion Python Implicit Type Conversion: In certain situations, Python automatically converts one data type to another. This is known as implicit type conversion. Example 1: Converting integer to float Let's see an example where Python promotes the conversion of the lower data type (integer) to the higher data type (float) to avoid data loss. integer_number = 123 float_number = 1.23 new_number = integer_number + float_number # display new value and resulting data type print("Value:",new_number) print("Data Type:",type(new_number)) Run Code Output: Value: 124.23 Data Type: Explicit Type Conversion: In Explicit Type Conversion, users convert the data type of an object to required data type. We use the built-in functions like int(), float(), str(), etc to perform explicit type conversion. This type of conversion is also called typecasting because the user casts (changes) the data type of the objects. Example 2: Addition of string and integer Using Explicit Conversion: num_string = '12' num_integer = 23 print("Data type of num_string before Type Casting:",type(num_string)) # explicit type conversion num_string = int(num_string) print("Data type of num_string after Type Casting:",type(num_string)) num_sum = num_integer + num_string print("Sum:",num_sum) print("Data type of num_sum:",type(num_sum)) Run Code Output: Data type of num_string before Type Casting: Data type of num_string after Type Casting: Sum: 35 Data type of num_sum: 12. Explain arithmetic operator with example. Ans. There are 7 arithmetic operators in Python. The lists are given below: Python Arithmetic Operators Examples: Addition Operator: In Python, + is the addition operator. It is used to add 2 values. Ex. val1 = 2 val2 = 3 # using the addition operator res = val1 + val2 print(res) Output: 5 Subtraction Operator: In Python, – is the subtraction operator. It is used to subtract the second value from the first value. Ex. val1 = 2 val2 = 3 # using the subtraction operator res = val1 - val2 print(res) Output: -1 Multiplication Operator: In Python, * is the multiplication operator. It is used to find the product of 2 values. Ex. val1 = 2 val2 = 3 # using the multiplication operator res = val1 * val2 print(res) Output : 6 Division Operator : In Python, / is the division operator. It is used to find the quotient when the first operand is divided by the second. Ex. val1 = 3 val2 = 2 # using the division operator res = val1 / val2 print(res) Output: 1.5 Modulus Operator: In Python, % is the modulus operator. It is used to find the remainder when the first operand is divided by the second. Ex. val1 = 3 val2 = 2 # using the modulus operator res = val1 % val2 print(res) Output: 1 Exponentiation Operator: In Python, ** is the exponentiation operator. It is used to raise the first operand to the power of the second. Ex. val1 = 2 val2 = 3 # using the exponentiation operator res = val1 ** val2 print(res) Output: 8 Floor Division Operator: In Python, // is used to conduct the floor division. It is used to find the floor of the quotient when the first operand is divided by the second. Ex. val1 = 3 val2 = 2 # using the floor division res = val1 // val2 print(res) Output: 1 13. Explain membership operator with example. Ans. Membership operators are used to test if a sequence is presented in an object: Operator : in Description: Returns True if a sequence with the specified value is present in the object Example : x in y x = ["apple", "banana"] print("banana" in x) # returns True because a sequence with the value "banana" is in the list Output: True Operator : not in Description : Returns True if a sequence with the specified value is not present in the object Example: x not in y x = ["apple", "banana"] print("pineapple" not in x) # returns True because a sequence with the value "pineapple" is not in the list Output: True 14. Explain identify operator with example. Ans. Identity operators are used to compare the objects, not if they are equal, but if they are actually the same object, with the same memory location: Operator: is Description: Returns true if both variables are the same object Example: x is y x = ["apple", "banana"] y = ["apple", "banana"] z = x print(x is z) # returns True because z is the same object as x print(x is y) # returns False because x is not the same object as y, even if they have the same content print(x == y) # to demonstrate the difference between "is" and "==": this comparison returns True because x is equal to y Output: True False True Operator : is not Description: Returns true if both variables are not the same object Example: x is not y x = ["apple", "banana"] y = ["apple", "banana"] z = x print(x is not z) # returns False because z is the same object as x print(x is not y) # returns True because x is not the same object as y, even if they have the same content print(x != y) # to demonstrate the difference between "is not" and "!=": this comparison returns False because x is equal to y Output : False True False 15. Explain if loop with example. Ans. If statements are control flow statements which helps us to run a particular code only when a certain condition is satisfied. For example, you want to print a message on the screen only when a condition is true then you can use if statement to accomplish this in programming. In this guide, we will learn how to use if statements in Python programming with the help of examples. Syntax of If statement in Python: The syntax of if statement in Python is pretty simple. if condition: block_of_code If statement flow diagram: Python – If statement Example: flag = True if flag==True: print("Welcome") print("To") print("BeginnersBook.com") Output: Welcome To BeginnersBook.com 16. Write a program of print the largest of the three numbers in python. Ans. Source Code: # Python program to find the largest number among the three input numbers # change the values of num1, num2 and num3 # for a different result num1 = 10 num2 = 14 num3 = 12 # uncomment following lines to take three numbers from user #num1 = float(input("Enter first number: ")) #num2 = float(input("Enter second number: ")) #num3 = float(input("Enter third number: ")) if (num1 >= num2) and (num1 >= num3): largest = num1 elif (num2 >= num1) and (num2 >= num3): largest = num2 else: largest = num3 print("The largest number is", largest) Output: The largest number is 14.0 17. Write a program to check whether a number is even or not. Ans. Source Code: # Python program to check if the input number is odd or even. # A number is even if division by 2 gives a remainder of 0. # If the remainder is 1, it is an odd number. num = int(input("Enter a number: ")) if (num % 2) == 0: print("{0} is Even".format(num)) else: print("{0} is Odd".format(num)) Output: Enter a number: 43 43 is Odd 18. Explain for loop with example. Ans. For Loop in Python: For loops are used for sequential traversal. For example: traversing a list or string or array etc. In Python, there is “for in” loop which is similar to for each loop in other languages. Let us learn how to use for in loop for sequential traversals. Syntax: for iterator_var in sequence: statements(s) # Python program to illustrate # Iterating over range 0 to n-1 n = 4 for i in range(0, n): print(i) Output: 0 1 2 3 Example with List, Tuple, string, and dictionary iteration using For Loops in Python We can use for loop to iterate lists, tuples, strings and dictionaries in Python. # Python program to illustrate # Iterating over a list print("List Iteration") l = ["geeks", "for", "geeks"] for i in l: print(i) # Iterating over a tuple (immutable) print("\nTuple Iteration") t = ("geeks", "for", "geeks") for i in t: print(i) # Iterating over a String print("\nString Iteration") s = "Geeks" for i in s: print(i) # Iterating over dictionary print("\nDictionary Iteration") d = dict() d['xyz'] = 123 d['abc'] = 345 for i in d: print("%s %d" % (i, d[i])) # Iterating over a set print("\nSet Iteration") set1 = {1, 2, 3, 4, 5, 6} for i in set1: print(i), Output: List Iteration geeks for geeks Tuple Iteration geeks for geeks String Iteration G e e k s Dictionary Iteration xyz 123 abc 345 Set Iteration 1 2 3 4 5 6 Iterating by the index of sequences: We can also use the index of elements in the sequence to iterate. The key idea is to first calculate the length of the list and in iterate over the sequence within the range of this length. See the below example: # Python program to illustrate # Iterating by index list = ["geeks", "for", "geeks"] for index in range(len(list)): print(list[index]) Output: geeks for geeks Using else statement with for loop in Python: We can also combine else statement with for loop like in while loop. But as there is no condition in for loop based on which the execution will terminate so the else block will be executed immediately after for block finishes execution. # Python program to illustrate # combining else with for list = ["geeks", "for", "geeks"] for index in range(len(list)): print(list[index]) else: print("Inside Else Block") Output: geeks for geeks Inside Else Block 19. Explain while loop with example. Write a program on sum= 1+2+3+....+n using while loop. Ans. While Loop in Python: In python, a while loop is used to execute a block of statements repeatedly until a given condition is satisfied. And when the condition becomes false, the line immediately after the loop in the program is executed. Syntax: while expression: statement(s) All the statements indented by the same number of character spaces after a programming construct are considered to be part of a single block of code. Python uses indentation as its method of grouping statements. Example of Python While Loop : Let’s see a simple example of while loop in Python. # Python program to illustrate while loop count = 0 while (count < 3): count = count + 1 print("Hello Geek") Output: Hello Geek Hello Geek Hello Geek Using else statement with While Loop in Python: The else clause is only executed when your while condition becomes false. If you break out of the loop, or if an exception is raised, it won’t be executed. Syntax of While Loop with else statement: while condition: # execute these statements else: # execute these statements Examples of While Loop with else statement Here is an example of while loop with else statement in Python: # Python program to illustrate # combining else with while count = 0 while (count < 3): count = count + 1 print("Hello Geek") else: print("In Else Block") Output: Hello Geek Hello Geek Hello Geek In Else Block Infinite While Loop in Python: If we want a block of code to execute infinite number of time, we can use the while loop in Python to do so. # Python program to illustrate # Single statement while block count = 0 while (count == 0): print("Hello Geek") Program: Source Code: # Sum of natural numbers up to num num = 16 if num < 0: print("Enter a positive number") else: sum = 0 # use while loop to iterate until zero while(num > 0): sum += num num -= 1 print("The sum is", sum) Output: The sum is 136 20. How to use pass statement in python? Ans. The Python pass statement is a null statement. But the difference between pass and comment is that comment is ignored by the interpreter whereas pass is not ignored. The Syntax of the pass statement: pass Why Python Needs “pass” Statement? If we do not use pass or simply enter a comment or a blank here, we will receive an IndentationError error message. Examples of Python pass statement Let’s see some of the examples to understand pass statements in Python more clearly. Use of pass keyword in Function: Python Pass keyword can be used in empty functions. To read more click here def function: pass Use of pass keyword in Python Class: The pass keyword can also be used in an empty class in Python. class geekClass: pass Use of pass keyword in Python Loop : The pass keyword can be used in Python for loop, when a user doesn’t know what to code inside the loop in Python. n = 10 for i in range(n): # pass can be used as placeholder # when code is to added later pass Use of pass keyword in Conditional statement: Python pass keyword can be used with conditional statements. a = 10 b = 20 if(a2999) syntax error: invalid syntax Exceptions: Exceptions are raised when the program is syntactically correct, but the code results in an error. This error does not stop the execution of the program, however, it changes the normal flow of the program. Example: # initialize the amount variable marks = 10000 # perform division with 0 a = marks / 0 print(a) Output: Traceback (most recent call last): File "/home/f3ad05420ab851d4bd106ffb0422997.py", line 4, in a=mark/0 ZeroDivisonError: Divison by zero In the above example raised the ZeroDivisionError as we are trying to divide a number by 0. Note: Exception is the base class for all the exceptions in Python. You can check the exception hierarchy here. Try and Except Statement – Catching Exceptions Try and except statements are used to catch and handle exceptions in Python. Statements that can raise exceptions are kept inside the try clause and the statements that handle the exception are written inside except clause. Catching Specific Exception A try statement can have more than one except clause, to specify handlers for different exceptions. Please note that at most one handler will be executed. For example, we can add IndexError in the above code. The general syntax for adding specific exceptions are – try: # statement(s) except IndexError: # statement(s) except ValueError: # statement(s) Try with Else Clause In Python, you can also use the else clause on the try-except block which must be present after all the except clauses. The code enters the else block only if the try clause does not raise an exception. Finally Keyword in Python: Python provides a keyword finally, which is always executed after the try and except blocks. The final block always executes after the normal termination of the try block or after the try block terminates due to some exception. Raising Exception: The raise statement allows the programmer to force a specific exception to occur. The sole argument in raise indicates the exception to be raised. This must be either an exception instance or an exception class (a class that derives from Exception). Advantages of Exception Handling: Improved program reliability: By handling exceptions properly, you can prevent your program from crashing or producing incorrect results due to unexpected errors or input. Simplified error handling: Exception handling allows you to separate error handling code from the main program logic, making it easier to read and maintain your code. Disadvantages of Exception Handling: Performance overhead: Exception handling can be slower than using conditional statements to check for errors, as the interpreter has to perform additional work to catch and handle the exception. Increased code complexity: Exception handling can make your code more complex, especially if you have to handle multiple types of exceptions or implement complex error handling logic. 38. Explain Try, except and finally keyword with example. Ans. Try Except in Python: Try and Except statement is used to handle these errors within our code in Python. The try block is used to check some code for errors i.e the code inside the try block will execute when there is no error in the program. Whereas the code inside the except block will execute whenever the program encounters some error in the preceding try block. Syntax: try: # Some Code except: # Executed if error in the # try block How try() works? First, the try clause is executed i.e. the code between try. If there is no exception, then only the try clause will run, except clause is finished. If any exception occurs, the try clause will be skipped and except clause will run. If any exception occurs, but the except clause within the code doesn’t handle it, it is passed on to the outer try statements. If the exception is left unhandled, then the execution stops. A try statement can have more than one except clause Code 1: No exception, so the try clause will run. # Python code to illustrate # working of try() def divide(x, y): try: # Floor Division : Gives only Fractional Part as Answer result = x // y print("Yeah ! Your answer is :", result) except ZeroDivisionError: print("Sorry ! You are dividing by zero ") # Look at parameters and note the working of Program divide(3, 2) Auxiliary Space: O(1) Output : Yeah ! Your answer is : 1 Finally Keyword in Python: Python provides a keyword finally, which is always executed after the try and except blocks. The final block always executes after the normal termination of the try block or after the try block terminates due to some exceptions. Syntax: try: # Some Code except: # Executed if error in the # try block else: # execute if no exception finally: # Some code .....(always executed) Code: # Python program to demonstrate finally # No exception Exception raised in try block try: k = 5//0 # raises divide by zero exception. print(k) # handles zerodivision exception except ZeroDivisionError: print("Can't divide by zero") finally: # this block is always executed # regardless of exception generation. print('This is always executed') Output: Can't divide by zero This is always executed 39. Explain different types of file access modes. Ans. File Handling in Python : File handling is an important activity in every web app. The types of activities that you can perform on the opened file are controlled by Access Modes. These describe how the file will be used after it has been opened. These modes also specify where the file handle should be located within the file. Similar to a pointer, a file handle indicates where data should be read or put into the file. In Python, there are six methods or access modes, which are: Read Only ('r’): This mode opens the text files for reading only. The start of the file is where the handle is located. It raises the I/O error if the file does not exist. This is the default mode for opening files as well. Read and Write ('r+’): This method opens the file for both reading and writing. The start of the file is where the handle is located. If the file does not exist, an I/O error gets raised. Write Only ('w’): This mode opens the file for writing only. The data in existing files are modified and overwritten. The start of the file is where the handle is located. If the file does not already exist in the folder, a new one gets created. Write and Read ('w+’): This mode opens the file for both reading and writing. The text is overwritten and deleted from an existing file. The start of the file is where the handle is located. Append Only ('a’): This mode allows the file to be opened for writing. If the file doesn't yet exist, a new one gets created. The handle is set at the end of the file. The newly written data will be added at the end, following the previously written data. Append and Read (‘a+’): Using this method, you can read and write in the file. If the file doesn't already exist, one gets created. The handle is set at the end of the file. The newly written text will be added at the end, following the previously written data. How to Write to a File in Python: There are two methods of writing to a file in Python, which are: The write() method: This function inserts the string into the text file on a single line. Based on the file we have created above, the below line of code will insert the string into the created text file, which is "myfile.txt.” file.write("Hello There\n") The writelines() method: This function inserts multiple strings at the same time. A list of string elements is created, and each string is then added to the text file. Using the previously created file above, the below line of code will insert the string into the created text file, which is "myfile.txt.” f.writelines(["Hello World ", "You are welcome to Fcc\n"]) The readline() method: This function reads a line from a file and returns it as a string. It reads at most n bytes for the specified n. But even if n is greater than the length of the line, it does not read more than one line. f = open("myfiles.txt", "r") print(f.readline()) The readlines() method: This function reads all of the lines and returns them as string elements in a list, one for each line. You can read the first two lines by calling readline() twice, reading the first two lines of the file: f = open("myfiles.txt", "r") print(f.readline()) print(f.readline()) 40. How to open and close .txt file in python? Ans. Opening a file in Python: There are two types of files that can be handled in Python, normal text files and binary files (written in binary language, 0s, and 1s). Opening a file refers to getting the file ready either for reading or for writing. This can be done using the open() function. This function returns a file object and takes two arguments, one that accepts the file name and another that accepts the mode(Access Mode). Note: The file should exist in the same directory as the Python script, otherwise, the full address of the file should be written. Syntax: File_object = open(“File_Name”, “Access_Mode”) Parameters: File_Name: It is the name of the file that needs to be opened. Access_Mode: Access modes govern the type of operations possible in the opened file. The below table gives the list of all access mode available in python Example 1: Open and read a file using Python # open the file using open() function file = open("sample.txt") # Reading from file print(file.read()) Output: Hello Geek! This is a sample text file for the example. Closing a file in Python: As you notice, we have not closed any of the files that we operated on in the above examples. Though Python automatically closes a file if the reference object of the file is allocated to another file, it is a standard practice to close an opened file as a closed file reduces the risk of being unwarrantedly modified or read. Python has a close() method to close a file. The close() method can be called more than once and if any operation is performed on a closed file it raises a ValueError. The below code shows a simple use of close() method to close an opened file. Example: Read and close the file using Python # open the file using open() function file = open("sample.txt") # Reading from file print(file.read()) # closing the file file.close() # Attempt to write in the file file.write(" Attempt to write on a closed file !") Output: ValueError: I/O operation on closed file. 41. How to create MySQL database connection using python. Ans. Creating MySQL Database: To create a database, we will use CREATE DATABASE database_name statement and we will execute this statement by creating an instance of the ‘cursor’ class. import mysql.connector mydb = mysql.connector.connect( host = "localhost", user = "yourusername", password = "your_password" ) # Creating an instance of 'cursor' class # which is used to execute the 'SQL' # statements in 'Python' cursor = mydb.cursor() # Creating a database with a name # 'geeksforgeeks' execute() method # is used to compile a SQL statement # below statement is used to create # the 'geeksforgeeks' database cursor.execute("CREATE DATABASE geeksforgeeks") Output: If the database with the name ‘geeksforgeeks’ already exists then you will get an error, otherwise no error. So make sure that the new database that you are creating does not have the same name as the database already you created or exists previously. Now to check the databases that you created, use “SHOW DATABASES” – SQL statement i.e. cursor.execute(“SHOW DATABASES”) Notes: mysql.connector allows Python programs to access MySQL databases. connect() method of the MySQL Connector class with the arguments will connect to MySQL and would return a MySQLConnection object if the connection is established successfully. user = “yourusername”, here “yourusername” should be the same username as you set during MySQL installation. password = “your_password”, here “your_password” should be the same password as you set during MySQL installation. cursor() is used to execute the SQL statements in Python. execute() method is used to compile a SQL statement. ..
- JAVA Que. Bank Sem-4 BCA
UNIT : 1 1. Explain below term. I) Byte Code II)JVM Ans. Java bytecode is the instruction set for the Java Virtual Machine. It acts similar to an assembler which is an alias representation of a C++ code. As soon as a java program is compiled, java bytecode is generated. In more apt terms, java bytecode is the machine code in the form of a .class file. With the help of java bytecode we achieve platform independence in java. Advantage of Java Bytecode : Platform independence is one of the soul reasons for which James Gosling started the formation of java and it is this implementation of bytecode which helps us to achieve this. Hence bytecode is a very important component of any java program. The set of instructions for the JVM may differ from system to system but all can interpret the bytecode. A point to keep in mind is that bytecodes are non-runnable codes and rely on the availability of an interpreter to execute and thus the JVM comes into play. JVM : JVM (Java Virtual Machine) is an abstract machine. It is a specification that provides runtime environment in which java bytecode can be executed. JVMs are available for many hardware and software platforms (i.e. JVM is platform dependent). What is JVM : It is: 1. A specification where working of Java Virtual Machine is specified. But implementation provider is independent to choose the algorithm. Its implementation has been provided by Oracle and other companies. 2. An implementation Its implementation is known as JRE (Java Runtime Environment). 3. Runtime Instance Whenever you write java command on the command prompt to run the java class, an instance of JVM is created. What it does: The JVM performs following operation: Loads code Verifies code Executes code Provides runtime environment JVM provides definitions for the: Memory area Class file format Register set Garbage-collected heap Fatal error reporting etc. 2. Explain features of JAVA. Ans. The primary objective of Java programming language creation was to make it portable, simple and secure programming language. Apart from this, there are also some excellent features which play an important role in the popularity of this language. The features of Java are also known as Java buzzwords. Simple: Java is very easy to learn, and its syntax is simple, clean and easy to understand. According to Sun Microsystem, Java language is a simple programming language because: Java syntax is based on C++ (so easier for programmers to learn it after C++). Java has removed many complicated and rarely-used features, for example, explicit pointers, operator overloading, etc. There is no need to remove unreferenced objects because there is an Automatic Garbage Collection in Java. Object-oriented: Java is an object-oriented programming language. Everything in Java is an object. Object-oriented means we organize our software as a combination of different types of objects that incorporate both data and behavior. Object-oriented programming (OOPs) is a methodology that simplifies software development and maintenance by providing some rules. Platform Independent: Java is platform independent because it is different from other languages like C, C++, etc. which are compiled into platform specific machines while Java is a write once, run anywhere language. A platform is the hardware or software environment in which a program runs. There are two types of platforms software-based and hardware-based. Java provides a software-based platform. Secured: Java is best known for its security. With Java, we can develop virus-free systems. Java is secured because: No explicit pointer Java Programs run inside a virtual machine sandbox Classloader: Classloader in Java is a part of the Java Runtime Environment (JRE) which is used to load Java classes into the Java Virtual Machine dynamically. It adds security by separating the package for the classes of the local file system from those that are imported from network sources. Bytecode Verifier: It checks the code fragments for illegal code that can violate access rights to objects. Security Manager: It determines what resources a class can access such as reading and writing to the local disk. Robust: The English mining of Robust is strong. Java is robust because: It uses strong memory management. There is a lack of pointers that avoids security problems. Java provides automatic garbage collection which runs on the Java Virtual Machine to get rid of objects which are not being used by a Java application anymore. There are exception handling and the type checking mechanism in Java. All these points make Java robust. Architecture-neutral : Java is architecture neutral because there are no implementation dependent features, for example, the size of primitive types is fixed. In C programming, int data type occupies 2 bytes of memory for 32-bit architecture and 4 bytes of memory for 64-bit architecture. However, it occupies 4 bytes of memory for both 32 and 64-bit architectures in Java. Portable : Java is portable because it facilitates you to carry the Java bytecode to any platform. It doesn't require any implementation. High-performance: Java is faster than other traditional interpreted programming languages because Java bytecode is "close" to native code. It is still a little bit slower than a compiled language (e.g., C++). Java is an interpreted language that is why it is slower than compiled languages, e.g., C, C++, etc. Distributed : Java is distributed because it facilitates users to create distributed applications in Java. RMI and EJB are used for creating distributed applications. This feature of Java makes us able to access files by calling the methods from any machine on the internet. Multi-threaded: A thread is like a separate program, executing concurrently. We can write Java programs that deal with many tasks at once by defining multiple threads. The main advantage of multi-threading is that it doesn't occupy memory for each thread. It shares a common memory area. Threads are important for multi-media, Web applications, etc. Dynamic : Java is a dynamic language. It supports the dynamic loading of classes. It means classes are loaded on demand. It also supports functions from its native languages, i.e., C and C++. 3. What is JAVA ? Explain Object Oriented Programming Concepts in Java. Ans. Java is a widely used object-oriented programming language and software platform that runs on billions of devices, including notebook computers, mobile devices, gaming consoles, medical devices and many others. The rules and syntax of Java are based on the C and C++ languages. One major advantage of developing software with Java is its portability. Once you have written code for a Java program on a notebook computer, it is very easy to move the code to a mobile device. When the language was invented in 1991 by James Gosling of Sun Microsystems (later acquired by Oracle), the primary goal was to be able to "write once, run anywhere." It's also important to understand that Java is much different from JavaScript. JavaScript does not need to be compiled, while Java code does need to be compiled. Also, JavaScript only runs on web browsers while Java can be run anywhere. Java OOPs Concepts : In this page, we will learn about the basics of OOPs. Object-Oriented Programming is a paradigm that provides many concepts, such as inheritance, data binding, polymorphism, etc. Simula is considered the first object-oriented programming language. The programming paradigm where everything is represented as an object is known as a truly object-oriented programming language. Smalltalk is considered the first truly object-oriented programming language. The popular object-oriented languages are Java, C#, PHP, Python, C++, etc. The main aim of object-oriented programming is to implement real-world entities, for example, object, classes, abstraction, inheritance, polymorphism, etc. OOPs (Object-Oriented Programming System): Object means a real-world entity such as a pen, chair, table, computer, watch, etc. Object-Oriented Programming is a methodology or paradigm to design a program using classes and objects. It simplifies software development and maintenance by providing some concepts: Object : Any entity that has state and behavior is known as an object. For example, a chair, pen, table, keyboard, bike, etc. It can be physical or logical. An Object can be defined as an instance of a class. An object contains an address and takes up some space in memory. Objects can communicate without knowing the details of each other's data or code. The only necessary thing is the type of message accepted and the type of response returned by the objects. Class: Collection of objects is called class. It is a logical entity. A class can also be defined as a blueprint from which you can create an individual object. Class doesn't consume any space. Inheritance: When one object acquires all the properties and behaviors of a parent object, it is known as inheritance. It provides code reusability. It is used to achieve runtime polymorphism. Polymorphism: If one task is performed in different ways, it is known as polymorphism. For example: to convince the customer differently, to draw something, for example, shape, triangle, rectangle, etc. In Java, we use method overloading and method overriding to achieve polymorphism. Another example can be to speak something; for example, a cat speaks meow, dog barks woof, etc. Abstraction: Hiding internal details and showing functionality is known as abstraction. For example phone call, we don't know the internal processing. In Java, we use abstract class and interface to achieve abstraction. Encapsulation: Binding (or wrapping) code and data together into a single unit are known as encapsulation. For example, a capsule, it is wrapped with different medicines. A java class is the example of encapsulation. Java bean is the fully encapsulated class because all the data members are private here. Coupling: Coupling refers to the knowledge or information or dependency of another class. It arises when classes are aware of each other. If a class has the details information of another class, there is strong coupling. In Java, we use private, protected, and public modifiers to display the visibility level of a class, method, and field. You can use interfaces for the weaker coupling because there is no concrete implementation. Cohesion: Cohesion refers to the level of a component which performs a single well-defined task. A single well-defined task is done by a highly cohesive method. The weakly cohesive method will split the task into separate parts. The java.io package is a highly cohesive package because it has I/O related classes and interface. However, the java.util package is a weakly cohesive package because it has unrelated classes and interfaces. Association: Association represents the relationship between the objects. Here, one object can be associated with one object or many objects. There can be four types of association between the objects: One to One One to Many Many to One, and Many to Many Let's understand the relationship with real-time examples. For example, One country can have one prime minister (one to one), and a prime minister can have many ministers (one to many). Also, many MP's can have one prime minister (many to one), and many ministers can have many departments (many to many). Association can be undirectional or bidirectional. Aggregation: Aggregation is a way to achieve Association. Aggregation represents the relationship where one object contains other objects as a part of its state. It represents the weak relationship between objects. It is also termed as a has-a relationship in Java. Like, inheritance represents the is-a relationship. It is another way to reuse objects. Composition: The composition is also a way to achieve Association. The composition represents the relationship where one object contains other objects as a part of its state. There is a strong relationship between the containing object and the dependent object. It is the state where containing objects do not have an independent existence. If you delete the parent object, all the child objects will be deleted automatically. 4. Explain Operators in JAVA. Ans. Operators in Java : Operator in Java is a symbol that is used to perform operations. For example: +, -, *, / etc. There are many types of operators in Java which are given below: Unary Operator, Arithmetic Operator, Shift Operator, Relational Operator, Bitwise Operator, Logical Operator, Ternary Operator and Assignment Operator. Java Unary Operator: The Java unary operators require only one operand. Unary operators are used to perform various operations i.e.: incrementing/decrementing a value by one negating an expression inverting the value of a Boolean Java Arithmetic Operators: Java arithmetic operators are used to perform addition, subtraction, multiplication, and division. They act as basic mathematical operations. Java Left Shift Operator: The Java left shift operator << is used to shift all of the bits in a value to the left side of a specified number of times. Java Right Shift Operator: The Java right shift operator >> is used to move the value of the left operand to right by the number of bits specified by the right operand. Java AND Operator Example: Logical && and Bitwise & The logical && operator doesn't check the second condition if the first condition is false. It checks the second condition only if the first one is true. The bitwise & operator always checks both conditions whether first condition is true or false. Java OR Operator Example: Logical || and Bitwise | The logical || operator doesn't check the second condition if the first condition is true. It checks the second condition only if the first one is false. Java Ternary Operator: Java Ternary operator is used as one line replacement for if-then-else statement and used a lot in Java programming. It is the only conditional operator which takes three operands. Java Assignment Operator: Java assignment operator is one of the most common operators. It is used to assign the value on its right to the operand on its left. 5. Explain briefly any 3 data types used in JAVA. Ans. Data Types in Java : Data types specify the different sizes and values that can be stored in the variable. There are two types of data types in Java: Primitive data types: The primitive data types include Boolean, char, byte, short, int, long, float and double. Non-primitive data types: The non-primitive data types include Classes, Interfaces, and Arrays. Java Primitive Data Types : In Java language, primitive data types are the building blocks of data manipulation. These are the most basic data types available in Java language. There are 8 types of primitive data types: Boolean data type byte data type char data type short data type int data type long data type float data type double data type Boolean Data Type: The Boolean data type is used to store only two possible values: true and false. This data type is used for simple flags that track true/false conditions. The Boolean data type specifies one bit of information, but its "size" can't be defined precisely. EX. Boolean one = false Byte Data Type: The byte data type is an example of primitive data type. It isan 8-bit signed two's complement integer. Its value-range lies between -128 to 127 (inclusive). Its minimum value is -128 and maximum value is 127. Its default value is 0. The byte data type is used to save memory in large arrays where the memory savings is most required. It saves space because a byte is 4 times smaller than an integer. It can also be used in place of "int" data type. EX. byte a = 10, byte b = -20 Short Data Type: The short data type is a 16-bit signed two's complement integer. Its value-range lies between -32,768 to 32,767 (inclusive). Its minimum value is -32,768 and maximum value is 32,767. Its default value is 0. The short data type can also be used to save memory just like byte data type. A short data type is 2 times smaller than an integer. EX. short s = 10000, short r = -5000 Int Data Type: The int data type is a 32-bit signed two's complement integer. Its value-range lies between - 2,147,483,648 (-2^31) to 2,147,483,647 (2^31 -1) (inclusive). Its minimum value is - 2,147,483,648and maximum value is 2,147,483,647. Its default value is 0. The int data type is generally used as a default data type for integral values unless if there is no problem about memory. EX. int a = 100000, int b = -200000 Float Data Type: The float data type is a single-precision 32-bit IEEE 754 floating point. Its value range is unlimited. It is recommended to use a float (instead of double) if you need to save memory in large arrays of floating point numbers. The float data type should never be used for precise values, such as currency. Its default value is 0.0F. EX. float f1 = 234.5f Double Data Type: The double data type is a double-precision 64-bit IEEE 754 floating point. Its value range is unlimited. The double data type is generally used for decimal values just like float. The double data type also should never be used for precise values, such as currency. Its default value is 0.0d. EX. double d1 = 12.3 UNIT 2 : 1. Define term - Constant, Literals and Variable in Java. Ans. Constant: Constant is a value that cannot be changed after assigning it. Java does not directly support the constants. There is an alternative way to define the constants in Java by using the non-access modifiers static and final. In Java, to declare any variable as constant, we use static and final modifiers. It is also known as non-access modifiers. According to the Java naming convention the identifier name must be in capital letters. Static and Final Modifiers: The purpose to use the static modifier is to manage the memory. It also allows the variable to be available without loading any instance of the class in which it is defined. The final modifier represents that the value of the variable cannot be changed. It also makes the primitive data type immutable or unchangeable. Why we use constants? The use of constants in programming makes the program easy and understandable which can be easily understood by others. It also affects the performance because a constant variable is cached by both JVM and the application. Literals : In Java, literal is a notation that represents a fixed value in the source code. In lexical analysis, literals of a given type are generally known as tokens. In this section, we will discuss the term literals in Java. In Java, literals are the constant values that appear directly in the program. It can be assigned directly to a variable. Java has various types of literals. The following figure represents a literal. Types of Literals in Java: There are the majorly four types of literals in Java: Integer Literal Character Literal Boolean Literal String Literal Why use literals? To avoid defining the constant somewhere and making up a label for it. Instead, to write the value of a constant operand as a part of the instruction. Variable: A variable is a container which holds the value while the Java program is executed. A variable is assigned with a data type. Variable is a name of memory location. There are three types of variables in java: local, instance and static. There are two types of data types in Java: primitive and non-primitive. A variable is the name of a reserved area allocated in memory. In other words, it is a name of the memory location. It is a combination of "vary + able" which means its value can be changed. Types of Variables: There are three types of variables in Java: local variable instance variable static variable 1) Local Variable: A variable declared inside the body of the method is called local variable. You can use this variable only within that method and the other methods in the class aren't even aware that the variable exists. A local variable cannot be defined with "static" keyword. 2) Instance Variable: A variable declared inside the class but outside the body of the method, is called an instance variable. It is not declared as static. It is called an instance variable because its value is instance-specific and is not shared among instances. 3) Static variable: A variable that is declared as static is called a static variable. It cannot be local. You can create a single copy of the static variable and share it among all the instances of the class. Memory allocation for static variables happens only once when the class is loaded in the memory. 2. Define string class with its all methods. Ans. In Java, string is basically an object that represents sequence of char values. An array of characters works same as Java string. For example: char[] ch={'j','a','v','a','t','p','o','i','n','t'}; String s=new String(ch); is same as: String s="javatpoint"; Java String class provides a lot of methods to perform operations on strings such as compare(), concat(), equals(), split(), length(), replace(), compareTo(), intern(), substring() etc. The java.lang.String class implements Serializable, Comparable and CharSequence interfaces. What is String in Java? Generally, String is a sequence of characters. But in Java, string is an object that represents a sequence of characters. The java.lang.String class is used to create a string object. There are two ways to create String object: By string literal By new keyword Java String class methods : The java.lang.String class provides many useful methods to perform operations on sequence of char values. No. Method ➡️ Description : char charAt(int index) ➡️ It returns char value for the particular index int length() ➡️ It returns string length static String format(String format, Object... args) ➡️ It returns a formatted string. static String format(Locale l, String format, Object... args) ➡️ It returns formatted string with given locale. String substring(int beginIndex) ➡️ It returns substring for given begin index. String substring(int beginIndex, int endIndex) ➡️ It returns substring for given begin index and end index. boolean contains(CharSequence s) ➡️ It returns true or false after matching the sequence of char value. static String join(CharSequence delimiter, CharSequence... elements) ➡️ It returns a joined string. static String join(CharSequence delimiter, Iterable elements) ➡️ It returns a joined string. boolean equals(Object another) ➡️ It checks the equality of string with the given object. boolean isEmpty() ➡️ It checks if string is empty. String concat(String str) ➡️ It concatenates the specified string. String replace(char old, char new) ➡️ It replaces all occurrences of the specified char value. String replace(CharSequence old, CharSequence new) ➡️ It replaces all occurrences of the specified CharSequence. static String equalsIgnoreCase(String another) ➡️ It compares another string. It doesn't check case. String[] split(String regex) ➡️ It returns a split string matching regex. String[] split(String regex, int limit) ➡️ It returns a split string matching regex and limit. String intern() ➡️ It returns an interned string. int indexOf(int ch) ➡️ It returns the specified char value index. int indexOf(int ch, int fromIndex) ➡️ It returns the specified char value index starting with given index. int indexOf(String substring) ➡️ It returns the specified substring index. int indexOf(String substring, int fromIndex) ➡️ It returns the specified substring index starting with given index. String toLowerCase() ➡️ It returns a string in lowercase. String toLowerCase(Locale l) ➡️ It returns a string in lowercase using specified locale. String toUpperCase() ➡️ It returns a string in uppercase. String toUpperCase(Locale l) ➡️ It returns a string in uppercase using specified locale. String trim() ➡️ It removes beginning and ending spaces of this string. static String valueOf(int value) ➡️ It converts given type into string. It is an overloaded method. 3. What is Array? Explain different types of array with examples. Ans. Array:- An array is a data structure that contains a group of elements. Typically these elements are all of the same data type, such as an integer or string. Arrays are commonly used in computer programs to organize data so that a related set of values can be easily sorted or searched Arrays can of following types: 1. One dimensional (1-D) arrays or Linear arrays: In it each element is represented by a single subscript. The elements are stored in consecutive memory locations. E.g. A [1], A [2], ….., A [N]. 2. Multi dimensional arrays: (a) Two dimensional (2-D) arrays or Matrix arrays: In it each element is represented by two subscripts. Thus a two dimensional m x n array A has m rows and n columns and contains m*n elements. It is also called matrix array because in it the elements form a matrix. E.g. A [2] [3] has 2 rows and 3 columns and 2*3 = 6 elements. (b) Three dimensional arrays: In it each element is represented by three subscripts. Thus a three dimensional m x n x l array A contains m*n*l elements. E.g. A [2] [3] [2] has 2*3*2 = 12 elements. 4. What is Conditional Statement? Explain any two with examples. Ans. Conditional statements help you to make a decision based on certain conditions. These conditions are specified by a set of conditional statements having Boolean expressions which are evaluated to a Boolean value of true or false. In our life, we frequently encounter certain situations where we have to make a decision be it your favorite food, movie, hobby, or the color of our shoes. In C programming also, you may encounter similar kinds of situations where you need to make a decision based on the two possibilities that are yes/no or true/false acceptance, we will learn all about the conditional statements in this article. There are the following types of conditional statements in C. If statement If-Else statement Nested If-else statement If-Else If ladder Switch statement If statement: The single if statement in C language is used to execute the code if a condition is true. It is also called a one-way selection statement. When we use the if condition, we pass the argument and if the argument will be satisfied then the respective code will be executed otherwise nothing can happen. Below is the if statement followed by the conditional expression. Syntax: if(expression) { //code to be executed } if Statement Example: #include #include void main() { int num=0; printf("enter the number"); scanf("%d",&num); if(n%2==0) { printf("%d number in even",num); } getch(); } If-else statement: The if-else statement in C language is used to execute the code if the condition is true or false. It is also called a two-way selection statement. The single if statement may work pretty well, but if you want to work with multiple variables or the extended conditional parameters, then the if-else statement is the optimum choice. By using the if statement, only one block of the code executes after the condition is true but by using the if-else statement, there are two possible blocks of code where the first block is used for handling the success part and the other one for the failure condition. Syntax: if(expression) { //Statements } else { //Statements } if..else Statement Example: #include #include void main() { int num=0; printf("enter the number"); scanf("%d",&num); if(n%2==0) { printf("%d number in even", num); } else { printf("%d number in odd",num); } getch(); } Switch Statement: switch statement acts as a substitute for a long if-else-if ladder that is used to test a list of cases. A switch statement contains one or more case labels that are tested against the switch expression. When the expression match to a case then the associated statements with that case would be executed. We have seen the way of using conditional statements such as if, if-else. if-else ladder, but the need for an additional way of dealing with conditional statements may seem unnecessary but based on the certain usage, switch case was defined to check for the single condition, and based on the multiple cases, code can be executed. Below is the basic syntax that shows how to use and implement a switch statement. Syntax: Switch (expression) { case value1: //Statements break; case value 2: //Statements break; case value 3: //Statements case value n: //Statements break; Default: //Statements } switch statement Example: #include #include void main( ) { char grade = 'B'; if (grade == 'A') { printf("Excellent!"); } else if (grade == 'B') { printf("Well done"); } else if (grade == 'D') { printf("You passed"); } else if (grade == 'F') { printf("Better try again"); } else { printf("You Failed!"); } } getch(); } 5. What is Loop Statement ? Explain any two with example. Ans. The Java for loop is used to iterate a part of the program several times. If the number of iteration is fixed, it is recommended to use for loop. There are three types of for loops in Java. Simple for Loop For-each or Enhanced for Loop Labeled for Loop Java for-each Loop: The for-each loop is used to traverse array or collection in Java. It is easier to use than simple for loop because we don't need to increment value and use subscript notation. It works on the basis of elements and not the index. It returns element one by one in the defined variable. Syntax: for(data_type variable : array_name){ //code to be executed } Example: ForEachExample.java //Java For-each loop example which prints the //elements of the array public class ForEachExample { public static void main(String[] args) { //Declaring an array int arr[]={12,23,44,56,78}; //Printing array using for-each loop for(int i:arr){ System.out.println(i); } } } Output: 12 23 44 56 78 Java Labeled For Loop : We can have a name of each Java for loop. To do so, we use label before the for loop. It is useful while using the nested for loop as we can break/continue specific for loop. Syntax: labelname: for(initialization; condition; increment/decrement){ //code to be executed } Example: LabeledForExample.java //A Java program to demonstrate the use of labeled for loop public class LabeledForExample { public static void main(String[] args) { //Using Label for outer and for loop aa: for(int i=1;i<=3;i++){ bb: for(int j=1;j<=3;j++){ if(i==2&&j==2){ break aa; } System.out.println(i+" "+j); } } } } Output: 1 1 1 2 1 3 2 1 6. Explain Array.Sort(),Array.Fill(),Array.BinarySearch() with example. Ans. Array class is a class containing static methods that are used with arrays in order to search, sort, compare, insert elements, or return a string representation of an array. So let us specify the functions first and later onwards we will be discussing the same. They are as follows being present in java.util.Arrays class. Here we will be discussing different plots using the sort() method of the Arrays class. Arrays.sort() method consists of two variations one in which we do not pass any arguments where it sort down the complete array be it integer array or character array but if we are supposed to sort a specific part using this method of Arrays class then we overload it and pass the starting and last index to the array. Syntax: sort() Method Arrays.sort(); Syntax: Overloaded sort() Method public static void sort(int[] arr, int from_Index, int to_Index) ; Parameters: It takes three parameters as can be perceived from the syntax which is as follows: The array to be sorted The index of the first element, inclusive, to be sorted (Referred to as from_index) The index of the last element, exclusive, to be sorted (Referred to as last_index) EX. : import java.util.Arrays; class GFG { public static void main(String args[]) { int[] arr = { 5, -2, 23, 7, 87, -42, 509 }; System.out.println("The original array is: "); for (int num : arr) { System.out.print(num + " "); } Arrays.sort(arr); System.out.println("\nThe sorted array is: "); for (int num : arr) { System.out.print(num + " "); } } } OUTPUT: The original array is: 5 -2 23 7 87 -42 509 The sorted array is: -42 -2 5 7 23 87 509 Array.Fill() : By using the Arrays.fill() method, we can either fill a complete array or can fill some part of it. Arrays.fill() method is also capable of filling both the 2D and the 3D Arrays. Arrays fill() method has the following syntax: Java.util.Arrays.fill(boolean[] arr, int fromIndex, int toIndex, boolean val ) The arr parameter defines an array to be filled. The formIndex parameter defines the index of the first element to be filled with the given value. The toIndex parameter defines the index of the last index to be filled with the given value. The val parameter defines the value to be stored in all elements of the given array. EX. : // import required classes and packages package javaTpoint.MicrosoftJava; import java.util.Arrays; import java.util.Scanner; // create ArraysFillExample4 to fill 3D array with the given value public class ArraysFillExample4 { //main() method start public static void main(String[] args) { int ele; // create scanner class object Scanner sc = new Scanner(System.in); System.out.print("Enter the size of the array: \n"); System.out.print("x : "); int x = sc.nextInt(); System.out.print("y : "); int y = sc.nextInt(); System.out.print("z : "); int z = sc.nextInt(); // create an array of size row*column int threeDArray[][][] = new int[x][y][z]; System.out.println("Enter the elements in the array: "); for(int i=0; i < threeDArray.length; i++){ for(int j=0; j < threeDArray[i].length; j++){ for(int k=0; k < threeDArray[i][j].length; k++){ System.out.println("Enter element ["+i+"]["+j+"]["+k+"]"); threeDArray[i][j][k] = sc.nextInt(); } } } System.out.print("Enter the element which you want to fill in the array: \n\n"); ele = sc.nextInt(); System.out.println("3D array after inserting elements: \n\n"); System.out.println(Arrays.deepToString(threeDArray)); // fill complete array with ele for (int[][] newRow : threeDArray) { for (int[] newRowColumn : newRow) { Arrays.fill(newRowColumn, ele); } } System.out.println("After filling" +ele+ " in the array:\n\n" + Arrays.deepToString(threeDArray)); sc.close(); } } OUTPUT: Array.BinarySearch() : Binary search is used to search a key element from multiple elements. Binary search is faster than linear search. In case of binary search, array elements must be in ascending order. If you have unsorted array, you can sort the array using Arrays.sort(arr) method. Binary Search Example in Java using Arrays.binarySearch() : import java.util.Arrays; class BinarySearchExample2{ public static void main(String args[]){ int arr[] = {10,20,30,40,50}; int key = 30; int result = Arrays.binarySearch(arr,key); if (result < 0) System.out.println("Element is not found!"); else System.out.println("Element is found at index: "+result); } } Output: Element is found at index: 2 7. Explain pass by value and pass by reference concept with example. Ans. Pass By Value: In Pass by value, function is called by directly passing the value of the variable as an argument. So any changes made inside the function does not affect the original value. In Pass by value, parameters passed as an arguments create its own copy. So any changes made inside the function is made to the copied value not to the original value . Let us take an example to understand better: function Passbyvalue(a, b) { let tmp; tmp = b; b = a; a = tmp; console.log(`Inside Pass by value function -> a = ${a} b = ${b}`); } let a = 1; let b = 2; console.log(`Before calling Pass by value Function -> a = ${a} b = ${b}`); Passbyvalue(a, b); console.log(`After calling Pass by value Function -> a =${a} b = ${b}`); Output: Before calling Pass by value Function -> a = 1 b = 2 Inside Pass by value function -> a = 2 b = 1 After calling Pass by value Function -> a =1 b = 2 Pass by Reference: In Pass by Reference, Function is called by directly passing the reference/address of the variable as an argument. So changing the value inside the function also change the original value. In JavaScript array and Object follows pass by reference property. In Pass by reference, parameters passed as an arguments does not create its own copy, it refers to the original value so changes made inside function affect the original value. let us take an example to understand better: function PassbyReference(obj) { let tmp = obj.a; obj.a = obj.b; obj.b = tmp; console.log(`Inside Pass By Reference Function -> a = ${obj.a} b = ${obj.b}`); } let obj = { a: 10, b: 20 } console.log(`Before calling Pass By Reference Function -> a = ${obj.a} b = ${obj.b}`); PassbyReference(obj) console.log(`After calling Pass By Reference Function -> a = ${obj.a} b = ${obj.b}`); Output: Before calling Pass By Reference Function -> a = 10 b = 20 Inside Pass By Reference Function -> a = 20 b = 10 After calling Pass By Reference Function -> a = 20 b = 10 UNIT 3 : 1. Discuss Accessibility of Access modifiers in different condition. Ans. There are four types of Java access modifiers: Private: The access level of a private modifier is only within the class. It cannot be accessed from outside the class. Default: The access level of a default modifier is only within the package. It cannot be accessed from outside the package. If you do not specify any access level, it will be the default. Protected: The access level of a protected modifier is within the package and outside the package through child class. If you do not make the child class, it cannot be accessed from outside the package. Public: The access level of a public modifier is everywhere. It can be accessed from within the class, outside the class, within the package and outside the package. There are many non-access modifiers, such as static, abstract, synchronized, native, volatile, transient, etc. Here, we are going to learn the access modifiers only. 1) Private: The private access modifier is accessible only within the class. Simple example of private access modifier: In this example, we have created two classes A and Simple. A class contains private data member and private method. We are accessing these private members from outside the class, so there is a compile-time error. class A{ private int data=40; private void msg(){System.out.println("Hello java");} } public class Simple{ public static void main(String args[]){ A obj=new A(); System.out.println(obj.data);//Compile Time Error obj.msg();//Compile Time Error } } Role of Private Constructor If you make any class constructor private, you cannot create the instance of that class from outside the class. For example: class A{ private A(){}//private constructor void msg(){System.out.println("Hello java");} } public class Simple{ public static void main(String args[]){ A obj=new A();//Compile Time Error } } 2) Default : If you don't use any modifier, it is treated as default by default. The default modifier is accessible only within package. It cannot be accessed from outside the package. It provides more accessibility than private. But, it is more restrictive than protected, and public. Example of default access modifier: In this example, we have created two packages pack and mypack. We are accessing the A class from outside its package, since A class is not public, so it cannot be accessed from outside the package. //save by A.java package pack; class A{ void msg(){System.out.println("Hello");} } //save by B.java package mypack; import pack.*; class B{ public static void main(String args[]){ A obj = new A();//Compile Time Error obj.msg();//Compile Time Error } } In the above example, the scope of class A and its method msg() is default so it cannot be accessed from outside the package. 3) Protected : The protected access modifier is accessible within package and outside the package but through inheritance only. The protected access modifier can be applied on the data member, method and constructor. It can't be applied on the class. It provides more accessibility than the default modifier. Example of protected access modifier: In this example, we have created the two packages pack and mypack. The A class of pack package is public, so can be accessed from outside the package. But msg method of this package is declared as protected, so it can be accessed from outside the class only through inheritance. //save by A.java package pack; public class A{ protected void msg(){System.out.println("Hello");} } //save by B.java package mypack; import pack.*; class B extends A{ public static void main(String args[]){ B obj = new B(); obj.msg(); } } Output: Hello 4) Public: The public access modifier is accessible everywhere. It has the widest scope among all other modifiers. Example of public access modifier: //save by A.java package pack; public class A{ public void msg(){System.out.println("Hello");} } //save by B.java package mypack; import pack.*; class B{ public static void main(String args[]){ A obj = new A(); obj.msg(); } } Output: Hello Java Access Modifiers with Method Overriding: If you are overriding any method, overridden method (i.e. declared in subclass) must not be more restrictive. class A{ protected void msg(){System.out.println("Hello java");} } public class Simple extends A{ void msg(){System.out.println("Hello java");}//C.T.Error public static void main(String args[]){ Simple obj=new Simple(); obj.msg(); } } The default modifier is more restrictive than protected. That is why, there is a compile-time error. 2. Discuss final and static method with example. Ans. Static methods are class level so there are not part of object. So we can not override static methods but we can call super class static method using subclass name or instance also. If we are trying to override static methods in sub class from super class then it will be method hiding not method overriding. Means whenever we call the static method on super class will call super class static method and if we are calling method using sub class it will call sub class method. So it is clear that static methods are hidden not overridden and they are part of class means class level not object level. Now the question is can a method be static and final together? For non static methods if we declare it as final then we are preventing that method from overriding so it can not be overridden in sub class. When we declare static method as final its prevents from method hiding. When we declare final static method and override in sub class then compiler shows an error Compile time error: Cannot override the final method from Super Lets see an example program to understand this better. Static methods in java: Program #1: Java example program to explain about static method in java: package inheritance Interview Programs; /* * @website: www.instanceofjava.com * @category: Deference between static and final static methods in java */ public class Super { static void method(){ System.out.println("Super class method"); } } package inheritance Interview Programs; // www.instanceofjava.com public class Sub extends Super { static void method(){ System.out.println("Sub class method"); } public static void main (String args[]) { Super.method(); Sub.method(); } } Output: Super class method Sub class method When we override static methods its not overriding it is method hiding and whenever we call method on class name it will call corresponding class method. If we call methods using objects it will call same methods. Program #2: Java example program to explain about calling super class static method using sub class in java: package inheritanceInterviewPrograms; /* * @website: www.instanceofjava.com * @category: Deference between static and final static methods in java */ public class Super { static void method(){ System.out.println("Super class method"); } } package inheritanceInterviewPrograms; // www.instanceofjava.com public class Sub extends Super { public static void main (String args[]) { Super.method(); Sub.method(); } } Output: Super class method Super class method We can call super class static methods using sub class object or sub class name also. Final static methods in java: Can a method be static and final together in java? When we declare a method as final we can not override that method in sub class. In the same way when we declare a static method as final we can not hide it in sub class means we can not create same method in sub class. If we try to create same static method in sub class compiler will throw an error. Lets see a java example program on final static methods in inheritance. Program #3: Java example program to explain about final static method in java : package inheritance Interview Programs; /* * @website: www.instanceofjava.com * @category: Deference between staic and final static methods in java */ public class Super { final static void method(){ System.out.println("Super class method"); } } package inheritanceInterviewPrograms; // www.instanceofjava.com public class Sub extends Super { static void method(){ // compiler time error: System.out.println("Sub class method"); } public static void main (String args[]) { Super.method(); Sub.method(); } } Output: 3. Difference between Abstract Class and interface. Ans. Abstract class and interface both are used to achieve abstraction where we can declare the abstract methods. Abstract class and interface both can't be instantiated. 4. What is multithreading? Why it is required? Explain Thread Life Cycle. ANS. Java is a multi-threaded programming language which means we can develop multi-threaded program using Java. A multi-threaded program contains two or more parts that can run concurrently and each part can handle a different task at the same time making optimal use of the available resources specially when your computer has multiple CPUs. By definition, multitasking is when multiple processes share common processing resources such as a CPU. Multi-threading extends the idea of multitasking into applications where you can subdivide specific operations within a single application into individual threads. Each of the threads can run in parallel. The OS divides processing time not only among different applications, but also among each thread within an application. Multi-threading enables you to write in a way where multiple activities can proceed concurrently in the same program. Life Cycle of a Thread: A thread goes through various stages in its life cycle. For example, a thread is born, started, runs, and then dies. The following diagram shows the complete life cycle of a thread. Following are the stages of the life cycle − New − A new thread begins its life cycle in the new state. It remains in this state until the program starts the thread. It is also referred to as a born thread. Runnable − After a newly born thread is started, the thread becomes runnable. A thread in this state is considered to be executing its task. Waiting − Sometimes, a thread transitions to the waiting state while the thread waits for another thread to perform a task. A thread transitions back to the runnable state only when another thread signals the waiting thread to continue executing. Timed Waiting − A runnable thread can enter the timed waiting state for a specified interval of time. A thread in this state transitions back to the runnable state when that time interval expires or when the event it is waiting for occurs. Terminated (Dead) − A runnable thread enters the terminated state when it completes its task or otherwise terminates. 5. What is difference between method overloading and method overriding. ANS. There are many differences between method overloading and method overriding in java. A list of differences between method overloading and method overriding are given below: Java Method Overloading example: class OverloadingExample{ static int add(int a,int b){return a+b;} static int add(int a,int b,int c){return a+b+c;} } Java Method Overriding example: class Animal{ void eat(){System.out.println("eating...");} } class Dog extends Animal{ void eat(){System.out.println("eating bread...");} } 6. Explain Inheritance with example. ANS. Inheritance in Java is a mechanism in which one object acquires all the properties and behaviors of a parent object. It is an important part of OOPs (Object Oriented programming system). The idea behind inheritance in Java is that you can create new classes that are built upon existing classes. When you inherit from an existing class, you can reuse methods and fields of the parent class. Moreover, you can add new methods and fields in your current class also. Inheritance represents the IS-A relationship which is also known as a parent-child relationship. Why use inheritance in java: For Method Overriding (so runtime polymorphism can be achieved). For Code Reusability. Terms used in Inheritance : Class: A class is a group of objects which have common properties. It is a template or blueprint from which objects are created. Sub Class/Child Class: Subclass is a class which inherits the other class. It is also called a derived class, extended class, or child class. Super Class/Parent Class: Superclass is the class from where a subclass inherits the features. It is also called a base class or a parent class. Reusability: As the name specifies, reusability is a mechanism which facilitates you to reuse the fields and methods of the existing class when you create a new class. You can use the same fields and methods already defined in the previous class. The syntax of Java Inheritance : class Subclass-name extends Superclass-name { //methods and fields } The extends keyword indicates that you are making a new class that derives from an existing class. The meaning of "extends" is to increase the functionality. In the terminology of Java, a class which is inherited is called a parent or superclass, and the new class is called child or subclass. Java Inheritance Example: As displayed in the above figure, Programmer is the subclass and Employee is the superclass. The relationship between the two classes is Programmer IS-A Employee. It means that Programmer is a type of Employee. class Employee{ float salary=40000; } class Programmer extends Employee{ int bonus=10000; public static void main(String args[]){ Programmer p=new Programmer(); System.out.println("Programmer salary is:"+p.salary); System.out.println("Bonus of Programmer is:"+p.bonus); } } OUTPUT: Programmer salary is:40000.0 Bonus of programmer is:10000 7. What is constructor? Explain types of constructor with example. ANS. In Java, a constructor is a block of codes similar to the method. It is called when an instance of the class is created. At the time of calling constructor, memory for the object is allocated in the memory. It is a special type of method which is used to initialize the object. Every time an object is created using the new() keyword, at least one constructor is called. It calls a default constructor if there is no constructor available in the class. In such case, Java compiler provides a default constructor by default. There are two types of constructors in Java: no-arg constructor, and parameterized constructor. Types of Java constructors : There are two types of constructors in Java: Default constructor (no-arg constructor) Java Default Constructor: A constructor is called "Default Constructor" when it doesn't have any parameter. Syntax of default constructor: (){} Example of default constructor In this example, we are creating the no-arg constructor in the Bike class. It will be invoked at the time of object creation. //Java Program to create and call a default constructor class Bike1{ //creating a default constructor Bike1(){System.out.println("Bike is created");} //main method public static void main(String args[]){ //calling a default constructor Bike1 b=new Bike1(); } } Output: Bike is created Java Parameterized Constructor : A constructor which has a specific number of parameters is called a parameterized constructor. Why use the parameterized constructor? The parameterized constructor is used to provide different values to distinct objects. However, you can provide the same values also. Example of parameterized constructor : In this example, we have created the constructor of Student class that have two parameters. We can have any number of parameters in the constructor. //Java Program to demonstrate the use of the parameterized constructor. class Student4{ int id; String name; //creating a parameterized constructor Student4(int i,String n){ id = i; name = n; } //method to display the values void display(){System.out.println(id+" "+name);} public static void main(String args[]){ //creating objects and passing values Student4 s1 = new Student4(111,"Karan"); Student4 s2 = new Student4(222,"Aryan"); //calling method to display the values of object s1.display(); s2.display(); } } OUTPUT: 111 Karan 222 Aryan 8. What is package? Explain creating and importing package in brief. ANS. In Java, a package is a group of classes, interfaces, enumeration, and annotations. Java contains many pre-defined packages such as java.lang, java.io, java.net, etc. When we create any Java program the java.lang package is imported by default. We need not to write the package name at the top of the program. We can also create our own package by providing the name that we want. In this section, we will learn how to create a package in Java. Creating a Package: To create a package, follow the steps given below: Choose a package name according to the naming convention. Write the package name at the top of every source file (classes, interface, enumeration, and annotations). Remember that there must be only one package statement in each source file. Package Naming Convention : We follow the naming convention rules to name a package. Java has some predefined packages and also allows us to create our own package. So, it is possible that a programmer can create a class with the same name as a package that already contains that type in a predefined package. Let's take an example of the Rectangle class. Suppose, a programmer creates a class with the name Rectangle in the package shape. The class with the same name is already present in java.awt package. The compiler allows both classes if they belong to the different packages. The fully qualified name of each class contains the package name that differentiate both Rectangle classes. Therefore, the package name of the user-defined class will be shape.Rectangle and the package name of the predefined class will be java.awt.Rectangle. Importing a Package: If we want to use a package in Java program it is necessary to import that package at the top of the program by using the import keyword before the package name. Syntax: import packageName; Let's create a calculator program in Java using the package. Add.java package p1; import java.util.*; public class Add { int s; public void sum() { System.out.print("Enter the first number: "); Scanner scan=new Scanner(System.in); int x=scan.nextInt(); System.out.print("Enter the second number: "); Scanner scan1=new Scanner(System.in); int y=scan1.nextInt(); s=x+y; System.out.println("sum="+s); } } Sub.java package p2; import java.util.*; public class Sub { int d; public void diff() { System.out.print("Enter the first number: "); Scanner scan=new Scanner(System.in); int x=scan.nextInt(); System.out.print("Enter the second number: "); Scanner scan1=new Scanner(System.in); int y=scan1.nextInt(); d=x-y; System.out.println("Difference="+d); } } 9. What is Variable? Explain different types of variable. ANS. A variable is a container which holds the value while the Java program is executed. A variable is assigned with a data type. Variable is a name of memory location. There are three types of variables in java: local, instance and static. There are two types of data types in Java: primitive and non-primitive. A variable is the name of a reserved area allocated in memory. In other words, it is a name of the memory location. It is a combination of "vary + able" which means its value can be changed. Types of Variables: There are three types of variables in Java: local variable instance variable static variable 1) Local Variable: A variable declared inside the body of the method is called local variable. You can use this variable only within that method and the other methods in the class aren't even aware that the variable exists. A local variable cannot be defined with "static" keyword. 2) Instance Variable: A variable declared inside the class but outside the body of the method, is called an instance variable. It is not declared as static. It is called an instance variable because its value is instance-specific and is not shared among instances. 3) Static variable: A variable that is declared as static is called a static variable. It cannot be local. You can create a single copy of the static variable and share it among all the instances of the class. Memory allocation for static variables happens only once when the class is loaded in the memory. Example to understand the types of variables in java: public class A { static int m=100;//static variable void method() { int n=90;//local variable } public static void main(String args[]) { int data=50;//instance variable } }//end of class 10. Write a java program to implement multiple inheritance. Also explain the concept implemented. ANS. When the child class extends from more than one superclass, it is known as multiple inheritance. However, Java does not support multiple inheritance. To achieve multiple inheritance in Java, we must use the interface. Example: Multiple Inheritance in Java : interface Backend { // abstract class public void connectServer(); } class Frontend { public void responsive(String str) { System.out.println(str + " can also be used as frontend."); } } // Language extends Frontend class // Language implements Backend interface class Language extends Frontend implements Backend { String language = "Java"; // implement method of interface public void connectServer() { System.out.println(language + " can be used as backend language."); } public static void main(String[] args) { // create object of Language class Language java = new Language() java.connectServer() // call the inherited method of Frontend class java.responsive(java.language); } } Output: Java can be used as backend language. Java can also be used as frontend. Explanation: Multiple Inheritance is the process in which a subclass inherits more than one superclass. In the below image, we can observe that Class C(sub-class) inherits from more than one superclass i.e., Class A, Class B. This is the concept of Multiple Inheritance. Many real-world examples of Multiple Inheritance also exist. For example, consider a newly born baby, inheriting eyes from mother, nose from father. Kindly note that Java does not support Multiple Inheritance, but we can use Interfaces to achieve the same purpose. Now we will be discussing an example to see what happens when we try to implement Multiple Inheritance in Java. Syntax: Class sub-class(name) extends super-class(name) { } Parent Class, Base Class are different terminologies for representing Superclass while Child Class, Derived Class are different terminologies for representing Subclass. In the program given below, we created two classes, i.e., class A and class B, along with the Main class. Here, class A is the superclass, and class B is the subclass. The subclass, class B extends Class A (superclass), thereby acquiring its methods also. Programme: class A { public void perform() { System.out.println("Hello.. from Super Class"); } } class B extends A { } public class Main { public static void main(String[] args) { B obj = new B(); // creating object of class B obj.perform(); // method gets inherited from class A } } Output: Hello.. from Super Class UNIT 4 1. Differentiate Checked and Unlocked Exception. ANS. What is a Checked Exception? A checked exception is an exception that should be reported in the method in which it is thrown. What is an Unchecked Exception? An exception that occurs at the runtime or at the time of execution is known as an unchecked exception. Differences between Checked and Unchecked Exceptions in Java S. No. Checked Exception ➡️ Unchecked Exception 1. Checked exceptions happen at compile time when the source code is transformed into an executable code. ➡️ Unchecked exceptions happen at runtime when the executable program starts running. 2. The checked exception is checked by the compiler. ➡️ These types of exceptions are not checked by the compiler. 3. Checked exceptions can be created manually. ➡️ They can also be created manually. 4. This exception is counted as a sub-class of the class. ➡️ This exception happens in runtime, and hence it is not included in the exception class. 5. Java Virtual Machine requires the exception to to be caught or handled. ➡️ Java Virtual Machine does not need the exception to be caught or handled. 2. What is exception Handling? Explain Try, catch and finally block with example. Ans. In the tutorial, we will learn about different approaches of exception handling in Java with the help of examples. In the last tutorial, we learned about Java exceptions. We know that exceptions abnormally terminate the execution of a program. This is why it is important to handle exceptions. Here's a list of different approaches to handle exceptions in Java. try...catch block finally block throw and throws keyword 1. Java try...catch block : Syntax: try { // code } catch(Exception e) { // code } Example: Exception handling using try...catch : class Main { public static void main(String[] args) { try { // code that generate exception int divideByZero = 5 / 0; System.out.println("Rest of code in try block"); } catch (ArithmeticException e) { System.out.println("ArithmeticException => " + e.getMessage()); } } } Output: ArithmeticException => / by zero 2. Java finally block: Syntax: try { //code } catch (ExceptionType1 e1) { // catch block } finally { // finally block always executes } Example: Java Exception Handling using finally block : class Main { public static void main(String[] args) { try { // code that generates exception int divideByZero = 5 / 0; } catch (ArithmeticException e) { System.out.println("ArithmeticException => " + e.getMessage()); } finally { System.out.println("This is the finally block"); } } } Output : ArithmeticException => / by zero This is the finally block 3. What is exception? Explain throw and throws block with example. ANS. Dictionary Meaning: Exception is an abnormal condition. In Java, an exception is an event that disrupts the normal flow of the program. It is an object which is thrown at runtime. throw: The throw keyword in Java is used to explicitly throw an exception from a method or any block of code. We can throw either checked or unchecked exception. The throw keyword is mainly used to throw custom exceptions. Syntax: throw Instance Example: throw new ArithmeticException("/ by zero"); The flow of execution of the program stops immediately after the throw statement is executed and the nearest enclosing try block is checked to see if it has a catch statement that matches the type of exception. If it finds a match, controlled is transferred to that statement otherwise next enclosing try block is checked and so on. If no matching catch is found then the default exception handler will halt the program. // Java program that demonstrates the use of throw class ThrowExcep { static void fun() { try { throw new NullPointerException("demo"); } catch(NullPointerException e) { System.out.println("Caught inside fun()."); throw e; // rethrowing the exception } } public static void main(String args[]) { try { fun(); } catch(NullPointerException e) { System.out.println("Caught in main."); } } } Output: Caught inside fun(). Caught in main. throws: throws is a keyword in Java which is used in the signature of method to indicate that this method might throw one of the listed type exceptions. The caller to these methods has to handle the exception using a try-catch block. Syntax: type method_name(parameters) throws exception_list exception_list is a comma separated list of all the exceptions which a method might throw. In a program, if there is a chance of raising an exception then compiler always warn us about it and compulsorily we should handle that checked exception, Otherwise we will get compile time error saying unreported exception XXX must be caught or declared to be thrown. To prevent this compile time error we can handle the exception in two ways: By using try catch By using throws keyword We can use throws keyword to delegate the responsibility of exception handling to the caller (It may be a method or JVM) then caller method is responsible to handle that exception. // Java program to illustrate error in case // of unhandled exception class tst { public static void main(String[] args) { Thread.sleep(10000); System.out.println("Hello Geeks"); } } Output: error: unreported exception InterruptedException; must be caught or declared to be thrown Explanation: In the above program, we are getting compile time error because there is a chance of exception if the main thread is going to sleep, other threads get the chance to execute main() method which will cause InterruptedException. // Java program to illustrate throws class tst { public static void main(String[] args)throws InterruptedException { Thread.sleep(10000); System.out.println("Hello Geeks"); } } Output: Hello Geeks Explanation: In the above program, by using throws keyword we handled the InterruptedException and we will get the output as Hello Geeks 4. Explain types of Errors. Give difference between error and exception. Ans. The Java.lang.Errors provide varieties of errors that are thrown under the lang package of Java. Some of the errors are: Error Name ➡️ Description AbstractMethodError ➡️ When a Java application tries to invoke an abstract method. Error ➡️ Indicating a serious but uncatchable error is thrown. This type of error is a subclass of Throwable. AssertionError ➡️ To indicate that an assertion has failed. ClassCircularityError ➡️ While initializing a class, a circularity is detected. IllegalAccessError ➡️ A Java application attempts either to access or modify a field or maybe invoking a method to which it does not have access. ClassFormatError ➡️ When JVM attempts to read a class file and find that the file is malformed or cannot be interpreted as a class file. InstantiationError ➡️ In case an application is trying to use the Java new construct for instantiating an abstract class or an interface. ExceptionInInitializerError ➡️ Signals that tell an unexpected exception have occurred in a static initializer. InternalError ➡️ Indicating the occurrence of an unexpected internal error in the JVM. IncompatibleClassChangeError ➡️ When an incompatible class change has occurred to some class of definition. LinkageError ➡️ Its subclass indicates that a class has some dependency on another data. NoSuchFieldError ➡️ In case an application tries to access or modify a specified field of an object, and after it, that object no longer has this field. OutOfMemoryError ➡️ In case JVM cannot allocate an object as it is out of memory, such error is thrown that says no more memory could be made available by the GC. NoClassDefFoundError ➡️ If a class loader instance or JVM, try to load in the class definition and not found any class definition of the class. ThreadDeath ➡️ Its instance is thrown in the victim thread when in thread class, the stop method with zero arguments is invoked. NoSuchMethodError ➡️ In case an application tries to call a specified method of a class that can be either static or instance, and that class no longer holds that method definition. StackOverflowError ➡️ When a stack overflow occurs in an application because it has recursed too deeply. UnsatisfiedLinkError ➡️ In case JVM is unable to find an appropriate native language for a native method definition. VirtualMachineError ➡️ Indicate that the JVM is broken or has run out of resources, essential for continuing operating. UnsupportedClassVersionError ➡️ When the JVM attempts to read a class file and get to know that the major & minor version numbers in the file are unsupportable. UnknownError ➡️ In case a serious exception that is unknown has occurred in the JVM. VerifyError ➡️ When it is found that a class file that is well-formed although contains some sort of internal inconsistency or security problem by the verifier. There are the below points that differentiate between both terms: Exception Error Can be handled Cannot be handled. Can be either checked type or unchecked type Errors are of unchecked type Thrown at runtime only, but the checked exceptions known by the compiler and the unchecked are not. Occurs at the runtime of the code and is not known to the compiler. They are defined in Java.lang.Exception package. They are defined in Java.lang.Error package Program implementation mistakes cause exceptions. Errors are mainly caused because of the environment of the program where it is executing. 5. Explain user defined Exception with example. ANS. User-defined exceptions are custom exceptions that a programmer can create in their code to handle specific error conditions or situations. These exceptions are derived from the base exception class and provide a way for the programmer to tailor the exception-handling process to their specific needs. User-defined exceptions are used to indicate errors that are specific to the particular application being developed and are often used to provide a higher level of abstraction and readability in the code. For example, a programmer may create a custom exception for a bank account class that checks if a withdrawal would result in a negative balance. If a withdrawal would cause a negative balance, the custom exception is thrown and can be caught and handled by the code. This allows the programmer to provide more meaningful error messages and handling of specific error conditions in the code, rather than relying on generic exceptions. Example: class NegativeBalanceException extends Exception { public NegativeBalanceException(String message) { super(message); } } class BankAccount { private double balance; public BankAccount(double balance) { this.balance = balance; } public double getBalance(){ return balance; } public void withdraw(double amount) throws NegativeBalanceException { if (balance - amount < 0) { throw new NegativeBalanceException("Insufficient funds to withdraw " + amount + " dollars."); } else { balance -= amount; } } } class Main { public static void main(String[] args) { BankAccount ba = new BankAccount(100); try { ba.withdraw(200); } catch (NegativeBalanceException ex) { System.out.println(ex.getMessage()); } System.out.println("Remaining balance: " + ba.getBalance()); } } Output: Insufficient funds to withdraw 200.0 dollars. Remaining balance: 100.0 6. Give Advantages of Exception Handling. ANS. Importance of Exception Handling: Below refers to the points why exception handling is important. Let’s see one by one. Ensures the Continuity of the Program: One of the key benefits of exception handling is that it ensures the continuity of the program. Without proper exception handling, an unhandled exception would cause the program to terminate abruptly, which can lead to data loss & other issues. With proper exception handling, the program can continue to execute and provide a more stable user experience. Enhances the Robustness of the Program: Exception handling allows for the program to anticipate and recover from errors, thus making the program more robust and resistant to unexpected conditions. By catching and handling exceptions, the program can continue to execute and provide a more stable user experience. Improves the Readability & Maintainability of the Code: Proper exception handling also improves the readability & maintainability of the code. By catching and handling exceptions, the program can provide clear error messages that accurately describe the error and provide information on how to resolve the issue. This makes it easier for developers to understand and modify the code in the future. Additionally, by providing detailed error messages, proper exception handling allows for more accurate error reporting, which is essential for debugging and troubleshooting purposes. Allows for more Accurate Error Reporting: Exception handling allows the program to catch & report errors in a more accurate & detailed manner, providing valuable information to developers for debugging and troubleshooting purposes. Facilitates Debugging and Troubleshooting: Exception handling allows the program to catch & report errors in a more accurate and detailed manner, which facilitates debugging and troubleshooting. By providing detailed error messages and stack traces, exception handling allows developers to quickly identify and resolve issues, reducing the amount of time and resources required for debugging. Improves the Security of the Program: Exception handling can also improve the security of a program by preventing sensitive information from being exposed in the event of an error. By catching and handling exceptions, the program can prevent sensitive information, such as passwords and personal data, from being displayed to the user or logged-in error messages. Provides a Better user Experience: Proper exception handling allows the program to anticipate and recover from errors, providing a more stable user experience. It is particularly important for user-facing applications, as it ensures that the program continues to function even in the event of an error, reducing the likelihood of user frustration and abandonment. Enables the use of error-recovery Mechanisms: Exception handling enables the use of error-recovery mechanisms, such as retries or fallbacks, which can improve the reliability and availability of the program. For example, if a program encounters a network error, it can retry the operation or fall back to a different network connection, ensuring that the program continues to function even in the event of an error. Improves the Scalability and Performance of the Program: Proper exception handling can also improve the scalability and performance of a program by reducing the amount of unnecessary processing and resource consumption. By catching and handling exceptions, the program can avoid performing unnecessary operations and releasing resources that are no longer needed, reducing the overall load on the system and improving performance. 7. Write a program to handle Divide by Zero Exception using try-catch and finally. ANS. class DivideByZeroExceptionHandling { public static void main(String[] args) { int a=10; int b=0; try{ int ans=divide(a,b); System.out.println("ans: "+ans); } catch (ArithmeticException e) { System.out.println("Error: "+ e.getMessage()); } finally { System.out.println("Finally block executed."); } } public static int divide(int a, int b) return a/b; } }
- Software Engineering Que. Bank Sem-4 BCA
SE Que. Bank 1)What Is Software Engineering? Ans: Software engineering is a field of study that involves the process of designing, developing, testing, and maintaining computer software. It involves applying the principles of engineering to software development, using a systematic approach to analyze user requirements and design, build, and test software applications to solve real-world problems. Software engineers use various programming languages, development tools, and methodologies to create software that meets the needs of users while adhering to best practices for quality, reliability, maintainability, and cost-effectiveness. Overall, software engineering is an interdisciplinary field that combines elements of computer science, mathematics, and engineering to create high-quality software products. 2)What Is The Roll Of Software Engineer? Ans: The role of a software engineer is to design, develop, test, and maintain computer software systems and applications that solve real-world problems for individuals, businesses, and organizations. They apply engineering principles to the software development process to create high-quality, innovative, and fully-performing software that complies with coding standards, and is efficient and reliable. Software engineers work on a variety of projects and may specialize in areas like front-end development, back-end development, full-stack development, software testing, or quality assurance. Ultimately, their goal is to create software that meets the needs of end-users, improves operational efficiency, and drives business growth. 3)Draw And Explain Software Engineering Layer? Ans: Software engineering is a multi-layered process that involves developing and maintaining software systems. Here is a summary of the layers of software engineering: 1. Tools layer: This layer contains automated or semi-automated tools that help software developers to build, test, and deploy software systems. Examples of these tools include integrated development environments (IDEs), code editors, build automation tools, and version control systems. 2. Methods layer: This layer defines the methodology or approach used in software development. Examples of software development approaches include Agile, Waterfall, and DevOps. 3. Process layer: This layer defines the processes that govern software development. It includes the steps involved in the software development life cycle (SDLC), such as requirements gathering, design, development, testing, deployment, and maintenance. 4. Quality layer: This layer is concerned with ensuring that the software system meets the required quality standards. It involves testing, verifying, and validating the software product for its quality, performance, reliability, and security. It's important to note that these layers are not necessarily distinct, and they may overlap or interact with each other in various ways depending on the software development approach being used. Moreover, the layering concept is not universally applied across all software development methodologies. 4)Explain Software Engineering As a Layer Technology. Ans: .Software engineering can be thought of as a layered technology, where each layer represents a different aspect of the overall software development process. The layers are related to each other and build on top of each other as the software is designed, developed, tested, and deployed. The layers of software engineering can vary depending on the specific methodology or framework being used, but they generally include the following: 1. Tools layer: This layer includes the software tools and technologies required for development, testing, and deployment of the software. Examples include text editors, integrated development environments (IDEs), version control systems, and testing frameworks. 2. Method layer: This layer defines the methodology or approach used to develop the software. Examples include agile, waterfall, and DevOps. 3. Process layer: This layer includes the processes and procedures used to manage the software development life cycle, including project management, requirements gathering, design, testing, and deployment. 4. Quality layer: This layer focuses on ensuring the quality and reliability of the software through testing, code reviews, and other quality assurance measures. By breaking down the software development process into these layers, software engineers can ensure that each aspect of the project is carefully considered and managed, ensuring that the end product is of high quality and meets user requirements. 5)Write Down The Characteristics of good Software. Ans: There are several recognized characteristics of good software, which are important to consider when developing software products. Some of the key characteristics of good software include: 1. Correctness: The software should perform the tasks it is designed to do, without any errors or bugs. 2. Usability: The software should be easy to use and understand for the user, with a simple and intuitive interface. 3. Efficiency: The software should perform its tasks within an acceptable time frame and with minimal use of resources like memory and CPU. 4. Reliability: The software should be able to deliver consistent results across different platforms and under varying conditions. 5. Maintainability: The software should be designed to allow for future modifications and updates to be made easily, without compromising its integrity. 6. Portability: The software should be designed to run on different platforms and operating systems without requiring significant changes. 7. Security: The software should protect user data and system resources from unauthorized access and malicious attacks. 8. Scalability: The software should be able to scale up or down based on the changing needs of the user or business. By keeping these characteristics in mind during the development process, software can be created that is effective, efficient, and user-friendly. 6)Explain The Process Model Which Is The Normally Suitable For development of large scale process system. Ans: The process model that is normally suitable for the development of large-scale software systems in software engineering is the spiral development model. This model combines some key aspects of the waterfall model and rapid prototyping methodologies. It aims to combine the advantages of top-down and bottom-up development concepts. The spiral development model consists of a series of iterations or spirals, with each iteration producing a prototype or working version of the software. During each iteration, the software is refined and improved based on feedback from stakeholders. This model is highly flexible, as it allows for continuous refinement and improvement of the software throughout the development process. It is also well-suited to large-scale projects where requirements may change over time, as it allows for easy adaptation to changing project requirements. Overall, the spiral development model is a highly effective approach for developing large-scale software systems in an agile and iterative manner. 7)Explain The Spiral Model Using The Example. Ans: The Spiral Model is a software development methodology that uses a risk-driven approach, combining elements of the Waterfall Model and the Iterative Model. In this approach, the development process is divided into smaller, more manageable phases, each performed in a spiral fashion. Each spiral is a complete iteration of the entire software development lifecycle (analysis, design, implementation, testing) and is made up of several smaller, iterative steps. During each phase, a prototype is developed and tested to identify potential issues and mitigate risks before proceeding to the next phase. As each iteration expands upon the previous ones, the software product becomes more refined and closer to an accurate representation of the final product. An example of the Spiral Model in software engineering could be the development of a new software system. The first spiral for this project may involve high-level requirements gathering and feasibility analysis of the project's technical capabilities. In the second spiral, a functional prototype of the system could be developed and tested, followed by an evaluation of user feedback and feature implementation in the third spiral. The fourth and final spiral could involve release preparation, rollout, and ongoing maintenance. Overall, the Spiral Model is an effective risk management approach that enables teams to detect and address issues early in their development process. By conducting frequent feedback and testing at different stages of the iterative cycle, teams can minimize the risks of unexpected problems as the project progresses. 8)Compare Increamental And Process Model. Ans: The Incremental Model and the Process Model are two software development models used in software engineering. The main difference between these two models is that the incremental model delivers a working product incrementally and involves multiple development cycles, while the process model is a linear sequential approach, where the product is developed through a series of phases in a sequential manner. In the incremental model, the product is analyzed, designed, implemented and tested incrementally until the complete product is ready. Each cycle in the incremental model delivers a working product incrementally. This model is preferred when the requirements are dynamic, and time to market is a critical factor. In contrast, the Process Model is a linear sequential approach consisting of phases, namely Requirements Analysis, Design, Implementation, Testing, and Maintenance. This model is popular when the requirements are well understood and the customer is looking for a product that meets the complete set of requirements. Both models have their pros and cons. The incremental model is more flexible and can adapt well to changing requirements, while the process model is more rigorous and ensures the completeness of the product. Choosing between the two models will depend on the specific needs of the project and its stakeholders. It is also important to note that several hybrid models have been developed to combine the advantages of the Incremental and Process Models. For example, the Agile Model, which combines the incremental and iterative approach with a focus on customer satisfaction and adaptability, has gained popularity in recent years. In summary, both the Incremental Model and the Process Model have their strengths and weaknesses, and selecting the appropriate model will depend on the needs of the project and its stakeholders. 9)Discuss Umbrella Activities And It's Role In Software Development Life Cycle. Ans: In software engineering, umbrella activities are the high-level tasks that must be performed throughout the software development life cycle (SDLC) to ensure the quality and success of a software project. Umbrella activities are so called because they encompass and oversee multiple other activities within the SDLC. Some common examples of umbrella activities in software development include project planning and tracking, software configuration management, quality assurance, and risk management. These activities are critical to the success of any software project, and they help to ensure that the project is completed on time, within budget and to the required standard. The role of umbrella activities in the SDLC is to define the characteristics of the software development process and to manage the impact of changes throughout that process. They also help to identify risks and issues early in the process, which can save time and money in the long term. By defining the scope of software development, the umbrella activities establish a framework within which software developers can work. These activities also ensure that the project remains on track and on budget, ultimately leading to better results and greater customer satisfaction. In conclusion, umbrella activities play an important role in the software development life cycle, helping to ensure that the project is completed successfully and satisfies the client's requirements. They are high-level tasks that oversee critical aspects of the development process and help to identify risks and issues early on. 10)Discuss two main features of azail model and discuss working of prototyping model with it's diagram. Ans: The Agile model of software development is designed to be flexible and adaptable to changing requirements. The two main features of the Agile model are: 1. Iterative development - The Agile model involves developing software in short iterations, which typically last between one and four weeks. The software is developed incrementally, with each iteration building on the previous one. 2. Collaboration - The Agile model places a strong emphasis on collaboration between team members, including developers, quality assurance professionals, and project stakeholders. This collaboration helps to ensure that everyone is involved in the development process and that the end product meets the needs of all users. The prototyping model is a software development model where a working prototype of the system is developed early in the project. The prototype is then evaluated and refined until it meets the requirements of the users. The main steps in the prototyping model are: 1. Requirements gathering - The requirements for the system are gathered from the users and stakeholders. 2. Prototype development - A working prototype of the system is developed based on the gathered requirements. 3. Prototype evaluation - The prototype is evaluated by the users and stakeholders to determine if it meets their needs. 4. Feedback and refinement - Based on the feedback received in the evaluation phase, the prototype is refined and improved. 5. Final product development - Once the prototype has been approved by the users and stakeholders, the final product is developed based on its design. Here's a diagram to illustrate the steps of the prototyping model: ``` Requirements Gathering --> Prototype Development --> Prototype Evaluation --> Feedback and Refinement --> Final Product Development ``` As you can see, the prototyping model involves an iterative process of refining and improving the prototype until it meets the requirements of the users and stakeholders. This makes it a useful model for software development projects where the requirements are not well-defined or may change throughout the development process. 11)Write About Component Software Engineering In Detail. Ans: Component-Based Software Engineering (CBSE) is a process that focuses on the design and development of computer-based systems using reusable software components. In CBSE, software components are independent modules that perform a specific function and can be easily combined with other components to create a larger system. This approach makes it easier to develop and maintain complex software systems, as each component can be separately tested, reused, and updated. Components in CBSE have a well-defined interface and conform to a recommended behavior common to all components within an architecture. They can be implemented in various programming languages and can run on different platforms. CBSE comprises several stages, including component identification, specification design, implementation, testing, and deployment. Overall, CBSE ultimately results in the creation of high-quality, reliable, and maintainable software systems that can be easily adapted to changing requirements. 12)What Is the importance of Process Model in development Of Software Model. Ans: The purpose of a process model in the development of software is to provide structure, organization and guidance to a team, helping to ensure consistency and efficiency in the development process. This is of particular importance because it keeps the project on track, minimizes risks and avoids common pitfalls that may arise during software development. The model provides a roadmap for developers, indicating different stages and milestones, which helps to ensure that everyone is on the same page and that progress is being made according to plan. By using a process model, the development process can be broken down into smaller, manageable tasks, which can be completed more easily than one large project, and reviewed more efficiently. This approach also ensures that quality is maintained, as the process model highlights the specific deliverables and artifacts that need to be completed and reviewed, thus reducing the risk of introducing errors or bugs into the system. In addition, the model can adapt to changing requirements, ensuring that the software system keeps pace with the changing needs of the business. There are various process models to choose from, including the waterfall model, iterative and incremental development, agile development, rapid application development, and the spiral model. Each model has its own strengths and weaknesses, and the choice will depend on the specific needs of the project. Some models are more suited for small teams working on simpler projects, while others are better suited for more complex systems, involving larger teams of developers. The benefits of following a process model in software development are numerous. They include cost savings, reduced risk, and faster time-to-market, as well as more streamlined communication and collaboration between team members. Furthermore, using a process model can help to ensure that code is clean, well-documented and easy to maintain, which can reduce maintenance costs in the long term. Overall, by using a process model, software development teams can ensure that they create high-quality software that meets the needs of their clients, is delivered on time and within budget, and evolves with the changing business environment. 13)What is SRS? Write Down Good Charactistics Of SRS. Ans: SRS stands for Software Requirements Specification. It is a document that clearly defines the requirements for a software project, including functional and non-functional requirements, design constraints, and any other relevant information. The SRS serves as a reference for both the client and the development team to ensure that everyone is on the same page regarding what the software will do and how it will function. Here are some good characteristics of an SRS in software engineering: 1. Correctness: The requirements should accurately reflect the needs of the client and the intended functionality of the software. 2. Completeness: The SRS should include all necessary requirements and specifications to ensure that the software meets the needs of the client. 3. Consistency: The requirements should be logically consistent and not contradict each other. 4. Verifiability: The requirements should be testable and verifiable to ensure that the software meets the needs of the client. 5. Feasibility: The requirements should be technically and economically feasible to implement. 6. Unambiguity: The requirements should be clear and unambiguous to avoid misunderstandings and confusion. 7. Prioritization: The requirements should be prioritized to ensure that the most important requirements are addressed first. 8. Traceability: The requirements should be traceable to their sources and to other requirements to ensure completeness and consistency. Overall, a well-written SRS is critical to the success of a software project, as it helps to ensure that everyone involved understands what is expected of the software and how it will function. 14)Writer the Software Requirement Specification For Hospital Management System. Ans: Writing a complete software requirements specification (SRS) for a Hospital Management System (HMS) is a big undertaking which requires a thorough understanding of the system's functionalities. However, I'll provide you with an overview of the sections that are commonly included in an SRS for HMS: 1. Introduction: This section describes the purpose, scope, and objectives of the Hospital Management System. 2. System Overview: This section provides a general description of the system, its functionality, and its interaction with other existing systems. 3. Functional Requirements: This section describes the specific features and functionalities of the Hospital Management System, such as patient management, appointment scheduling, medical records management, billing, and inventory management. 4. Non-Functional Requirements: This section describes the quality attributes of the HMS, including performance, security, reliability, usability, accessibility, scalability, and maintainability. 5. Use Cases: This section provides detailed descriptions of how the system will be used in various scenarios, such as registering patients, scheduling appointments, and generating reports. 6. User Interface: This section describes the graphical user interface of the system, including wireframes, mockups, and prototypes. 7. Data Management: This section describes how the system will store, retrieve, and manage the data required for its operations, including data models, database schema, and data dictionaries. 8. System Architecture: This section describes the technical architecture of the system, including hardware and software requirements, system components, and data flow diagrams. 9. Assumptions and Dependencies: This section lists the assumptions made during the development of the SRS and the dependencies of the system on external factors, such as hardware, software, and third-party services. These are just the main sections of an SRS for HMS. Depending on the complexity of the system, additional sections may be required. Also, it's important to note that the format and structure of an SRS can vary depending on the organization and industry standards. 15)What is Software Measurement? Ans: Software Measurement is the quantification of software-related attributes, including the quality, size, complexity, and performance of software products, processes, and projects. In the field of software engineering, software measurement is used to evaluate and improve the quality and efficiency of software development processes, as well as to assess the effectiveness and overall success of software projects. Software measurement includes a variety of techniques, tools, and standards for evaluating software attributes, such as Function Point Analysis, Cyclomatic Complexity, and ISO/IEC 15939:2002 Software Measurement Process. Ultimately, software measurement enables software engineers to create high-quality software products and reach critical delivery and performance targets. 16)Explain Software Matrix Used For Software Cost Estimation. Ans: Software metrics are quantifiable measurements that can be used to evaluate different aspects of a software product or process. One type of software metric that is commonly used in software engineering is the Software Metrics Matrix, which is often used in software cost estimation. The Software Metrics Matrix is a table that lists the different software metrics that will be measured during the software development process. For each metric, the table includes a definition, a method for measuring the metric, and a target value or range for the metric. Using the information in the Software Metrics Matrix, software development teams can estimate the cost and effort required to complete various tasks, such as developing specific features or fixing bugs. By tracking these metrics over time, teams can evaluate the effectiveness of their development process and make improvements as necessary. It's important to note that the Software Metrics Matrix should not be used in isolation to estimate software costs or measure performance. Other factors such as team size, experience, and project complexity can also play a role in software cost estimation. 17)Explain Different Matrix In Software Engineering In Detail. Ans: In software engineering, there are several types of matrices that are commonly used for various purposes. 1. Requirement Traceability Matrix (RTM): RTM is used to trace the requirements from the initial level to the final product. It maps each requirement to its corresponding design, implementation, and testing artifacts. RTM helps to ensure that all requirements are covered during development and testing. 2. Risk Matrix: Risk Matrix is used to identify and mitigate risks in software development. It is a tool for assessing and managing project risks. The matrix defines the likelihood and impact of various risks and helps in prioritizing the risks. 3. Responsibility Assignment Matrix (RAM): RAM is used to define and track the roles and responsibilities of each team member involved in a project. It maps each task to its responsible team member or team. RAM helps in ensuring that work is distributed among the team members appropriately. 4. RACI Matrix: RACI Matrix is similar to a RAM, but it also defines the level of authority of each team member. It maps each task to its Responsible, Accountable, Consulted or Informed team member. RACI Matrix helps in clarifying the responsibilities and authority of each team member. 5. Test Matrix: Test Matrix is used to map test cases to requirements, design, and implementation artifacts. It ensures that all test cases are covering all requirements and implemented design. Overall, these matrices are important tools in software engineering as they help in managing and tracking complex projects, and ensure that all requirements are fulfilled, risks are mitigated, and the work is distributed among team members appropriately. 18)What Are The Steps In Software Project Planning? What Are Effort Estimation. Ans: Effort estimation is the process of forecasting how much effort is required to develop or maintain a software application. It is an essential process in software project planning, which involves a number of steps. Some common steps in software project planning are: 1. Scoping: Defining the project goals, objectives, and requirements. 2. Decomposition: Breaking down the project into smaller tasks or work items. 3. Sizing: Assigning each work item a size estimate, such as story points or hours. 4. Expert and peer review: Reviewing the size estimates with subject matter experts and team members to identify any issues or gaps. 5. Estimation finalization: Combining the work item sizes to produce an overall estimate of effort required for the project. Effort estimation is important for project planning and control, as it helps to determine the project's schedule, budget, and resource allocation. However, it is also a complex process that requires careful consideration of many factors, such as the project's scope, requirements, and technical complexity. Additionally, a variety of techniques can be used for effort estimation, including expert judgment, historical data, and statistical models. 19)Explain COCOMO Model In Detail. Ans: COCOMO (Constructive Cost Model) is a widely used software cost estimation model in software engineering, developed by Barry Boehm in the late 1970s. It is a procedural cost estimate model for software projects and helps to calculate the cost and effort required to complete a project. COCOMO is based on the estimation of Lines of Code (LOC) in a software product and the time, effort, and cost required for development. COCOMO helps in determining the size of the project, which in turn helps to estimate the time and cost required to complete the project. COCOMO is of three types: 1. Basic COCOMO (also called COCOMO 81): This model depends primarily on the number of lines of code for software product development, and uses that figure to determine project size and the cost and effort required to complete the project. This model assumes that the project follows good development practices, and does not consider factors such as the complexity of the project, the experience of the development team, or the tools and platforms being used. 2. Intermediate COCOMO : This model considers additional factors such as the complexity of the project, the experience of the development team, and the tools and platforms being used, in addition to the lines of code. 3. Detailed COCOMO: This model takes into account all the factors considered in the Intermediate COCOMO model, along with other factors such as the capabilities of the development team and other external factors that might affect the project's outcome. Overall, COCOMO is a useful model for software development project management, as it helps in estimating time and cost required for a project before developing the software product in detail. The model can be improved with additional factors that affect project estimation. It is important to note that COCOMO estimates are not always accurate, and actual effort and cost for development may vary depending on various other factors like quality of developers, team dynamics, etc. 20)Explain Different Type Of Software Requirement. Ans: There are different types of software requirements that are typically defined during the software development process. Here are the main types of software requirements: 1. Functional requirements: These requirements describe the specific functions or features that the software application must perform. They focus on what the software must do. For example, a functional requirement for a banking application might be to allow users to view their account balances. 2. Non-functional requirements: These requirements describe the qualities or characteristics of the software application. They focus on how well the software must perform. Examples of non-functional requirements include performance, security, scalability, and usability. 3. Business requirements: These requirements are derived from the business objectives or goals that the software application is intended to support. They define what the software must achieve in order to meet the needs of the business. For example, a business requirement for a sales application might be to increase sales revenue by 10%. 4. System requirements: These requirements describe the hardware and software requirements that the software application must meet. They are often related to the environment in which the application will be running. For example, a system requirement for a gaming application might be to require a certain amount of RAM or a specific graphics card. 5. User requirements: These requirements describe the needs and goals of the users who will be interacting with the software application. They focus on how the software will be used and what the user experience must be. For example, a user requirement for a messaging application might be to allow users to send messages to multiple recipients at once. These are some of the main types of software requirements. A software development team will typically document these requirements in a software requirements specification (SRS) document, which will help guide the development process and ensure that the software application meets the needs of its users and stakeholders. 21)Write Down The Functional And Non-Functional Requirements With Example Of Hospital Management System. Ans: Here are some functional and non-functional requirements for a Hospital Management System: Functional Requirements: 1. Keep track of patient's medical history and current treatment plans. 2. Enable doctors to view and update patient information and schedules. 3. Allow emergency medical staff to access patient details quickly and easily. 4. Provide billing and payment systems for patients and healthcare providers. 5. Manage inventory and supplies for the hospital. Non-Functional Requirements: 1. The system should be available 24/7 and have a high level of reliability. 2. The system should be secure and protect patient information at all times. 3. The system should be scalable to accommodate future growth. 4. The system should be easy to use and have a user-friendly interface. 5. The system should comply with relevant regulations and standards, such as HIPAA. These are just some examples of functional and non-functional requirements for a Hospital Management System. The exact requirements will depend on the specific needs and goals of the healthcare organization. 22)What Is The Importance Of User Interface. Explain User Interface Design Rules With Example. Ans: The importance of user interface (UI) in software engineering cannot be overstated. A well-designed UI can make the difference between a successful software application and a failed one. The main goal of UI design is to make software applications more user-friendly, efficient, and enjoyable for people to use. Good UI can help users accomplish tasks more quickly and with fewer errors, resulting in a better user experience. Here are some golden rules of UI design that designers often follow to create effective and intuitive interfaces: 1. Keep it Simple: Strive for simplicity in design by keeping it as clear and concise as possible. Avoid clutter and complexity that can confuse or overwhelm users. 2. Consistency is Key: Consistency in design is important to avoid confusion and make it easier for users to understand how the system works. 3. Provide Feedback: The system should give users immediate feedback on any action they take or decision they make. 4. Keep Users in Control: The system should always provide users with a clear understanding of what is happening and allow them to have control over their actions and interactions. 5. Error Prevention and Handling: Effective UI design should be able to anticipate and prevent errors from occurring in the first place. When errors do occur, the system should provide clear and meaningful error messages to help users recover. For example, consider a website that allows users to create an account. The UI should be optimized for clarity and simplicity, with all the required fields clearly labeled and easy to fill out. The form should provide immediate feedback to users to notify them if a field is incorrectly filled out or missing. The interface should also give users the option to review the information they have entered and correct any mistakes. Finally, good UI design would ensure there is adequate error-handling to prevent users from losing their data if they navigate away from the form by mistake. Overall, effective UI design is critical to engage users with software applications by making their interactions more efficient, intuitive and enjoyable. 23)Compare Coupling And Cohesion. Ans: In software engineering, coupling and cohesion are two important concepts that refer to the relationships between software modules. Cohesion refers to the degree to which the elements of a module belong together. A highly cohesive module has elements that work together to perform a single, well-defined task, whereas a module with low cohesion has elements that are not closely related and may perform multiple tasks. Having high cohesion in a module makes it easier to maintain and modify, as changes can be made to a specific area of the module without affecting other areas. Coupling, on the other hand, refers to the level of interdependence between modules. Modules with high coupling are tightly connected to one another and depend heavily on the functionality of other modules, whereas modules with low coupling are more independent and rely less on the functionality of other modules. Reducing coupling between modules can make a system more flexible and easier to maintain. Overall, high cohesion and low coupling are desirable characteristics in software engineering, as they can make a system more modular, easier to maintain, and more flexible. By contrast, low cohesion and high coupling can lead to code that is difficult to change, debug, and test. 24)Explain Different Type Of Coupling And It's Effect On Software Module. Ans: Coupling is the degree of interdependence between software modules). It is a measure of how closely connected two routines or modules are). High coupling means that modules are closely connected, and changes in one module may affect other modules. Low coupling means that modules are loosely connected, and changes in one module may not affect other modules. There are different types of coupling, including: 1. Content coupling: This type of coupling occurs when one module can directly access or modify the content of another module. 2. Common coupling: This type of coupling occurs when multiple modules share and access the same global data. 3. Control coupling: This type of coupling occurs when one module makes decisions for another module, such as by passing control flags or parameters. 4. Stamp coupling: This type of coupling occurs when two modules share a common data structure, but only use a part of it. 5. Data coupling: This type of coupling occurs when modules pass data between each other but does not directly access each other's content. The effect of high coupling is that it makes software less modular and harder to maintain because changes in one module may have a cascading effect on other modules. It also makes testing more difficult since changes can have unintended consequences. On the other hand, low coupling makes software more modular, easier to maintain, and testable. In general, it's best to aim for low coupling between modules in software design to make the code more flexible, extensible, and maintainable in the long run. 25)What Is User Interface? Explain Design Rules For UI Ans: User interface (UI) is the means by which a user interacts with a computer program or website. The UI includes all the elements a user interacts with, such as buttons, menus, forms, and other input and output elements. The design of a UI is crucial to the success of an application or website, as it can significantly impact how easy or difficult it is for users to accomplish their goals and interact with the system. There are several design rules that are commonly followed in UI design to ensure a good user experience. Here are some of the most important ones: 1. Strive for consistency: consistent sequences of actions should be required in similar situations. 2. Use clear, descriptive labels: labels should clearly indicate what each button, field, or input does. 3. Use familiar icons and symbols: users should be able to easily interpret any icons or symbols used in the UI. 4. Seek universal usability: the design should be usable by people with a range of abilities and disabilities. 5. Aim for simplicity and clarity: the design should make the simple, common tasks straightforward and easy to do. 6. Use appropriate feedback: provide feedback to users after each interaction, to acknowledge that the system has received their input and to inform them of any errors or problems. 7. Design for error handling: error messages should be clear, concise and user-friendly, offering guidance on how to resolve any issues. These and other design rules help to create a UI that is intuitive, easy to use, and effective in helping users achieve their goals in a software application or website. 26)Explain The Different Design Concept. Ans: In software engineering, design concepts refer to the fundamental principles and techniques used to create effective software designs. Some of the key design concepts in software engineering include: 1. Abstraction: This refers to the process of breaking down a complex system into smaller, more manageable parts. Abstraction allows developers to focus on the essential features of a system while ignoring unnecessary details. 2. Modularity: This refers to the practice of dividing a system into independent components or modules that can be developed and tested separately. Modularity makes it easier to maintain and update software and reduces the risk of errors. 3. Encapsulation: This refers to the practice of hiding the internal workings of a module or component so that it can only be accessed through a well-defined interface. Encapsulation helps to ensure that changes to one module do not affect the behavior of other modules. 4. Cohesion: This refers to the degree to which the elements within a module are related to each other. A module with high cohesion has elements that are closely related and work together to perform a single function. 5. Coupling: This refers to the degree to which two or more modules depend on each other. A module with low coupling is easier to modify and maintain than a module with high coupling. 6. Design Patterns: These are repeatable solutions to common software design problems. They provide a standard way of solving particular problems and can make designs more modular, reusable, and maintainable. By using these design concepts, software engineers can create effective and efficient software designs that are scalable, modular, and easy to maintain. 27)Explain The Different Design Concept. Ans: Software engineering involves various design concepts that are used to create effective and efficient software systems. Some of the key design concepts in software engineering include: 1. Abstraction: This involves hiding various implementation details of a system from the users, allowing them to interact with high-level functionalities. 2. Modularity: This concept emphasizes on organizing the software system components into separate modules that can be easily maintained and updated without disrupting the entire system. 3. Coupling and Cohesion: These concepts describe the degree of dependency and interaction between the various software components. High cohesion and low coupling arrangements are generally preferred in software design. 4. Structured design: This describes the logical step-by-step approach followed in designing software systems using the hierarchical decomposition of functions. 5. Design patterns: These are standardized solutions to recurring software design problems that are widely accepted and used in the industry. 6. Cloud-Based Development: This method of software design involves cloud-based environments that support the entire software development process. Overall, by applying these design concepts, software developers can simplify the software code, reduce the likelihood of errors, and create flexible and maintainable systems. 28)Draw Use-Case Diagram For ATM Machine. Ans: 29)Draw Sequence And Activity Diagram For Billing Counters In Mall. Ans: Sequence Diagram: 😊 Best of Luck 😊
- Java Que. Bank Sem-4 BCA
Q. : 1) True or False The size of char data-type is 1 byte in Java. ➡ FALSE A single Java file many contain any number of class definitions. ➡ TRUE Java source code can be written in files with any extension. ➡ FALSE A Boolean value can be cast to an int. ➡ FALSE Every class has at least one constructor available. ➡ TRUE Static variable cannot be used in non-static methods. ➡ FALSE Overloading of a constructor is not allowed in Java. ➡ FALSE Java supports destructor. ➡ FALSE String is a immutable object in java. ➡ TRUE Object is an instance of a class. ➡ TRUE The size of char data-type is 2 byte in java. ➡ TRUE The default case is required in the switch selection structure. ➡ FALSE “final” variables cannot be modified. ➡ TRUE An abstract class must have at least one abstract method. ➡ FALSE One class cannot be derived from more than one class in java. ➡ TRUE The object created by String class can be modified. ➡ TRUE Q. :2) Fill up the blank line A method declared with final modifier cannot be overridden. Java uses Unicode character set to represent characters. It is possible to throw an exception explicitly using the C# throw or the Visual Basic Throw statement. System Exception Class is the base class of all Exception class. A package is a collection of classes and interfaces. The setBackground() method sets the background color of an applet. Method main is a public static method. Justify so that compiler can call it without the creation of an object or before the creation of an object of the class. Q. :3) 2-3 Mark Questions 1. Draw compilation and interpretation process of java. Ans. Java can be considered both a compiled and an interpreted language because its source code is first compiled into a binary byte-code. This byte-code runs on the Java Virtual Machine (JVM), which is usually a software-based interpreter. 2. What is the difference between method overloading and overriding in Java? Ans. Overriding occurs when the method signature is the same in the superclass and the child class. Overloading occurs when two or more methods in the same class have the same name but different parameters. 3. What is the difference between final method and ordinary method of a class? Ans. Static methods can be called by other static methods and only access the static members of the class. On the other hand, final methods cannot be overridden. 4. Explain the uses of keyword “super” and “extends” with code. Ans. The super keyword refers to superclass (parent) objects. It is used to call superclass methods, and to access the superclass constructor. The most common use of the super keyword is to eliminate the confusion between superclasses and subclasses that have methods with the same name. 5. What is meant by interface? Explain with java code. Ans. An interface is an abstract "class" that is used to group related methods with "empty" bodies: To access the interface methods, the interface must be "implemented" (kinda like inherited) by another class with the implements keyword (instead of extends ). CODE: interface Animal { public void animalSound(); // interface method (does not have a body) public void sleep(); // interface method (does not have a body) } class Pig implements Animal { public void animalSound() { System.out.println("The pig says: wee wee"); } public void sleep() { System.out.println("Zzz"); } } class Main { public static void main(String[] args) { Pig myPig = new Pig(); myPig.animalSound(); myPig.sleep(); } } 6. How method overriding will be achieved in Java application? Ans. In Java, method overriding occurs when a subclass (child class) has the same method as the parent class. In other words, method overriding occurs when a subclass provides a particular implementation of a method declared by one of its parent classes. 7. Explain the purpose of “Exception” class. Ans. Exceptions provide the means to separate the details of what to do when something out of the ordinary happens from the main logic of a program. In traditional programming, error detection, reporting, and handling often lead to confusing spaghetti code. 8. Explain the uses of the keywords “throw” and “finally”. Ans. Java Throw: The throw keyword is used to throw an exception explicitly. Only object of Throwable class or its sub classes can be thrown. Program execution stops on encountering throw statement, and the closest catch statement is checked for matching type of exception. finally clause: A finally keyword is used to create a block of code that follows a try block. A finally block of code is always executed whether an exception has occurred or not. Using a finally block, it lets you run any cleanup type statements that you want to execute, no matter what happens in the protected code. A finally block appears at the end of catch block. 9. Explain static method in a class. Ans. A static method is a method that belongs to a class rather than an instance of a class. This means you can call a static method without creating an object of the class. Static methods are sometimes called class methods. You can access static methods from outside of the class in which they are defined. This is not possible with non-static methods. Subclasses can override static methods, but non-static methods cannot. Static methods are executed when an instance of the class is created, whereas non-static methods are not. Static methods can be used to create utility classes that contain general-purpose methods. You can use static methods to enforce encapsulation since they can only be called from within the class in which they are defined. 10. Define String class with all its method. Ans. Java String class provides a lot of methods to perform operations on strings such as compare(), concat(), equals(), split(), length(), replace(), compareTo(), intern(), substring() etc. The java.lang.String class implements Serializable, Comparable and CharSequence interfaces. 11. What hat is the difference between “Pass by value” and “Pass by reference” in java? Explain with proper example. Ans. Pass by Value: It is a process in which the function parameter values are copied to another variable and instead this object copied is passed. This is known as call by Value. Pass by Reference: It is a process in which the actual copy of reference is passed to the function. This is called by Reference. Example: public class Mug { private String contents; public Mug(String contents) { this.contents = contents; } public void setContents(String contents) { this.contents = contents; } public String getContents(){ return contents; } } public class Run { public static void spill(Mug myMug) { myMug.setContents("nothing"); } public static void main(String args[]) { Mug myMug = new Mug("tea"); // myMug contains "tea" System.out.println(myMug.getContents()); spill(myMug); // myMug now contains "nothing" System.out.println(myMug.getContents()); } } 12. Explain “Array of Reference Type” using java code. Ans. Java also allows the use of an interface name to specify a reference type. In addition, array types in Java are reference types because Java treats arrays as objects. The two main characteristics of objects in Java are that: Objects are always dynamically allocated. 1. Loops: for loop and for-each loop int[] intArray = {2,5,46,12,34}; for(int i=0; i list = Arrays.asList(intArray); // creating an iterator of Integer List Iterator it = list.iterator(); // if List has elements to be iterated while(it.hasNext()) { System.out.print(it.next()); // output: 25461234 } 6. Java Stream API Integer[] intArray = {2,5,46,12,34}; Arrays.stream(intArray).forEach(System.out::print); // output: 25461234 13. Discuss final keyword used with variable, method and class. Ans. Java final keyword is a non-access specifier that is used to restrict a class, variable, and method. If we initialize a variable with the final keyword, then we cannot modify its value. If we declare a method as final, then it cannot be overridden by any subclasses. And, if we declare a class as final, we restrict the other classes to inherit or extend it. In other words, the final classes can not be inherited by other classes. Final Variable in Java: Once we declare a variable with the final keyword, we can’t change its value again. If we attempt to change the value of the final variable, then we will get a compilation error. Final Method in Java: As earlier, we discussed the Final Keyword and How to declare the Final Variable. We can declare Java methods as Final Method by adding the Final keyword before the method name. Final Class in Java: We can also declare a class with a final keyword in Java. When we declare a class as final, then we restrict other classes to inherit or extend it. 14. Describe default and parameterized constructor with example. Ans. Definition: Default Constructor: A Constructor with no argument is called default Constructor Parameterized Constructor: A Constructor with arguments is called Parameterized Constructor Syntax: //Default ConstructorClass ConstructorExample { ConstructorExample (){ //Do something } } //Parameterized ConstructorClass ConstructorExample { variableName; ConstructorExample ( variableName){ this.variableName = variableName; //Do something } } Default and Parameterized Constructor Example Program : public class DefaultAndParameterizedConstructor { public static void main(String[] args) { //Creating object of class using default constructor DefaultConstructorExample object1 = new DefaultConstructorExample(); object1.doAddition(); //Creating object of class using parameterized constructor ParameterizedConstructorExample object2 = new ParameterizedConstructorExample(100,200); object2.doAddition(); } } class DefaultConstructorExample{ int num1 = 5, num2 = 10, result; int doAddition(){ result = num1+num2; System.out.println("This method is called using a default constructor"); return result; } } class ParameterizedConstructorExample{ int num1, num2, result; public ParameterizedConstructorExample(int num1, int num2) { this.num1 = num1; this.num2 = num2; } int doAddition(){ result = num1+num2; System.out.println("This method is called using a parameterized constructor"); return result; } } Sample Output : This method is called using a default constructor This method is called using a parameterized constructor 15. Discuss Accessibility of access modifiers in different condition. Ans. There are two types of modifiers in Java: access modifiers and non-access modifiers. The access modifiers in Java specifies the accessibility or scope of a field, method, constructor, or class. We can change the access level of fields, constructors, methods, and class by applying the access modifier on it. There are four types of Java access modifiers: Private: The access level of a private modifier is only within the class. It cannot be accessed from outside the class. Default: The access level of a default modifier is only within the package. It cannot be accessed from outside the package. If you do not specify any access level, it will be the default. Protected: The access level of a protected modifier is within the package and outside the package through child class. If you do not make the child class, it cannot be accessed from outside the package. Public: The access level of a public modifier is everywhere. It can be accessed from within the class, outside the class, within the package and outside the package. Examples : 1. Private: class A{ private int data=40; private void msg(){System.out.println("Hello java");} } public class Simple{ public static void main(String args[]){ A obj=new A(); System.out.println(obj.data);//Compile Time Error obj.msg();//Compile Time Error } } 2. Default: //save by A.java package pack; class A{ void msg(){System.out.println("Hello");} } //save by B.java package mypack; import pack.*; class B{ public static void main(String args[]){ A obj = new A();//Compile Time Error obj.msg();//Compile Time Error } } 3. Protected : //save by A.java package pack; public class A{ protected void msg(){System.out.println("Hello");} } //save by B.java package mypack; import pack.*; class B extends A{ public static void main(String args[]){ B obj = new B(); obj.msg(); } } 4. Public : //save by A.java package pack; public class A{ public void msg(){System.out.println("Hello");} } //save by B.java package mypack; import pack.*; class B{ public static void main(String args[]){ A obj = new A(); obj.msg(); } } OUTPUT : Hello Java Access Modifiers with Method Overriding class A{ protected void msg(){System.out.println("Hello java");} } public class Simple extends A{ void msg(){System.out.println("Hello java");}//C.T.Error public static void main(String args[]){ Simple obj=new Simple(); obj.msg(); } } 16. Explain this keyword and its related concepts with example. Ans. Definition & Usage : The this keyword refers to the current object in a method or constructor. The most common use of the this keyword is to eliminate the confusion between class attributes and parameters with the same name (because a class attribute is shadowed by a method or constructor parameter). If you omit the keyword in the example above, the output would be "0" instead of "5". this can also be used to: Invoke current class constructor Invoke current class method Return the current class object Pass an argument in the method call Pass an argument in the constructor call Example: public class Main { int x; // Constructor with a parameter public Main(int x) { this.x = x; } // Call the constructor public static void main(String[] args) { Main myObj = new Main(5); System.out.println("Value of x = " + myObj.x); } } Output : Value of x= 5 17. Differentiate Checked and Unchecked Exceptions. Ans. Checked Exceptions They occur at compile time. The compiler checks for a checked exception. These exceptions can be handled at the compilation time. It is a sub-class of the exception class. The JVM requires that the exception be caught and handled. Example of Checked exception- ‘File Not Found Exception’ Unchecked Exceptions These exceptions occur at runtime. The compiler doesn’t check for these kinds of exceptions. These kinds of exceptions can’t be caught or handled during compilation time. This is because the exceptions are generated due to the mistakes in the program. These are not a part of the ‘Exception’ class since they are runtime exceptions. The JVM doesn’t require the exception to be caught and handled. Example of Unchecked Exceptions- ‘No Such Element Exception’. Q. 4) 7-8 Marks Questions 1. Why Java is a platform independent language? How Java achieve this? Ans. The platform can be defined as a distinct combination of hardware, operating system, and software that provides an environment to run programs. Java is called Platform Independent because programs written in Java can be run on multiple platforms without re-writing them individually for a particular platform, i.e., Write Once Run Anywhere (WORA). How Java Provides Platform Independence? To understand how Java facilitates platform independence, let us differentiate between the compilation process of other programming languages, mainly C/C++, and that of Java. The program written by the programmer, known as source code, is not understood by the computer. Source code is very similar to human language, consisting of words and phrases. It has to be converted into machine language code, which computers can easily understand and execute. Machine language code is a set of instructions to be executed by the computer. The compiler does this conversion. The process of converting source code into machine code is called compilation. Machine Language Code is unique for different platforms. Step-by-Step Execution of Java Programs: Contrary to other compilers, the Java compiler doesn't produce native executable files or code for a particular platform. The compilation process in Java instead generates a special format called byte code. This generated file is also referred to as a .class file. The Byte Code of Java is a set of machine instructions for a Java processor chip called Java Virtual Machine (JVM). Java Byte Code is very similar to machine language, but unlike machine language, Java byte code is absolutely the same on every platform. The byte code is not directly executable on any platform. Java code compiled into byte code still needs an interpreter to execute them on the platform. Java Virtual Machine or JVM is a special Java Interpreter. Java Virtual Machine takes byte code as input. It interprets and executes the byte code and provides the output of the program. Note: A compiler translates the entire program at once into machine-readable code. An Interpreter also converts the program to machine code, but it does so by translating it instruction-by-instruction or line-by-line. The interpreter then converts the byte code into the native code. Native code is just like machine language code, which can be compiled to run with a particular processor and its set of instructions. Thus, native code can be executed by an individual operating system. Java Byte Code is platform-independent but natively executable code generated from byte code using an interpreter is highly platform-dependent and cannot run on other platforms. For example, source code written in windows OS is compiled by the javac compiler of windows, and the .class file (byte code) is created. JVM of Unix, MAC, or any other platform can interpret this byte code. Hence, the JVM of that specific platform interprets the byte code and generates natively executable code for the platform. This native code is readily understood by the system and is executed, and it prints Hello World! Using byte code, a natively executable code can be generated on any platform using a JVM interpreter, irrespective of the platform on which the byte code was created. But the natively executable code of one platform cannot be used for other platforms, i.e., the native code of Unix cannot run on Windows or MAC. Note: Java code is both compiled and interpreted language. The source code written in Java is first compiled into bytecode. The Java Virtual Machine then interprets the generated bytecode for execution. However, the JVM also makes use of a Just in Time compiler during runtime to improve performances. 2. Explain Object oriented programming concepts in java. Ans. Object means a real-world entity such as a pen, chair, table, computer, watch, etc. Object-Oriented Programming is a methodology or paradigm to design a program using classes and objects. It simplifies software development and maintenance by providing some concepts: Object Any entity that has state and behavior is known as an object. For example, a chair, pen, table, keyboard, bike, etc. It can be physical or logical. An Object can be defined as an instance of a class. An object contains an address and takes up some space in memory. Objects can communicate without knowing the details of each other's data or code. The only necessary thing is the type of message accepted and the type of response returned by the objects. Class Collection of objects is called class. It is a logical entity. A class can also be defined as a blueprint from which you can create an individual object. Class doesn't consume any space. Inheritance When one object acquires all the properties and behaviors of a parent object, it is known as inheritance. It provides code reusability. It is used to achieve runtime polymorphism. Polymorphism If one task is performed in different ways, it is known as polymorphism. For example: to convince the customer differently, to draw something, for example, shape, triangle, rectangle, etc. In Java, we use method overloading and method overriding to achieve polymorphism. Another example can be to speak something; for example, a cat speaks meow, dog barks woof, etc. Abstraction Hiding internal details and showing functionality is known as abstraction. For example phone call, we don't know the internal processing. In Java, we use abstract class and interface to achieve abstraction. Encapsulation Binding (or wrapping) code and data together into a single unit are known as encapsulation. For example, a capsule, it is wrapped with different medicines. A java class is the example of encapsulation. Java bean is the fully encapsulated class because all the data members are private here. Coupling Coupling refers to the knowledge or information or dependency of another class. It arises when classes are aware of each other. If a class has the details information of another class, there is strong coupling. In Java, we use private, protected, and public modifiers to display the visibility level of a class, method, and field. You can use interfaces for the weaker coupling because there is no concrete implementation. Cohesion Cohesion refers to the level of a component which performs a single well-defined task. A single well-defined task is done by a highly cohesive method. The weakly cohesive method will split the task into separate parts. The java.io package is a highly cohesive package because it has I/O related classes and interface. However, the java.util package is a weakly cohesive package because it has unrelated classes and interfaces. Association Association represents the relationship between the objects. Here, one object can be associated with one object or many objects. There can be four types of association between the objects: One to One One to Many Many to One, and Many to Many Let's understand the relationship with real-time examples. For example, One country can have one prime minister (one to one), and a prime minister can have many ministers (one to many). Also, many MP's can have one prime minister (many to one), and many ministers can have many departments (many to many). Association can be undirectional or bidirectional. Aggregation Aggregation is a way to achieve Association. Aggregation represents the relationship where one object contains other objects as a part of its state. It represents the weak relationship between objects. It is also termed as a has-a relationship in Java. Like, inheritance represents the is-a relationship. It is another way to reuse objects. Composition The composition is also a way to achieve Association. The composition represents the relationship where one object contains other objects as a part of its state. There is a strong relationship between the containing object and the dependent object. It is the state where containing objects do not have an independent existence. If you delete the parent object, all the child objects will be deleted automatically. work in processing