Tumgik
#Printing an ArrayList in Java
Text
Printing an array in java with example
In this article, we will discuss printing an array in java using different methods like using loop, without loop, 2d array, and array in reverse with source code and output of that. #1. Printing an Array in Java using for loop A. Explanation of the source code The code snippet below demonstrates how to print an array in Java using a for loop. The for loop iterates through the elements of the…
Tumblr media
View On WordPress
0 notes
vibinjack · 3 months
Text
Best Java Programs For Beginners And Experienced 
Tumblr media
Introduction:
Java is a popular and flexible programming language that has been a mainstay in software development for many years. Whether you are taking your first steps into the programming realm or seeking to enhance your skills, mastering Java is a rewarding journey. In this article, we'll explore a curated selection of the best Java programs suitable for beginners and experienced programmers, aiming to provide a well-rounded understanding of the language's capabilities. Embarking on Java Training In Chennai has been a pivotal step in my journey as a programmer, equipping me with the essential skills needed to excel in the dynamic world of Java development.
Hello World: The Starting Point For Every Programmer
The timeless "Hello World" program is the foundation for Java beginners. It introduces a Java program's basic syntax and structure, acting as a gateway to understanding variables, data types, and the essential concept of printing output to the console.
Calculator Program: Basic Arithmetic Operations
Creating a simple calculator application is an excellent exercise for beginners transitioning to more complex programs. This program incorporates user input, conditional statements, and arithmetic operations, offering hands-on experience building interactive Java applications.
Guess The Number: Introduction To Control Flow
To delve into control flow and decision-making, a "Guess the Number" game is an engaging choice. This program introduces conditional statements (if, else), loops (while or for), and user input handling. It provides practical insights into creating interactive and dynamic Java applications.
File Handling: Reading And Writing Data
Moving into more advanced territory, file handling is a critical skill for experienced programmers. Creating a Java program that reads from and writes to files enhances knowledge of file I/O operations, exception handling, and the importance of data persistence.
Object-Oriented Programming (OOP) Concepts: Employee Management System
For both beginners and experienced developers, building an Employee Management System demonstrates the application of OOP principles in Java. This program involves creating classes, encapsulation, inheritance, polymorphism, and abstraction, fostering a deeper understanding of Java's object-oriented paradigm.
Multithreading: Concurrent Programming
Multithreading is a powerful aspect of Java, enabling concurrent execution of tasks. An advanced program showcasing multithreading can involve creating threads, synchronisation, and coordination, providing insights into handling parallel processes effectively.
Networking: Simple Client-Server Communication
Developing a simple client-server communication program introduces networking concepts to broaden Java expertise. This program allows programmers to grasp the fundamentals of sockets, server-client architecture, and data exchange over a network, laying the groundwork for more complex networked applications.
GUI Application: Address Book
Creating an Address Book application is ideal for hands-on experience in graphical user interface (GUI) development. This program uses Java's Swing or JavaFX libraries, providing a practical introduction to building interactive and visually appealing desktop applications.
Exception Handling: Robust Error Management
Writing a program that incorporates robust exception handling is crucial for experienced Java developers. This program focuses on anticipating and handling runtime errors gracefully, enhancing the reliability and resilience of Java applications.
Java Collections Framework: To-Do List Application
To master the Java Collections Framework, building a To-Do List application is an excellent choice. This program involves utilising collections like ArrayLists or LinkedLists, understanding iteration, sorting, and searching operations, and honing skills in managing data efficiently. Enrolling in comprehensive Python Training In Chennai has equipped me with the skills and knowledge needed to excel in the dynamic programming field.
Conclusion:
Mastering Java programming involves a gradual progression from fundamental concepts to advanced applications. The selection of Java programs provided here serves as a roadmap for beginners and experienced programmers, offering a comprehensive journey through Java's versatile features. As you explore these programs, you'll strengthen your Java skills and gain a deeper appreciation for the language's flexibility and applicability in diverse software development scenarios.
0 notes
tutorialworld · 2 years
Text
Nagarro Java developer Interview Questions
1. Difference in ArrayList and Hashset Some difference between ArrayList and Hashset are: - ArrayList implements List interface while HashSet implements Set interface in Java. - ArrayList can have duplicate values while HashSet doesn’t allow any duplicates values. - ArrayList maintains the insertion order that means the object in which they are inserted will be intact while HashSet is an unordered collection that doesn’t maintain any insertion order. - ArrayList is backed by an Array while HashSet is backed by an HashMap. - ArrayList allow any number of null value while HashSet allow one null value. - Syntax:- ArrayList:-ArrayList list=new ArrayList(); - HashSet:-HashSet set=new HashSet(); 2. Using Lambda Function print given List of Integers import java.util.*; public class Main { public static void main(String args) { List arr = Arrays.asList(1,2,3,4); arr.forEach(System.out::println); arr.stream().forEach(s->System.out.println(s)); } } Output 1 2 3 4 3. new ArrayList(2); What does this mean? 4. Difference in Synchronization and Lock Differences between lock and synchronized: - with locks, you can release and acquire the locks in any order. - with synchronized, you can release the locks only in the order it was acquired. 5. What is Closeable interface? A Closeable is a source or destination of the data that needs to be closed. The close() method is invoked when we need to release resources that are being held by objects such as open files. The close() method of an AutoCloseable object is called automatically when exiting a try -with-resources block for which the object has been declared in the resource specification header. Closeable is defined in java.io and it is idempotent. Idempotent means calling the close() method more than once has no side effects. Declaration public interface Closeable extends AutoCloseable { public void close() throws IOException; } Implementing the Closeable interface import java.io.*; class Main { public static void main(String s) { try (Demo1 d1 = new Demo1(); Demo2 d2 = new Demo2()) { d1.show1(); d2.show2(); } catch (ArithmeticException e) { System.out.println(e); } } } //Resource1 class Demo1 implements Closeable { void show1() { System.out.println("inside show1"); } public void close() { System.out.println("close from demo1"); } } //Resource2 class Demo2 implements Closeable { void show2() { System.out.println("inside show2"); } public void close() { System.out.println("close from demo2"); } } Output inside show1 inside show2 close from demo2 close from demo1 6. What are Lambda Functions? A lambda expression is a block of code that takes parameters and returns a value.  Syntax of Lambda Expression Lambda expression contains a single parameter and an expression parameter -> expression Lambda expression contains a Two parameter and an expression (parameter1, parameter2) -> expression Expressions cannot contain variables, assignments or statements such as if or for. If you wanted to do some more complex operations, a code block can be used with curly braces. If the lambda expression needs to return a value, then the code block should have a return statement. (parameter1, parameter2) -> { code block } import java.util.ArrayList; public class Main { public static void main(String args) { ArrayList list = new ArrayList(); list.add(1); list.add(2); list.add(3); list.add(4); list.forEach( (n) -> { System.out.println(n); } ); } } Output 1 2 3 4 7. What are @Component and @Service used for? @Component @Component annotation is used across the application to mark the beans as Spring's managed components.  Spring check for @Component annotation and will only pick up and register beans with @Component, and doesn't look for @Service and @Repository in general. @Repository @Repository annotation is used to indicate that the class provides the mechanism for storage, retrieval, search, update and delete operation on objects. @Service We mark beans with @Service to indicate that they're holding the business logic. Besides being used in the service layer, there isn't any other special use for this annotation. 8. Why 'get' type in REST API called idempotent? An idempotent HTTP method is a method that can be invoked many times without the different outcomes. It should not matter if the method has been called only once, or ten times over. The result should always be the same. - POST is NOT idempotent. - GET, PUT, DELETE, HEAD, OPTIONS and TRACE are idempotent. - A PATCH is not necessarily idempotent, although it can be. 9. Working of HashMap HashMap contains an array of Node and Node can represent a class having the following objects :  - int hash - K key - V value - Node next 10. What are different types of method in REST API? Some different types of REST API Methods are GET, POST,  PUT,  PATCH,  DELETE. 11. How to load application.yml file in application. To Work with application.yml file, create a application.yml in the src/resources folder. Spring Boot will load and parse yml file automatically and bind the values into the classes which annotated with @ConfigurationProperties 12. /users/:id and /user/name={"Saurabh"} convert into API 13. What is Transaction Management in Spring? A database transaction is a sequence of actions that are treated as a single unit of work. These actions should either complete entirely or take no effect at all. Transaction management is an important part of RDBMS-oriented enterprise application to ensure data integrity and consistency. The concept of transactions can be described with the following four key properties described as ACID  - Atomicity − A transaction should be treated as a single unit of operation, which means either the entire sequence of operations is successful or unsuccessful. - Consistency − This represents the consistency of the referential integrity of the database, unique primary keys in tables, etc. - Isolation − There may be many transaction processing with the same data set at the same time. Each transaction should be isolated from others to prevent data corruption. - Durability − Once a transaction has completed, the results of this transaction have to be made permanent and cannot be erased from the database due to system failure. 14. How to load application.yml file in application? Ans: @EnableConfigurationProperties 15. Backward Compatibility of Java 1.8 Java versions are expected to be binary backwards-compatible. For example, JDK 8 can run code compiled by JDK 7 or JDK 6. It is common to see applications leverage this backwards compatibility by using components built by different Java version. A Compatibility Guide (explained later) exists for each major release to provide special mention when something is not backwards compatible. The backwards compatibility means that you can run Java 7 program on Java 8 runtime, not the other way around. 16. Input- Output- How to do this? import java.util.*; class Main { public static void main(String s) { ArrayList arr = new ArrayList(Arrays.asList(4,2,6,8,9,1,3,4)); Set set = new HashSet(); set.addAll(arr); arr.clear(); arr.addAll(set); System.out.println(arr); } } Output 17. Default size of HashSet? Default size of HashSet is 16. 18.  What is Functional Interface and it's example? Functional Interface is a Interface that contains only one abstract method. It can contains any number of default, static methods but can have only one abstract method. Abstract method is a method that does not have a body.  @FunctionalInterface interface CustomFunctionalInterface { void display(); } public class Main { public static void main(String args) { CustomFunctionalInterface functionalInterface = () -> { System.out.println("Functional Interface Example"); }; functionalInterface.display(); } } Output Functional Interface Example 19. Difference between Encapsulation and Data Hiding.
Key Differences Between Data Hiding and Encapsulation
- Encapsulation deals with hiding the complexity of a program. On the other hand, data hiding deals with the security of data in a program. - Encapsulation focuses on wrapping (encapsulating) the complex data in order to present a simpler view for the user. On the other hand, data hiding focuses on restricting the use of data, intending to assure the data security. - In encapsulation data can be public or private but, in data hiding, data must be private only. - Data hiding is a process as well as a technique whereas, encapsulation is subprocess in data hiding. 20. What are generics? Generics means parameterized types. The idea is to allow type (Integer, String, … etc., and user-defined types) to be a parameter to methods, classes, and interfaces. Using Generics, it is possible to create classes that work with different data types. An entity such as class, interface, or method that operates on a parameterized type is a generic entity. class GenericTest { T obj; GenericTest(T obj) { this.obj = obj; } public T getObject() { return this.obj; } } class Main { public static void main(String args) { GenericTest obj1 = new GenericTest(10); System.out.println(obj1.getObject()); GenericTest obj2 = new GenericTest("Generic Example"); System.out.println(obj2.getObject()); } } Output 10 Generic Example Read the full article
0 notes
felord · 3 years
Text
COMP1020 Lab11-Simple sorting – the Selection Sort Solved
COMP1020 Lab11-Simple sorting – the Selection Sort Solved
Simple sorting – the Selection Sort Notes: The three exercises in this lab are independent – they can be done in any order. However, the Gold exercise is very similar to the Bronze exercise, and it would be best to do the Bronze exercise first. Only one of the three exercises is required, but try to do as many as you can. Selection Sort to print an ArrayList Start with the file java. Complete…
Tumblr media
View On WordPress
0 notes
sharifs · 6 years
Text
Coding A Raffle List Editor in Java Using ArrayList
One night in the summer while looking over my decent game collection which you may have seen in the background of one of my “Video Game Sheriff” series videos, while having trouble deciding which of the many great games I wanted to play in that moment, I was inspired to write a program that could work like a hat where I could put in the titles of all my games then select one out at random.
youtube
You can get a glimpse of my collection in the background of some of my videos also posted on this site.
The resultant application is a console based editor which allows the user to build his own list of titles, edit them, delete them individually, clear them all, save them to a text file as well as read the text file made (or imported to the folder) prior to running the program.
I’m going to go through each part of the code and explain why I made the choices I did. I hope this can provide a good reference or template for your java projects.
My main method for accomplishing the editor and raffle program was centered around the use of arraylist along with some basic IO work. Let’s dive right in:
First I imported the libraries I thought I might need (you can figure this out as you go along of course)
import java.util.*; import java.io.*; import java.nio.file.*;
Variables
I decided to write this procedurally as one class since this is not a huge complex program being developed in a massive organization. I called my main class “Interface” but you can choose any name you want for yours. I decided to make a unique scanner object for each part of the program, but this may not be necessary in your project. I have laid out all the variables I used, though you may get by on more or less variables, considering the structure of my app, it will need to use at least one arraylist to function. Note that I use a Random class from the library in order to generate a random seed for the raffle feature.
public class Interface { public static void main(String[] args) throws IOException { Scanner selection = new Scanner(System.in); Scanner input = new Scanner(System.in); Scanner in = new Scanner(System.in); Scanner edit = new Scanner(System.in); int currentChoice = 0; String currentGame = "null"; ArrayList<String> games = new ArrayList<String>(); Random raffleWheel = new Random(); String userEdit = "null"; int gameIndex = 0; int gameIndex4D = 0;
Menu LOOP
The top of my program begins with a welcome message and a menu in a while loop along with an input scanner object awaiting user input based on selecting from the menu (loop closes at end of program shown at end of article). Note that because choices 8 & 9 exit the program, I made that as the loop condition.
System.out.println("Welcome to the Backlog Gaming Sheriff's Super Raffler!\n"); while (currentChoice <= 7 || currentChoice >= 10){ System.out.println("\n1. Run the Raffler and make a random selection."); System.out.println("2. View game list"); System.out.println("3. Add new game to the list"); System.out.println("4. Delete a game from the list"); System.out.println("5. Edit a game on the list"); System.out.println("6. Clear Game List"); System.out.println("7. Read Game List"); System.out.println("8. Quit & Save List"); System.out.println("9. Quit without saving\n"); System.out.println("Please make a selection from the above options"); currentChoice = selection.nextInt();
Conditional Statements
Next up are the conditional statements that serve as the engine of the program. I first start with a potentially erroneous input, beyond the menu choices.
if (currentChoice > 9){ System.out.println("Error. Invalid input. Please try again.\n"); }
My next conditional statement is for choice #7 from the menu to read the game list, as that is often the first thing the user may need to do.
else if (currentChoice == 7){ try (BufferedReader br = new BufferedReader(new FileReader("Game_List.txt"))) { String line; while ((line = br.readLine()) != null) { games.add(line); } } }
The following conditional statement allows the user to delete a title from the list while providing the option to confirm or cancel the deletion of that item (more fail safe than C!) and provides the template for other options requiring submenu options. Note my use of ArrayList class’s ‘size’ function to determine the length of the array to base the validity of the index number on.
else if (currentChoice == 4){ int counter = 1; while (counter != 0){ System.out.println("\nPlease enter game index number"); gameIndex4D = in.nextInt(); if (gameIndex4D > games.size()){ System.out.println("\nError. Invalid index number."); } else if (gameIndex4D < 0){ System.out.println("\nError. Invalid index number."); } else counter = 0; } System.out.println("\nThe selected game title currently is:"); System.out.println(games.get(gameIndex4D)); System.out.println("\nAre you sure you want to delete the selected title?"); System.out.println("1. Confirm"); System.out.println("2. Cancel"); int userChoice = in.nextInt(); if (userChoice == 1){ games.remove(gameIndex4D); System.out.println("Selected title deleted."); } else if (userChoice == 2 || userChoice < 1 || userChoice >2){ System.out.println("Deletion Canceled."); } }
A simpler version of the above condition, allows the user to clear the entire list from the program (but not the file).
else if (currentChoice == 6){ System.out.println("\nAre you sure you want to delete all titles?"); System.out.println("1. Confirm"); System.out.println("2. Cancel"); int userChoice = in.nextInt(); if (userChoice == 1){ while (games.size() > 0){ games.remove(games.size()-1); } System.out.println("Game list cleared."); } else if (userChoice == 2 || userChoice < 1 || userChoice >2){ System.out.println("Deletion Canceled."); } }
To add a title, I simply used ArrayList class’s ‘add’ function.
else if (currentChoice == 3){ System.out.println("\nPlease enter game name"); currentGame = input.nextLine(); games.add(currentGame); }
In order to list out every title in the ArrayList for the user, I wrote a simple for loop to handle that task for each item in the list, printed with print line.
else if (currentChoice == 2){ for (int i=0;i<(games.size());i++){ System.out.println(games.get(i)); } }
The conditional statement after that handles the actual raffle feature, randomly selecting one title from the entire list.
else if (currentChoice == 1){ System.out.println("Running Raffler\n"); for (int i=1;i<4;i++){ System.out.print("."); } int raffleNum = raffleWheel.nextInt(games.size()); String raffleGame = games.get(raffleNum); System.out.println("\n" + raffleGame); }
Once again using the submenu template I wrote for the delete option, this condition was developed to allow the user to change the name of a title he already added based on the index number (with title 1 starting at index 0, title 2 at index 1, etc…).
else if (currentChoice == 5){ int counter2 = 1; while (counter2 != 0){ System.out.println("\nPlease enter game index number"); gameIndex = in.nextInt(); if (gameIndex > games.size()){ System.out.println("\nError. Invalid index number."); } else if (gameIndex < 0){ System.out.println("\nError. Invalid index number."); } else counter2 = 0; } System.out.println("\nThe selected game title currently is:"); System.out.println(games.get(gameIndex)); System.out.println("\nPlease enter replacement title:"); userEdit = edit.nextLine(); games.set(gameIndex, userEdit); }
For the quit and save option, I use a try/catch structure as the standard to prevent the IO process from having any problems. This code successfully writes the current program’s ArrayList to a designated text file in the program folder.
if (currentChoice == 8){ System.out.println("Goodbye!"); try{ PrintWriter gameList = new PrintWriter("Game_List.txt"); for (int i=0;i<(games.size());i++){ gameList.println(games.get(i)); } gameList.close(); } catch (Exception ex) { ex.printStackTrace(); } }
End Of The Program
I end off the program with a simple goodbye message and the necessary closing braces to close out the while loop, main class and surrounding “Interface” class.
if (currentChoice == 9){ System.out.println("Goodbye!"); } } } }
Feel free to copy and paste all the above code in order to an appropriately named class and run it for yourself. Hopefully this can help you on your journey to learn Java or in your working project.
(adsbygoogle = window.adsbygoogle || []).push({});
Related Posts
The 3 Business Pipelines & The Roles Of Each
“Why Are There C# & Java Web Developers When We Have Javascript?” #Programming College Student Q&A: #WebDev
3 Things You Have To Do To Make A Game [Video Update]
Indie VS Mainstream Business Conflicts
“What Is Visual Scripting Anyway?”
Production Hacks 101 – “What is Production Hacking Anyway?”
What Your Rich Open-World RPG Will Need #17Ideas
Why You Should Script It
1 note · View note
chieffacedefendor · 4 years
Link
Array List in Java are the important data structures that can be extended to accommodate a greater number of elements and shrink back by removing items from the array when not needed. This is highly important if you wanted to handle elements within array dynamically. Here is an example of how to print the whole array list in Java –
System.out.println(“Whole List=”+ ListTest);
0 notes
Link
Have you ever solved a real-life maze? The approach that most of us take while solving a maze is that we follow a path until we reach a dead end, and then backtrack and retrace our steps to find another possible path. This is exactly the analogy of Depth First Search (DFS). It's a popular graph traversal algorithm that starts at the root node, and travels as far as it can down a given branch, then backtracks until it finds another unexplored path to explore. This approach is continued until all the nodes of the graph have been visited. In today’s tutorial, we are going to discover a DFS pattern that will be used to solve some of the important tree and graph questions for your next Tech Giant Interview! We will solve some Medium and Hard Leetcode problems using the same common technique. So, let’s get started, shall we?
Implementation
Since DFS has a recursive nature, it can be implemented using a stack. DFS Magic Spell:
Push a node to the stack
Pop the node
Retrieve unvisited neighbors of the removed node, push them to stack
Repeat steps 1, 2, and 3 as long as the stack is not empty
Graph Traversals
In general, there are 3 basic DFS traversals for binary trees:
Pre Order: Root, Left, Right OR Root, Right, Left
Post Order: Left, Right, Root OR Right, Left, Root
In order: Left, Root, Right OR Right, Root, Left
144.  Binary Tree Preorder Traversal (Difficulty: Medium)
To solve this question all we need to do is simply recall our magic spell. Let's understand the simulation really well since this is the basic template we will be using to solve the rest of the problems.
Tumblr media
At first, we push the root node into the stack. While the stack is not empty, we pop it, and push its right and left child into the stack. As we pop the root node, we immediately put it into our result list. Thus, the first element in the result list is the root (hence the name, Pre-order). The next element to be popped from the stack will be the top element of the stack right now: the left child of root node. The process is continued in a similar manner until the whole graph has been traversed and all the node values of the binary tree enter into the resulting list.
Tumblr media
145. Binary Tree Postorder Traversal (Difficulty: Hard)
Pre-order traversal is root-left-right, and post-order is right-left-root. This means post order traversal is exactly the reverse of pre-order traversal. So one solution that might come to mind right now is simply reversing the resulting array of pre-order traversal. But think about it – that would cost O(n) time complexity to reverse it. A smarter solution is to copy and paste the exact code of the pre-order traversal, but put the result at the top of the linked list (index 0) at each iteration. It takes constant time to add an element to the head of a linked list. Cool, right?
Tumblr media
94. Binary Tree Inorder Traversal (Difficulty: Medium)
Our approach to solve this problem is similar to the previous problems. But here, we will visit everything on the left side of a node, print the node, and then visit everything on the right side of the node.
Tumblr media
323. Number of Connected Components in an Undirected Graph (Difficulty: Medium)
Our approach here is to create a variable called ans that stores the number of connected components. First, we will initialize all vertices as unvisited. We will start from a node, and while carrying out DFS on that node (of course, using our magic spell), it will mark all the nodes connected to it as visited. The value of ans will be incremented by 1.
import java.util.ArrayList; import java.util.List; import java.util.Stack; public class NumberOfConnectedComponents { public static void main(String[] args){ int[][] edge = {{0,1}, {1,2},{3,4}}; int n = 5; System.out.println(connectedcount(n, edge)); } public static int connectedcount(int n, int[][] edges) { boolean[] visited = new boolean[n]; List[] adj = new List[n]; for(int i=0; i<adj.length; i++){ adj[i] = new ArrayList<Integer>(); } // create the adjacency list for(int[] e: edges){ int from = e[0]; int to = e[1]; adj[from].add(to); adj[to].add(from); } Stack<Integer> stack = new Stack<>(); int ans = 0; // ans = count of how many times DFS is carried out // this for loop through the entire graph for(int i = 0; i < n; i++){ // if a node is not visited if(!visited[i]){ ans++; //push it in the stack stack.push(i); while(!stack.empty()) { int current = stack.peek(); stack.pop(); //pop the node visited[current] = true; // mark the node as visited List<Integer> list1 = adj[current]; // push the connected components of the current node into stack for (int neighbours:list1) { if (!visited[neighbours]) { stack.push(neighbours); } } } } } return ans; } }
200. Number of Islands (Difficulty: Medium)
This falls under a general category of problems where we have to find the number of connected components, but the details are a bit tweaked. Instinctually, you might think that once we find a “1” we initiate a new component. We do a DFS from that cell in all 4 directions (up, down, right, left) and reach all 1’s connected to that cell. All these 1's connected to each other belong to the same group, and thus, our value of count is incremented by 1. We mark these cells of 1's as visited and move on to count other connected components.
Tumblr media
547. Friend Circles (Difficulty: Medium)
This also follows the same concept as finding the number of connected components. In this question, we have an NxN matrix but only N friends in total. Edges are directly given via the cells so we have to traverse a row to get the neighbors for a specific "friend". Notice that here, we use the same stack pattern as our previous problems.
Tumblr media
That's all for today! I hope this has helped you understand DFS better and that you have enjoyed the tutorial. Please recommend this post if you think it may be useful for someone else!
0 notes
siva3155 · 4 years
Text
300+ TOP JAVA SPRING Objective Questions and Answers
Java Spring Multiple Choice Questions :-
1. What is the meaning of the return data type void? A. An empty memory space is returned so that the developers can utilize it. B. void returns no data type. C. void is not supported in Java D. None of the above Ans: B 2. A lower precision can be assigned to a higher precision value in JavA. For example a byte type data can be assigned to int type. A. True B. False Ans : B 3. Which of the following statements about the Java language is true? A. Both procedural and OOP are supported in JavA. B. Java supports only procedural approach towards programming. C. Java supports only OOP approach. D. None of the above. Ans: A 4. Which of the following statements is false about objects? A. An instance of a class is an object B. Objects can access both static and instance data C. Object is the super class of all other classes D. Objects do not permit encapsulation Ans: D 5. Which methods can access to private attributes of a class? A. Only Static methods of the same class B. Only instances of the same class C. Only methods those defined in the same class D. Only classes available in the same package. Ans: C 6. What is an aggregate object? A. An object with only primitive attributes B. An instance of a class which has only static methods C. An instance which has other objects D. None of the above Ans: C 7. Assume that File is an abstract class and has toFile() methoD. ImageFile and BinaryFile are concrete classes of the abstract class File. Also, assume that the method toFile() is implemented in both Binary File and Image File. A File references an ImageFile object in memory and the toFile method is called, which implementation method will be called? A. Binary File B. Image File C. Both File and Binary Files D. None of the above Ans: B 8. A class can have many methods with the same name as long as the number of parameters or type of parameters is different. This OOP concept is known as A. Method Invocating B. Method Overriding C. Method Labeling D. Method Overloading Ans: D 9. Which of the following is considered as a blue print that defines the variables and methods common to all of its objects of a specific kind? A. Object B. Class C. Method D. Real data types Ans: B 10. What are the two parts of a value of type double? A. Significant Digits, Exponent B. Length, Denominator C. Mode, Numerator Ans: A
Tumblr media
JAVA SPRING MCQs 11. After the following code fragment, what is the value in fname? String str; int fname; str = "Foolish boy."; fname = str.indexOf("fool"); A. 0 B. 2 C. -1 D. 4 Ans: C 12. What is the value of ‘number’ after the following code fragment execution? int number = 0; int number2 = 12 while (number { number = number + 1; } A. 5 B. 12 C. 21 D. 13 Ans: B 13. Given the following code snippet; int salaries[; int index = 0; salaries = new int salaries[4; while (index { salaries[index = 10000; index++; } What is the value of salaries [3? A. 40000 B. 50000 C. 15000 D. 10000 Ans: D 14. Which of the following is not a return type? A. boolean B. void C. public D. Button Ans: C 15. If result = 2 + 3 * 5, what is the value and type of ‘result’ variable? A. 17, byte B. 25, byte C. 17, int D. 25, int Ans: C 16. What is the data type for the number 9.6352? A. float B. double C. Float D. Double Ans: B 17. Assume that the value 3929.92 is of type ‘float’. How to assign this value after declaring the variable ‘interest’ of type float? A. interest = 3929.92 B. interest = (Float)3929.92 C. interest = 3929.92 (float) D. interest = 3929.92f Ans: D 18. Which of the following statements is true? A. The default char data type is a space( ‘ ‘ ) character. B. The default integer data type is ‘int’ and real data type is ‘float’ C. The default integer data type is ‘long’ and real data type is ‘float’ D. The default integer data type is ‘int’ and real data type is ‘double’ Ans: D 19. How many numeric data types are supported in Java? A. 8 B. 4 C. 2 D. 6 Ans: D 20. Which of the following statements declare class Sample to belong to the payroll.admindept package? A. package payroll;package admindept; B. import payroll.*; C. package payroll.admindept.Sample; D. import payroll.admindept.*; E. package payroll.admindept; Ans: E 21. The class javA.lang.Exception is A. protected B. extends Throwable C. implements Throwable D. serializable Ans: B 22. Which of the following statements is true? A. An exception can be thrown by throw keyword explicitly. B. An exception can be thrown by throws keyword explicitly. Ans: A 23. All the wrapper classes (Integer, Boolean, Float, Short, Long, Double and Character) in java A. are private B. are serializable C. are immutatable D. are final Ans: D 24. The code snippet if( "Welcome".trim() == "Welcome".trim() ) System.out.println("Equal"); else System.out.println("Not Equal"); will A. compile and display “Equal” B. compile and display “Not Equal” C. cause a compiler error D. compile and display NULL Ans: C 25. Consider the following code snippet. What will be assigned to the variable fourthChar, if the code is executed? String str = new String(“Java”); char fourthChar = str.charAt(4); A. ‘a’ B. ‘v’ C. throws StringIndexOutofBoundsException D. null character Ans: C 26. Which of the following statements is preferred to create a string "Welcome to Java Programming"? A. String str = “Welcome to Java Programming” B. String str = new String( “Welcome to Java Programming” ) C. String str; str = “Welcome to Java Programming” D. String str; str = new String (“Welcome to Java Programming” ) Ans: A 27. Which of the following statements is true? A. A super class is a sub set of a sub class B. class ClassTwo extends ClassOne means ClassOne is a subclass C. class ClassTwo extends ClassOne means ClassTow is a super class D. the class Class is the super class of all other classes in JavA. Ans: A 28. What kind of thread is the Garbage collector thread is? A. Non daemon thread B. Daemon thread C. Thread with dead state D. None of the above Ans: B 29. When a thread terminates its processing, into what state that thread enters? A. Running state B. Waiting state C. Dead state D. Beginning state Ans: C 30. Which statement is true? A. HashTable is a sub class of Dictionary B. ArrayList is a sub class of Vector C. LinkedList is a subclass of ArrayList D. Vector is a subclass of Stack Ans: A 31. Which of these statements is true? A. LinkedList extends List B. AbstractSet extends Set C. HashSet extends AbstractSet D. WeakHashMap extends HashMap Ans: C 32. Which of the following is synchronized? A. Set B. LinkedList C. Vector D. WeakHashMap Ans: C 33. Select all the true statements from the following. A. AbstractSet extends AbstractCollection B. AbstractList extends AbstractCollection C. HashSet extends AbstractSet D. Vector extends AbstractList E. All of the above Ans: E 34. Which of the methods should be implemented if any class implements the Runnable interface? A. start() B. run() C. wait() D. notify() and notifyAll() Ans: B 35. A thread which has invoked wait() method of an object, still owns the lock of the object. Is this statement true or false? A. True B. False Ans: B 36. Which of the following is not a method of the Thread class. A. public void run() B. public void start() C. public void exit() D. public final int getPriority() Ans: C 37. To execute the threads one after another A. the keyword synchronize is used B. the keyword synchronizable is used C. the keyword synchronized is used D. None of the above Ans: B 38. The object of DataInputStream is used to A. To covert binary stream into character stream B. To covert character stream into binary stream C. To write data onto output object D. All of the above Ans: A 39. DataInputStream is an example of A. Output stream B. I/O stream C. Filtered stream D. File stream Ans: C 40. From a MVC perspective, Struts provides the A. Model B. View C. Controller Ans: B 41.Consider the following program: import myLibrary.*; public class ShowSomeClass { // code for the class... } What is the name of the java file containing this program? A. myLibrary.java B. ShowSomeClass.java C. ShowSomeClass D. ShowSomeClass.class E. Any file name with the java suffix will do Ans: B 42.Which of the following is TRUE? A. In java, an instance field declared public generates a compilation error. B. int is the name of a class available in the package javA.lang C. Instance variable names may only contain letters and digits. D. A class has always a constructor (possibly automatically supplied by the java compiler). E. The more comments in a program, the faster the program runs. Ans: D 43.Consider the following code snippet String river = new String(“Columbia”); System.out.println(river.length()); What is printed? A. 6 B. 7 C. 8 D. Columbia E. river Ans: C 44. A constructor A. must have the same name as the class it is declared within. B. is used to create objects. C. may be declared private D. A and B E. A, B and C Ans: E 45.Which of the following may be part of a class definition? A. instance variables B. instance methods C. constructors D. all of the above E. none of the above Ans: D 46.What is different between a Java applet and a Java application? A. An application can in general be trusted whereas an applet can't. B. An applet must be executed in a browser environment. C. An applet is not able to access the files of the computer it runs on D. (A), (B) and (C). E. None of the above Ans: D 47.Consider public class MyClass{ public MyClass(){/*code*/} // more code... } To instantiate MyClass, you would write? A. MyClass mc = new MyClass(); B. MyClass mc = MyClass(); C. MyClass mc = MyClass; D. MyClass mc = new MyClass; E. It can't be done. The constructor of MyClass should be defined as public void MyClass(){/*code*/} Ans: A 48.What is byte code in the context of Java? A. The type of code generated by a Java compiler B. The type of code generated by a Java Virtual Machine C. It is another name for a Java source file D. It is the code written within the instance methods of a class. E. It is another name for comments written within a program. Ans: A 49.What is garbage collection in the context of Java? A. The operating system periodically deletes all of the java files available on the system. B. Any package imported in a program and not used is automatically deleteD. C. When all references to an object are gone, the memory used by the object is automatically reclaimeD. D. The JVM checks the output of any Java program and deletes anything that doesn't make sense. E. Janitors working for Sun MicroSystems are required to throw away any Microsoft documentation found in the employees' offices. Ans: c 50.You read the following statement in a Java program that compiles and executes. submarine.dive(depth); What can you say for sure? A. depth must be an int B. dive must be a methoD.(ans) C. dive must be the name of an instance fielD. D. submarine must be the name of a class E. submarine must be a methoD. Ans: B 51.  Formed on a diskette (or hard drive) during initialization. A. source code B. images C. sectors D. storage units Ans: C 52.  The CPU consists of: A. Control Unit, Temporary Memory, Output B. Control Unit, Arithmetic Logic Unit, Temporary Memory C. Input, Process, Storage, Output D. Input, Control Unit, Arithmetic Logic Unit, Output Ans: B 53.  OOP stands for: A. Observable Object Programming B. Object Observed Procedures C. Object Oriented Programming D. Object Overloading Practices Ans: C 54.  Output printed on paper. A. softcopy B. hardcopy C. source code D. software Ans: B 55.  A binary digit (1 or 0) signifying "on" or "off". A. bit B. byte C. megabyte D. gigabyte Ans: A 56.  Our decimal number 44, when represented in binary, is: A. 101100 B. 101010 C. 111000 D. 10100 Ans: A 57.  Byte code is the machine language for a hypothetical computer called the: A. Java Byte Code Compiler B. Java Byte Code Interpreter C. Java Virtual Machine D. Java Memory Machine Ans: C 58.  Equals 8 bits. A. megabyte B. gigabyte C. sector D. byte Ans: D 59.  Java allows for three forms of commenting: A. // single line, ** block lines, /*/ documentation B. // single line, /*...*/ block lines, /**...*/ documentation C. / single line, /* block lines, ** documentation D. // single line, //...// block lines, //*...*// documentation Ans: B 60.  To prepare a diskette (or hard drive) to receive information. A. format B. track C. interpret D. boot Ans: A 61.  In Java, the name of the class must be the same as the name of  the .java file. A. false B. true - but case sensitivity does not apply C. true - but additional numbers may be added to the name D. true Ans: D 62.  The name Java was derived from A. a cup of coffee B. an acronym for JBuilder Activated Variable Assembly C. an acronym for Juxtapositioned Activated Variable Actions D. an acronym for John's Answer for Various Accounts Ans: A 63.  Programs that tell a computer what to do. A. harware B. software C. hard copy D. projects Ans: B 64.  RAM stands for _________. A. Read Anytime Memory B. Read Allocated Memory C. Random Access Memory D. Random Allocated Memory Ans: C 65.  Several computers linked to a server to share programs and storage space. A. library B. grouping C. network D. integrated system Ans: C 66.  Source code in Java will not run if it is not indenteD. A. true B. false Ans: B 67.  When working in Java with JBuilder, each program you write should be assigned to a new project. A. true B. false Ans: A 68.  The four equipment functions of a computer system. A. Input, Process, Control Unit, Output B. Input, Control Unit, Arithmetic Logic Unit, Output C. Input, Process, Storage, Output D. Input, Process, Library Linking, Output Ans: C 69.  Translates and executes a program line by line. A. compiler B. interpreter C. linker D. control unit Ans: B 70.  The physical components of a computer system. A. control unit B. hardware C. software D. ALU Ans: B JAVA SPRING Questions and Answers pdf Download Read the full article
0 notes
uniqtutor-blog · 5 years
Text
Solved: DATA STRUCTURES JAVA CODING ASSIGNMENT Instructions: - Given the English wordlist read all the words into an ArrayList of appropriate type.
Solved: DATA STRUCTURES JAVA CODING ASSIGNMENT Instructions: – Given the English wordlist read all the words into an ArrayList of appropriate type.
Tumblr media
Question:
DATA STRUCTURES JAVA CODING ASSIGNMENT
Instructions:
– Given the English wordlist read all the words into an ArrayList of appropriate type. – Count the number of words using Arraylist methods. Print the number of words – Count the number of duplicate words in the array list, and print the count. – Time the code for steps (ii) and (iii). using System.currentTimeMillis() – Do steps…
View On WordPress
0 notes
Text
Image identification using a convolutional neural network
ICYDK: This blog  explores a typical image identification task using a convolutional ("Deep Learning") neural network. For this purpose we will use a simple JavaCNN packageby D.Persson, and make our example small and concise using the Python scripting language. This example can also be rewritten in Java, Groovy, JRuby or any scripting language supported by the Java virtual machine. This example will use images in the grayscale format (PGM). The name "PGM" is an acronym derived from "Portable Gray Map" where cell values range from 0 - 255. The files are typically in the binary format (it has the magic value "P5" - you can see it by opening one of such files), but you can convert them to "Plain" (or uncompressed PGM), where each pixel in the raster is represented as an ASCII decimal number (of arbitrary size). Our input images are from a publicly available database (CBCL Face Database MIT Center For Biological and Computation Learning). Let us copy a zip file with this (slightly modifies) database and unzip it. To do this, install the most recent DataMelt program, make a file "example.py" and run these commands using DataMelt: from jhplot import * print Web.get("http://jwork.org/dmelt/examples/data/mitcbcl_pgm_set2.zip") print IO.unzip("mitcbcl_pgm_set2.zip") The last command unzips two directories "train" and "test". You can omit "print", which is only used to print the status of these commands. Each directory has images with faces ("face_*") and some other images ("cmu_*). Note that "_" in the file name is important since this help identify image type. The "train" directory has about 1500 files with images of faces and 13700 files with other types of images. Let us look at one image and study its properties. We will use the IJ Java package. Append the following code to your previous lines: from ij import * imp = IJ.openImage("mitcbcl_pgm_set2/train/face_00001.pgm") print "Width:", imp.width," Hight:", imp.height imp.show() # show this image in a frame ip = imp.getProcessor().convertToFloat() pixels = ip.getPixels() # get array of pixels print pixels # print array with pixels These commands show an image on the screen, print its size (19x19 pixels) and the 3D matrix with the PGM image values. Now let us create a code which will do the following: * Reads the images from "train/" directory * Reads the images from "test/" directory * Initialize the CNN using several convolutional layers and pooling layers * It runs over 50 iterations. You can increase or decrease this number depending on the required precision of image identification. * During each iteration it calculates the probability for correct identification images with faces from the "test/" directory and saves the CNN to a file * At the end of the training, it reads the trained CNN from the file and performs the final run over test images, printing the predictions. Copy these lines and save in a file "example.py". Then  run this code inside the DataMelt: from jhplot import * print Web.get("http://jwork.org/dmelt/examples/data/mitcbcl_pgm_set2.zip") print IO.unzip("mitcbcl_pgm_set2.zip") NMax=50 # Total runs. Reduce this number to get results faster from org.ea.javacnn.data import DataBlock,OutputDefinition,TrainResult from org.ea.javacnn.layers import DropoutLayer,FullyConnectedLayer,InputLayer,LocalResponseNormalizationLayer from org.ea.javacnn.layers import ConvolutionLayer,RectifiedLinearUnitsLayer,PoolingLayer from org.ea.javacnn.losslayers import SoftMaxLayer from org.ea.javacnn.readers import ImageReader,MnistReader,PGMReader,Reader from org.ea.javacnn.trainers import AdaGradTrainer,Trainer from org.ea.javacnn import JavaCNN from java.util import ArrayList,Arrays from java.lang import System layers = ArrayList(); de = OutputDefinition() print "Total number of runs=", NMax print "Reading train sample.." mr = PGMReader("mitcbcl_pgm_set2/train/") print "Total number of trainning images=",mr.size()," Nr of types=",mr.numOfClasses() print "Read test sample .." mrTest = PGMReader("mitcbcl_pgm_set2/test/") print "Total number of test images=",mrTest.size()," Nr of types=",mrTest.numOfClasses() modelName = "model.ser" # save NN to this file layers.add(InputLayer(de, mr.getSizeX(), mr.getSizeY(), 1)) layers.add(ConvolutionLayer(de, 5, 32, 1, 2)) # uses different filters layers.add(RectifiedLinearUnitsLayer()) # applies the non-saturating activation function layers.add(PoolingLayer(de, 2,2, 0)) # creates a smaller zoomed out version layers.add(ConvolutionLayer(de, 5, 64, 1, 2)) layers.add(RectifiedLinearUnitsLayer()) layers.add(PoolingLayer(de, 2,2, 0)) layers.add(FullyConnectedLayer(de, 1024)) layers.add(LocalResponseNormalizationLayer()) layers.add(DropoutLayer(de)) layers.add(FullyConnectedLayer(de, mr.numOfClasses())) layers.add(SoftMaxLayer(de)) print "Training.." net = JavaCNN(layers) trainer = AdaGradTrainer(net, 20, 0.001) from jarray import zeros numberDistribution,correctPredictions = zeros(10, "i"),zeros(10, "i") start = System.currentTimeMillis() db = DataBlock(mr.getSizeX(), mr.getSizeY(), 1, 0) for j in range(NMax): loss = 0 for i in range(mr.size()): db.addImageData(mr.readNextImage(), mr.getMaxvalue()) tr = trainer.train(db, mr.readNextLabel()) loss = loss + tr.getLoss() if (i != 0 and i % 500 == 0): print "Nr of images: ",i," Loss: ",(loss/float(i)) print "Loss: ", (loss / float(mr.size())), " for run=",j mr.reset() print 'Wait.. Calculating predictions for labels=', mr.getLabels() Arrays.fill(correctPredictions, 0) Arrays.fill(numberDistribution, 0) for i in range(mrTest.size()): db.addImageData(mrTest.readNextImage(), mr.getMaxvalue()) net.forward(db, False) correct = mrTest.readNextLabel() prediction = net.getPrediction() if(correct == prediction): correctPredictions[correct] +=1 numberDistribution[correct] +=1 mrTest.reset() print " -> Testing time: ",int(0.001*(System.currentTimeMillis() - start))," s" print " -> Current run:",j print net.getPredictions(correctPredictions, numberDistribution, mrTest.size(), mrTest.numOfClasses()) print " -> Save current state to ",modelName net.saveModel(modelName) print "Read trained network from ",modelName," and make the final test" cnn =net.loadModel(modelName) Arrays.fill(correctPredictions, 0) Arrays.fill(numberDistribution, 0) for i in range(mrTest.size()): db.addImageData(mrTest.readNextImage(), mr.getMaxvalue()) net.forward(db, False) correct = mrTest.readNextLabel() prediction = net.getPrediction() if(correct == prediction): correctPredictions[correct] +=1 numberDistribution[correct] +=1 print "Final test:" print net.getPredictions(correctPredictions, numberDistribution, mrTest.size(), mrTest.numOfClasses()) 50 iterations usually take a few hours. The final probability to identify images with human faces will be close to 85%. Taking into account the complexity of this task, this is a rather decent performance. https://goo.gl/jxFCD6 #DataScience #Cloud
0 notes
janbaskt · 6 years
Link
0 notes
felord · 5 years
Text
CS526 Homework Assignment 6 Solution
Tumblr media
This assignment has two parts. Part 1 is an experiment that compares insertion times and search times of hash data structure, array list data structure, and linked list data structure. Part 2 is an experiment that compares the running times of four different sorting algorithms.  
Part 1 (50 points)
  The goal of Part 1 is to give students an opportunity to observe differences among three data structures in Java – HashMap, ArrayList, LinkedList – in terms of insertion time and search time.   Students are required to write a program named InsertSearchTimeComparison.java that implements the following pseudocode:   create a HshMap instance myMap create an ArrayList instance myArrayList create a LinkedList instance myLinkedList   Repeat the following 10 times and calculate average total insertion times and average total search times for all three data structures   generate 100,000 random integers in the range and store them in the array of integers keys   // Insert keys one at a time but measure only the total time (not individual insert  // time) // Use put method for HashMap // Use add method for ArrayList and Linked List   insert all keys in keys into myMap and measure the total insert time insert all keys in keys into  myArrayList and measure the total insert time insert all keys in keys into myLinkedList and measure the total insert time   // after insertion, keep the three data structures with all inserted keys.   generate 100,000 random integers in the range and store them in the array keys   // Search keys one at a time but measure only total time (not individual search // time) // Use containsKey method for HashMap // Use contains method for ArrayList and Linked List   search myMap for all keys in keys and measure the total search time search myArrayList for all keys in keys and measure the total search time search myLinkedList for all keys in keys and measure the total search time   Print your output on the screen using the following format:   Number of keys = 100000   HashMap average total insert time = xxxxx ArrayList average total insert time = xxxxx LinkedList average total insert time = xxxxx   HashMap average total search time = xxxxx ArrayList average total search time = xxxxx LinkedList average total search time = xxxxx   You can generate n random integers between 1 and N in the following way:   Random r = new Random(System.currentTimeMillis() ); for i = 0 to n – 1 a = r.nextInt(N) + 1   When you generate random numbers, it is a good practice to reset the seed. When you first create an instance of the Random class, you can pass a seed as an argument, as shown below:   Random r = new Random(System.currentTimeMillis());   You can pass any long integer as an argument. The above example uses the current time as a seed.   Later, when you want to generate another sequence of random numbers using the same Random instance, you can reset the seed as follows:   r.setSeed(System.currentTimeMillis());   You can also use the Math.random( ) method. Refer to a Java tutorial or reference manual on how to use this method.   We cannot accurately measure the execution time of a code segment. However, we can estimate it by measuring an elapsed time, as shown below:   long startTime, endTime, elapsedTime; startTime = System.currentTimeMillis(); // code segment endTime = System.currentTimeMillis(); elapsedTime = endTime ‐ startTime;   We can use the elapsedTime as an estimate of the execution time of the code segment.    
Part 2 (50 points)
  The goal of part 2 is to give students an opportunity to compare and observe how running times of sorting algorithms grow as the input size grows. Since it is not possible to measure an accurate running time of an algorithm, you will use an elapsed time as an approximation as as described in the Part 1.   Write a program named SortingComparison.java that implements four sorting algorithms for this experiment: insertion-sort, merge-sort, quick-sort and heap-sort. A code of insertion-sort is in page 111 of our textbook. An array-based implementation of merge-sort is shown in pages 537 and 538 of our textbook. An array-based implementation of quick-sort is in page 553 of our textbook. You can use these codes, with some modification if needed, for this assignment. For heap-sort, our textbook does not have a code. You can implement it yourself or you may use any implementation you can find on the internet or any code written by someone else. If you use any material (pseudocode or implementation) that is not written by yourself, you must clearly show the source of the material in your report.   A high-level pseudocode is given below:   for n = 10,000, 20,000, . . ., 100,000 (for ten different input sizes) Create an array of n random integers between 1 and 1,000,000 Run insertionsort and calculate the elapsed time // make sure you use the initial, unsorted array Run mergesort and calculate the elapsed time // make sure you use the initial, unsorted array Run quicksort and calculate the elapsed time // make sure you use the initial, unsorted array Run heapsort and calculate the elapsed time   Note that it is important that you use the initial, unsorted array for each sorting algorithm. So, you may want to keep the original array and use a copy when you run each sorting algorithm.   You can calculate the elapsed time of the execution of a sorting algorithm in the following way:   long startTime = System.currentTimeMillis(); call a sorting algorithm long endTime = System.currentTimeMillis(); long elapsedTime = endTime ‐ startTime;   Collect all elapsed times and show the result (1) as a table and (2) as a line graph.   The table should look like:           n Algorithm 10000 20000 30000 40000 50000 60000 70000 80000 90000 100000 insertion                     merge                     quick                     heapsort                       Entries in the table are elapsed times in milliseconds.   The line graph shows the same information but as a graph with four lines, one for each sorting algorithm. The x-axis of the graph is the input size n and the y-axis of the graph is the elapsed time in milliseconds. An example graph is shown below:        
Deliverables
  You need to submit program files and a documentation files.   Two program files to be submitted are InsertSearchTimeComparison.java and SortingComparison.java files. If you have other files that are necessary to compile and run the two programs, you must submit these additional files too   In a documentation file, you must include, for each part, your conclusion/observation/discussion of each experiment.   Combine all program files, additional files (if any), and the documentation file  into a single archive file, such as a zip file or a rar file, and name it LastName_FirstName_hw6.EXT, where EXT is an appropriate file extension (such as zip or rar). Upload it to Blackboard.  
Grading
  For both parts, there is no one correct output. As far as your output is consistent with generally expected output, no point will be deducted. Otherwise, 10 points will be deducted for each part.   If your conclusion/observation/discussion is not substantive, points will be deducted up to 10 points.   If there is no sufficient inline comments, points will be deducted up to 20 points.   Read the full article
0 notes
hasnainamjad · 4 years
Link
An array in Java is a type of variable that can store multiple values. It stores these values based on a key that can be used to subsequently look up that information.
Arrays can be useful for developers to store, arrange, and retrieve large data sets. Whether you are keeping track of high scores in a computer game, or storing information about clients in a database, an array is often the best choice.
Also read: How to use arrays in Python
So, how do you create an array in Java? That all depends on the type of array you want to use!
How to create an array in Java
The word “array” is defined as a data structure, consisting of a collection of elements. These elements must be identified by at least one “index” or “key.”
There are multiple data objects in Java that we could describe as arrays, therefore. We refer to the first as the “Java array.” Though making matters a little more confusing, this is actually most similar to what we would call a “list” in many other programming languages!
This is the easiest way to think about a Java array: as a list of sequential values. Here, a key is automatically assigned to each value in the sequence based on its relative position. The first index is always “0” and from there, the number will increase incrementally with each new item.
Unlike a list in say Python, however, Java arrays are of a fixed size. There is no way to remove elements or to add to the array at run time. This restriction is great for optimized code but of course does have some limitations.
To create this type of array in Java, simply create a new variable of your chosen data type with square brackets to indicate that it is indeed an array. We then enter each value inside curly brackets, separated by commas. Values are subsequently accessed by using the index based on the order of this list.
String listOfFruit[] = {"apple", "orange", "lemon", "pear", "grape"}; System.out.println(listOfFruit[2]);
While it’s not possible to change the size of a Java array, we can change specific values:
listOfFruit[3] = “melon”;
ArrayLists
If you need to use arrays in Java that can be resized, then you might opt for the ArrayList. An ArrayList is not as fast, but it will give you more flexibility at runtime.
To build an array list, you need to initialize it using our chosen data type, and then we can add each element individually using the add method. We also need to import ArrayList from the Java.util package.
import java.util.ArrayList; class Main { public static void main(String[] args) { ArrayList<String> arrayListOfFruit = new ArrayList<String>(); arrayListOfFruit.add("Apple"); arrayListOfFruit.add("Orange"); arrayListOfFruit.add("Mango"); arrayListOfFruit.add("Banana"); System.out.println(arrayListOfFruit); } }
Now, at any point in our code, we will be able to add and remove elements. But keep in mind that doing so will alter the positions of all the other values and their respective keys. Thus, were I to do this:
System.out.println(arrayListOfFruit.get(3)); arrayListOfFruit.add(2, "Lemon"); System.out.println(arrayListOfFruit.get(3));
I would get a different output each time I printed. Note that we use “get” in order to return values at specific indexes, and that I can add values at different positions by passing my index as the first argument.
How to create an array in Java using maps
Another type of array in Java is the map. A map is an associative array that uses key/value pairs that do not change.
This is a perfect way to store phone numbers, for example. Here, you might use the numbers as the values and the names of the contacts as the index. So “197701289321” could be given the key “Jeff.” This makes it much easier for us to quickly find the data we need, even as we add and remove data from our list!
We do this like so:
import java.util.HashMap; import java.util.Map; Map<String, String> phoneBook = new HashMap<String, String>(); phoneBook.put("Adam", "229901239"); phoneBook.put("Fred", "981231999"); phoneBook.put("Dave", "123879122"); System.out.println("Adam's Number: " + phoneBook.get("Adam"));
As you can see then, a Java Array is always an array, but an array is not always a Java Array!
How to use the multidimensional array in Java
Head not spinning enough yet? Then take a look at the multidimensional array in Java!
This is a type of Java Array that has two “columns.”
Imagine that your typical Java array is an Excel spreadsheet. Were that the case, you’d have created a table with just a single column. We might consider it a “one dimensional” database, in that the data only changes from top to bottom. We have as many rows as we like (1st dimension) but only one column (the hypothetical 2nd dimension).
To add more columns, we simply add a second set of square brackets. We then populate the rows and columns. The resulting data structure can be thought of as an “array of arrays,” wherein each element is an entire array itself!
In this example, we are using integers (whole numbers):
int[][] twoDimensions = { {1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}, };
But we can actually take this idea even further by creating a three dimensional array! This would be an array of 2D arrays. You would build it like this:
int[][][] threeDimensions = { { {1, 2, 3}, {4, 5, 6} }, { {-1, -2, -3}, {-4, -5. -61}, } };
Although this idea is tricky to conceptualize, try to imagine a database that has three axes, with cells that move in each direction.
So that is how you create an array in Java! While many people reading this will never need to concern themselves with three-dimensional arrays, it just goes to show how powerful and adaptable Java really is.
In fact, the list of things you can accomplish with Java is limitless. As is the Array List. Why not continue your education with one of the best resources to learn Java?
source https://www.androidauthority.com/how-to-create-an-array-in-java-1151277/
0 notes
codippa · 4 years
Text
Java 8 consumer example
Consumer is an interface added in java 8. It is a Functional interface with a single method accept() which takes an argument and returns no value, that is, its return type is void. Thus, this method consumes a value and hence the name of the interface. Consumer behaves just opposite to java 8 Supplier interface which takes no argument and returns a value. Signature of accept() method is void accept(T t); where T is the generic type. Creating Consumer Since Consumer is a Functional interface, it can be represented as a Lambda expression which matches the signature of accept() method as shown below. Consumer consumer = (str) -> System.out.println(str); Here, the expression to the right is a Lambda expression which takes a single argument and returns nothing. There is another primitive way of creating a Consumer as well. Since Consumer is an interface, you can not create its object directly but as an anonymous inner class as shown below. Consumer c = new Consumer() { @Override public void accept(String arg) { System.out.println(arg); } }; Clearly, the primitive approach is much lengthier as compared to Lambda expression. Invoking a Consumer Once a Consumer is created, you can invoke it by calling its accept method as shown below. // create a consumer Consumer printer = (str) -> System.err.println(str); // invoke it printer.accept("Hello World!")' try { window._mNHandle.queue.push(function (){ window._mNDetails.loadTag("181322386", "728x90", "181322386"); }); } catch (error) {} Why use Consumer You might ask why should I use Consumer just to print something, I can directly do that. But, there are scenarios where using Consumer is beneficial and required. They are: 1. Many methods in java api expect an object of type Consumer such as forEach method in java.lang.Iterable interface. forEach is a default interface method added in java 8. 2. A Consumer may be used to modify an object supplied to it such as squaring an integer supplied to it. Both these will be covered in the examples below. Consumer interface Example Below program iterates over a list and prints its elements using a Consumer. // create a consumer Consumer printer = (str) -> System.err.println(str); // initialize a list List list = List.of("Learning", "Consumer", "at", "codippa.com"); // iterate the list list.forEach(printer); This example iterates over a list using forEach method and passes a Consumer to it. forEach will invoke the Consumer for each list element and print it to the console. Here is the output Learning Consumer at codippa.com Consumer interface Example 2 As stated above, a Consumer may be used to modify the element supplied to it. Below program creates a Consumer of Integer object and adds 10 to its value. //create a consumer Consumer adder = (num) -> { num += 10; System.out.println(num); }; // invoke consumer adder.accept(50); // prints 60 Chaining Consumers Chaining consumers means combining multiple consumers to produce a required result. Consumer interface contains a method andThen() which expects a Consumer argument and returns a Consumer. This is a default interface method and can be used to chain consumers. Below example creates multiple consumers, where one consumer iterates over a list, capitalizes its elements and another consumer then prints its elements. All this is done using single consumer invocation as shown below. // initialize a list List list = new ArrayList(); // add elements list.add("Learning"); list.add("Consumer"); list.add("at"); list.add("codippa.com"); // create a consumer to iterate list and print Consumer printer = (items) -> items. forEach(item -> System.out.println(item)); // create a consumer to capitalize its elements Consumer capitalizer = (items) -> { for (int i = 0; i UnsupportedOperationException while modifying list elements as below Exception in thread "main" java.lang.UnsupportedOperationException at java.base/java.util.ImmutableCollections.uoe(ImmutableCollections.java:73) If you look at the source of andThen() method, it is default Consumer andThen(Consumer Read the full article
0 notes
rafi1228 · 4 years
Link
Start Learning Java Programming Step By Step with 200+ code examples. 250 Amazing Steps For Absolute Java Beginners!
What you’ll learn
You will Learn Java the MODERN WAY – Step By Step – With 200 HANDS-ON Code Examples
You will Understand the BEST PRACTICES in Writing High Quality Java Code
You will Solve a Wide Range of Hands-on Programming EXERCISES with Java
You will Learn to Write AWESOME Object Oriented Programs with Java
You will Acquire ALL the SKILLS to demonstrate an EXPERTISE with Java Programming in Your Job Interviews
You will learn ADVANCED Object Oriented Programming Concepts – Abstraction, Inheritance, Encapsulation and Polymorphism
You will learn the Basics of Object Oriented Programming – Interfaces, Inheritance, Abstract Class and Constructors
You will learn the Basics of Programming – variables, choosing a data type, conditional execution, loops, writing great methods, breaking down problems into sub problems and implementing great Exception Handling
You will learn Basics of Functional Programming with Java
You will gain Expertise in using Eclipse IDE and JShell
You will learn the basics of MultiThreaded Programming – with Executor Service
You will learn about a wide variety of Java Collections – List, Map, Set and Queue Interfaces
Requirements
You have an attitude to learn while having fun 🙂
You have ZERO Programming Experience and Want to Learn Java
Description
Zero Java Programming Experience? No Problem.
Do you want to take the first steps to Become a Great Java Programmer? Do you want to Learn Java Step By Step in a Fail Safe in28Minutes Way? Do you want to Learn to Write Great Java Programs?
******* Some Amazing Reviews From Our Learners *******
★★★★★ it’s an awesome course , i was a complete beginner and it helped me a lot. One of the best courses i have every taken on Udemy.
★★★★★ This is the best Java course I’ve come across. It’s straight to the point without any missing details. You can get an idea of what you’re getting into working with Java fast with this course. I really like it.
★★★★★ The experienece was extremely amazing. The course was highly detailed and comprehensive and all the topic were covered properly with due examples to their credit. The instructor is passionateabout what he is doing and hence it makes the course much more worth to learn. Kudos to the instructor for such an amazing job.
★★★★★ Never thought taking an online course will be so helpful. The instructor is quite engaging, gives good amount of exercises.
★★★★★ This course is wonderful! I really enjoy it. It really is for beginners, so it’s very helpful for people which don’t know nothing about programming.
★★★★★ Very comprehensive and detail course the instructor takes the patience to explain everything and goes a step forward in thinking what kind of errors could happen to the students really good instructor!
★★★★★ It’s very well thought out. I enjoy the constant exercises and the challenge they present to make things happen.
******* Course Overview *******
Java is one of the most popular programming languages. Java offers both object oriented and functional programming features.
We take an hands-on approach using a combination of JShell and Eclipse as an IDE to illustrate more than 200 Java Coding Exercises, Puzzles and Code Examples. This course assumes no previous ( beginner ) programming or Java experience. If you’ve never programmed a computer before, or if you already have experience with another programming language and want to quickly learn Java, this is a perfect course for you.
In more than 250 Steps, we explore the most important Java Programming Language Features
Basics of Java Programming – Expressions, Variables and Printing Output
Java Operators – Java Assignment Operator, Relational and Logical Operators, Short Circuit Operators
Java Conditionals and If Statement
Methods – Parameters, Arguments and Return Values
Object Oriented Programming – Class, Object, State and Behavior
Basics of OOPS – Encapsulation, Abstraction, Inheritance and Polymorphism
Basics about Java Data Types – Casting, Operators and More
Java Built in Classes – BigDecimal, String, Java Wrapper Classes
Conditionals with Java – If Else Statement, Nested If Else, Java Switch Statement, Java Ternary Operator
Loops – For Loop, While Loop in Java, Do While Loop, Break and Continue
Immutablity of Java Wrapper Classes, String and BigDecimal
Java Dates – Introduction to LocalDate, LocalTime and LocalDateTime
Java Array and ArrayList – Java String Arrays, Arrays of Objects, Primitive Data Types, toString and Exceptions
Introduction to Variable Arguments
Basics of Designing a Class – Class, Object, State and Behavior. Deciding State and Constructors.
Understanding Object Composition and Inheritance
Java Abstract Class and Interfaces. Introduction to Polymorphism.
Java Collections – List Interface(ArrayList, LinkedList and Vector), Set Interface (HashSet, LinkedHashSet and TreeSet), Queue Interface (PriorityQueue) and Map Interface (HashMap, HashTable, LinkedHashMap and TreeMap() – Compare, Contrast and Choose
Generics – Why do we need Generics? Restrictions with extends and Generic Methods, WildCards – Upper Bound and Lower Bound.
Functional Programming – Lambda Expression, Stream and Operations on a Stream (Intermediate Operations – Sort, Distinct, Filter, Map and Terminal Operations – max, min, collect to List), Functional Interfaces – Predicate Interface,Consumer Interface, Function Inteface for Mapping, Method References – static and instance methods
Introduction to Threads and MultiThreading – Need for Threads
Implementing Threads – Extending Thread Class and Implementing Runnable Interface
States of a Thread and Communication between Threads
Introduction to Executor Service – Customizing number of Active Threads. Returning a Future, invokeAll and invokeAny
Introduction to Exception Handling – Your Thought Process during Exception Handling. try, catch and finally. Exception Hierarchy – Checked Exceptions vs Unchecked Exceptions. Throwing an Exception. Creating and Throwing a Custom Exception – CurrenciesDoNotMatchException. Try with Resources – New Feature in Java 7.
List files and folders in Directory with Files list method, File walk method and find methods. Read and write from a File.
******* What You Can Expect from Every in28Minutes Course *******
in28Minutes created 20 Best Selling Courses providing Amazing Learning Experiences to 250,000 Learners across the world.
Each of these courses come with
✔ Amazing Hands-on Step By Step Learning Experiences
✔ Real Project Experiences using the Best Tools and Frameworks
✔ Awesome Troubleshooting Guides with 200+ FAQs Answered
✔ Friendly Support in the Q&A section
✔ Free Udemy Certificate of Completion on Completion of Course
✔ 30 Day “No Questions Asked” Money Back Guarantee!
~~~ Here are a Few Reviews on The in28Minutes Way ~~~
★★★★★ Excellent, fabulous. The way he has prepared the material and the way he teaches is really awesome. What an effort .. Thanks a million
★★★★★ A lot of preparation work has taken place from the teacher and this is visible throughout the course.
★★★★★ This guy is fantastic. Really. Wonderful teaching skills, and goes well out of his way to make sure that everything he is doing is fully understood. This is the kind of tutorial that gets me excited to work with a framework that I may otherwise not be.
★★★★★ The best part of it is the hands-on approach which the author maintained throughout the course as he had promised at the beginning of the lecture. He explains the concepts really well and also makes sure that there is not a single line of code you type without understanding what it really does.
★★★★★ I also appreciate the mind and hands approach of teaching something and then having the student apply it. It makes everything a lot clearer for the student and uncovers issues that we will face in our project early.
★★★★★ Amazing course. Explained super difficult concepts (that I have spent hours on the internet finding a good explanation) in under 5 minutes.
Zero risk. 30 day money-back guarantee with every purchase of the course. You have nothing to lose!
Start Learning Now. Hit the Enroll Button!
******* Step By Step Details *******
Introduction to Java Programming with Jshell using Multiplication Table
Step 00 – Getting Started with Programming Step 01 – Introduction to Multiplication Table challenge Step 02 – Launch JShell Step 03 – Break Down Multiplication Table Challenge Step 04 – Java Expression – An Introduction Step 05 – Java Expression – Exercises Step 06 – Java Expression – Puzzles Step 07 – Printing output to console with Java Step 08 – Printing output to console with Java – Exercise Statements Step 09 – Printing output to console with Java – Exercise Solutions Step 10 – Printing output to console with Java – Puzzles Step 11 – Advanced Printing output to console with Java Step 12 – Advanced Printing output to console with Java – Exercises and Puzzles Step 13 – Introduction to Variables in Java Step 14 – Introduction to Variables in Java – Exercises and Puzzles Step 15 – 4 Important Things to Know about Variables in Java Step 16 – How are variables stored in memory? Step 17 – How to name a variable? Step 18 – Understanding Primitive Variable Types in Java Step 19 – Understanding Primitive Variable Types in Java – Choosing a Type Step 20 – Java Assignment Operator Step 21 – Java Assignment Operator – Puzzles on Increment, Decrement and Compound Assignment Step 23 – Java Conditionals and If Statement – Introduction Step 24 – Java Conditionals and If Statement – Exercise Statements Step 25 – Java Conditionals and If Statement – Exercise Solutions Step 26 – Java Conditionals and If Statement – Puzzles Step 27 – Java For Loop to Print Multiplication Table – Introduction Step 28 – Java For Loop to Print Multiplication Table – Exercise Statements Step 29 – Java For Loop to Print Multiplication Table – Exercise Solutions Step 30 – Java For Loop to Print Multiplication Table – Puzzles Step 31 – Programming Tips : JShell – Shortcuts, Multiple Lines and Variables TODO Move up Step 32 – Getting Started with Programming – Revise all Terminology
Introduction to Method with Multiplication Table
Step 00 – Section 02 – Methods – An Introduction Step 01 – Your First Java Method – Hello World Twice and Exercise Statements Step 02 – Introduction to Java Methods – Exercises and Puzzles Step 03 – Programming Tip – Editing Methods with JShell Step 04 – Introduction to Java Methods – Arguments and Parameters Step 05 – Introduction to Java Method Arguments – Exercises Step 06 – Introduction to Java Method Arguments – Puzzles and Tips Step 07 – Getting back to Multiplication Table – Creating a method Step 08 – Print Multiplication Table with a Parameter and Method Overloading Step 09 – Passing Multiple Parameters to a Java Method Step 10 – Returning from a Java Method – An Introduction Step 11 – Returning from a Java Method – Exercises Step 99 – Methods – Section Review
Introduction to Java Platform
Step 00 – Section 03 – Overview Of Java Platform – Section Overview Step 01 – Overview Of Java Platform – An Introduction – java, javac, bytecode and JVM Step 02 – Java Class and Object – First Look Step 03 – Create a method in a Java class Step 04 – Create and Compile Planet.java class Step 05 – Run Planet calss with Java – Using a main method Step 06 – Play and Learn with Planet Class Step 07 – JDK vs JRE vs JVM
Introduction to Eclipse – First Java Project
Step 01 – Creating a New Java Project with Eclipse Step 02 – Your first Java class with Eclipse Step 03 – Writing Multiplication Table Java Program with Eclipse Step 04 – Adding more methods for Multiplication Table Program Step 05 – Programming Tip 1 : Refactoring with Eclipse Step 06 – Programming Tip 2 : Debugging with Eclipse Step 07 – Programming Tip 3 : Eclipse vs JShell – How to choose?
Introduction To Object Oriented Programming
Step 00 – Introduction to Object Oriented Programming – Section Overview Step 01 – Introduction to Object Oriented Programming – Basics Step 02 – Introduction to Object Oriented Programming – Terminology – Class, Object, State and Behavior Step 03 – Introduction to Object Oriented Programming – Exercise – Online Shopping System and Person Step 04 – Create Motor Bike Java Class and a couple of objects Step 05 – Exercise Solutions – Book class and Three instances Step 06 – Introducing State of an object with speed variable Step 07 – Understanding basics of Encapsulation with Setter methods Step 08 – Exercises and Tips – Getters and Generating Getters and Setters with Eclipse Step 09 – Puzzles on this and initialization of member variables Step 10 – First Advantage of Encapsulation Step 11 – Introduction to Encapsulation – Level 2 Step 12 – Encapsulation Exercises – Better Validation and Book class Step 13 – Introdcution to Abstraction Step 14 – Introduction to Java Constructors Step 15 – Introduction to Java Constructors – Exercises and Puzzles Step 16 – Introduction to Object Oriented Programming – Conclusion
Primitive Data Types And Alternatives
Step 00 – Primitive Data Types in Depth – Section Overview Step 01 – Basics about Java Integer Data Types – Casting, Operators and More Step 02 – Java Integer Data Types – Puzzles – Octal, Hexadecimal, Post and Pre increment Step 03 – Java Integer Data Types – Exercises – BiNumber – add, multiply and double Step 04 – Java Floating Point Data Types – Casting , Conversion and Accuracy Step 05 – Introduction to BigDecimal Java Class Step 06 – BigDecimal Puzzles – Adding Integers Step 07 – BigDecimal Exercises – Simple Interest Calculation Step 08 – Java Boolean Data Type – Relational and Logical Operators Step 09 – Java Boolean Data Type – Puzzles – Short Circuit Operators Step 10 – Java Character Data Type char – Representation and Conversion Step 11 – Java char Data Type – Exercises 1 – isVowel Step 12 – Java char Data Type – Exercises 2 – isDigit Step 13 – Java char Data Type – Exercises 3 – isConsonant, List Upper Case and Lower Case Characters Step 14 – Primitive Data Types in Depth – Conclusion
Conditionals
Step 00 – Conditionals with Java – Section Overview Step 01 – Introduction to If Else Statement Step 02 – Introduction to Nested If Else Step 03 – If Else Statement – Puzzles Step 04 – If Else Problem – How to get User Input in Java? Step 05 – If Else Problem – How to get number 2 and choice from user? Step 06 – If Else Problem – Implementing with Nested If Else Step 07 – Java Switch Statement – An introduction Step 08 – Java Switch Statement – Puzzles – Default, Break and Fall Through Step 09 – Java Switch Statement – Exercises – isWeekDay, nameOfMonth, nameOfDay Step 10 – Java Ternary Operation – An Introduction Step 11 – Conditionals with Java – Conclusion
Loops
Step 00 – Java Loops – Section Introduction Step 01 – Java For Loop – Syntax and Puzzles Step 02 – Java For Loop – Exercises Overview and First Exercise Prime Numbers Step 03 – Java For Loop – Exercise – Sum Upto N Numbers and Sum of Divisors Step 04 – Java For Loop – Exercise – Print a Number Triangle Step 05 – While Loop in Java – An Introduction Step 06 – While Loop – Exericises – Cubes and Squares upto limit Step 07 – Do While Loop in Java – An Introduction Step 08 – Do While Loop in Java – An Example – Cube while user enters positive numbers Step 09 – Introduction to Break and Continue Step 10 – Selecting Loop in Java – For vs While vs Do While
Reference Types
Step 00 – Java Reference Types – Section Introduction Step 01 – Reference Types – How are they stored in Memory? Step 02 – Java Reference Types – Puzzles Step 03 – String class – Introduction and Exercise – Print each word and char on a new line Step 04 – String class – Exercise Solution and Some More Important Methods Step 05 – Understanding String is Immutable and String Concat, Upper Case, Lower Case, Trim methods Step 06 – String Concatenation and Join, Replace Methods Step 07 – Java String Alternatives – StringBuffer and StringBuilder Step 08 – Java Wrapper Classes – An Introduction – Why and What? Step 09 – Java Wrapper Classes – Creation – Constructor and valueOf Step 10 – Java Wrapper Classes – Auto Boxing and a Few Wrapper Constants – SIZE, BYTES, MAX_VALUE and MIN_VALUE Step 11 – Java Dates – Introduction to LocalDate, LocalTime and LocalDateTime Step 12 – Java Dates – Exploring LocalDate – Creation and Methods to play with Date Step 13 – Java Dates – Exploring LocalDate – Comparing Dates and Creating Specific Dates Step 14 – Java Reference Types – Conclusion
Arrays and ArrayLists
Step 00 – Introduction to Array and ArrayList – Section Introduction with a Challenge Step 01 – Understanding the need and Basics about an Array Step 02 – Java Arrays – Creating and Accessing Values – Introduction Step 03 – Java Arrays – Puzzles – Arrays of Objects, Primitive Data Types, toString and Exceptions Step 04 – Java Arrays – Compare, Sort and Fill Step 05 – Java Arrays – Exercise – Create Student Class – Part 1 – Total and Average Marks Step 06 – Java Arrays – Exercise – Create Student Class – Part 2 – Maximum and Minimum Mark Step 07 – Introduction to Variable Arguments – Need Step 08 – Introduction to Variable Arguments – Basics Step 09 – Introduction to Variable Arguments – Enhancing Student Class Step 10 – Java Arrays – Using Person Objects and String Elements with Exercises Step 11 – Java String Arrays – Exercise Solutions – Print Day of Week with Most number of letters and more Step 12 – Adding and Removing Marks – Problem with Arrays Step 13 – First Look at ArrayList – An Introduction Step 14 – First Look at ArrayList – Refactoring Student Class to use ArrayList Step 15 – First Look at ArrayList – Enhancing Student Class with Add and Remove Marks Step 16 – Introduction to Array and ArrayList – Conclusion
Object Oriented Programming Again
Step 00 – Object Oriented Programming – Level 2 – Section Introduction Step 01 – Basics of Designing a Class – Class, Object, State and Behavior Step 02 – OOPS Example – Fan Class – Deciding State and Constructors Step 03 – OOPS Example – Fan Class – Deciding Behavior with Methods Step 04 – OOPS Exercise – Rectangle Class Step 05 – Understanding Object Composition with Customer Address Example Step 06 – Understanding Object Composition – An Exercise – Books and Reviews Step 07 – Understanding Inheritance – Why do we need it? Step 08 – Object is at top of Inheritance Hierarchy Step 09 – Inheritance and Overriding – with toString() method Step 10 – Java Inheritance – Exercise – Student and Employee Classes Step 11 – Java Inheritance – Default Constructors and super() method call Step 12 – Java Inheritance – Puzzles – Multiple Inheritance, Reference Variables and instanceof Step 13 – Java Abstract Class – Introductio Step 14 – Java Abstract Class – First Example – Creating Recipes with Template Method Step 15 – Java Abstract Class – Puzzles Step 16 – Java Interface – Example 1 – Gaming Console – How to think about Intefaces? Step 17 – Java Interface – Example 2 – Complex Algorithm – API defined by external team Step 18 – Java Interface – Puzzles – Unimplemented methods, Abstract Classes, Variables, Default Methods and more Step 19 – Java Interface vs Abstract Class – A Comparison Step 20 – Java Interface Flyable and Abstract Class Animal – An Exercise Step 21 – Polymorphism – An introduction
Collections
Step 01 – Java Collections – Section Overview with Need For Collections Step 02 – List Interface – Introduction – Position is King Step 03 – List Inteface – Immutability and Introduction of Implementations – ArrayList, LinkedList and Vector Step 04 – List Inteface Implementations – ArrayList vs LinkedList Step 05 – List Inteface Implementations – ArrayList vs Vector Step 06 – List Inteface – Methods to add, remove and change elements and lists Step 07 – List and ArrayList – Iterating around elements Step 08 – List and ArrayList – Choosing iteration approach for printing and deleting elements Step 09 – List and ArrayList – Puzzles – Type Safety and Removing Integers Step 10 – List and ArrayList – Sorting – Introduction to Collections sort static method Step 11 – List and ArrayList – Sorting – Implementing Comparable Inteface in Student Class Step 12 – List and ArrayList – Sorting – Providing Flexibility by implementing Comparator interface Step 13 – List and ArrayList – A Summary Step 14 – Set Interface – Introduction – No Duplication Step 15 – Understanding Data Structures – Array, LinkedList and Hashing Step 16 – Understanding Data Structures – Tree – Sorted Order Step 17 – Set Interface – Hands on – HashSet, LinkedHashSet and TreeSet Step 18 – Set Interface – Exercise – Find Unique Characters in a List Step 19 – TreeSet – Methods from NavigableSet – floor,lower,upper, subSet, head and tailSet Step 20 – Queue Interface – Process Elements in Order Step 21 – Introduction to PriorityQueue – Basic Methods and Customized Priority Step 22 – Map Interface – An Introduction – Key and Value Step 23 – Map Interface – Implementations – HashMap, HashTable, LinkedHashMap and TreeMap Step 24 – Map Interface – Basic Operations Step 25 – Map Interface – Comparison – HashMap vs LinkedHashMap vs TreeMap Step 26 – Map Interface – Exercise – Count occurances of characters and words in a piece of text Step 27 – TreeMap – Methods from NavigableMap – floorKey, higherKey, firstEntry, subMap and more Step 28 – Java Collections – Conclusion with Three Tips
Generics
Step 01 – Introduction to Generics – Why do we need Generics? Step 02 – Implementing Generics for the Custom List Step 03 – Extending Custom List with a Generic Return Method Step 04 – Generics Puzzles – Restrictions with extends and Generic Methods Step 05 – Generics and WildCards – Upper Bound and Lower Bound
Introduction to Functional Programming
Step 01 – Introduction to Functional Programming – Functions are First Class Citizens Step 02 – Functional Programming – First Example with Function as Parameter Step 03 – Functional Programming – Exercise – Loop a List of Numbers Step 04 – Functional Programming – Filtering – Exercises to print odd and even numbers from List Step 05 – Functional Programming – Collect – Sum of Numbers in a List Step 06 – Functional Programming vs Structural Programming – A Quick Comparison Step 07 – Functional Programming Terminology – Lambda Expression, Stream and Operations on a Stream Step 08 – Stream Intermediate Operations – Sort, Distinct, Filter and Map Step 09 – Stream Intermediate Operations – Exercises – Squares of First 10, Map String List to LowerCase and Length of String Step 10 – Stream Terminal Operations – 1 – max operation with Comparator Step 11 – Stream Terminal Operations – 2 – min, collect to List, Step 12 – Optional class in Java – An Introduction Step 13 – Behind the Screens with Functional Interfaces – Implement Predicate Interface Step 14 – Behind the Screens with Functional Interfaces – Implement Consumer Interface Step 15 – Behind the Screens with Functional Interfaces – Implement Function Inteface for Mapping Step 16 – Simplify Functional Programming code with Method References – static and instance methods Step 17 – Functions are First Class Citizens Step 18 – Introduction to Functional Programming – Conclusion
Introduction to Threads And Concurrency
Step 01 – Introduction to Threads and MultiThreading – Need for Threads Step 02 – Creating a Thread for Task1 – Extending Thread Class Step 03 – Creating a Thread for Task2 – Implement Runnable Interface Step 04 – Theory – States of a Thread Step 05 – Placing Priority Requests for Threads Step 06 – Communication between Threads – join method Step 07 – Thread utility methods and synchronized keyword – sleep, yield Step 08 – Need for Controlling the Execution of Threads Step 09 – Introduction to Executor Service Step 10 – Executor Service – Customizing number of Threads Step 11 – Executor Service – Returning a Future from Thread using Callable Step 12 – Executor Service – Waiting for completion of multiple tasks using invokeAll Step 13 – Executor Service – Wait for only the fastest task using invokeAny Step 14 – Threads and MultiThreading – Conclusion
Introduction to Exception Handling
Step 01 – Introduction to Exception Handling – Your Thought Process during Exception Handling Step 02 – Basics of Exceptions – NullPointerException and StackTrace Step 03 – Basics of Handling Exceptions – try and catch Step 04 – Basics of Handling Exceptions – Exception Hierarchy, Matching and Catching Multiple Exceptions Step 05 – Basics of Handling Exceptions – Need for finally Step 06 – Basics of Handling Exceptions – Puzzles Step 07 – Checked Exceptions vs Unchecked Exceptions – An Example Step 08 – Hierarchy of Errors and Exceptions – Checked and Runtime Step 09 – Throwing an Exception – Currencies Do Not Match Runtime Exception Step 10 – Throwing a Checked Exception – Throws in method signature and handling Step 11 – Throwing a Custom Exception – CurrenciesDoNotMatchException Step 12 – Write less code with Try with Resources – New Feature in Java 7 Step 13 – Basics of Handling Exceptions – Puzzles 2 Step 14 – Exception Handling – Conclusion with Best Practices
Files and Directories
Step 01 – List files and folders in Directory with Files list method Step 02 – Recursively List and Filter all files and folders in Directory with Step Files walk method and Search with find method Step 03 – Read content from a File – Files readAllLines and lines methods Step 04 – Writing Content to a File – Files write method Step 05 – Files – Conclusion
More Concurrency with Concurrent Collections and Atomic Operations
Step 01 – Getting started with Synchronized Step 02 – Problem with Synchronized – Less Concurrency Step 03 – Enter Locks with ReEntrantLock Step 04 – Introduction to Atomic Classes – AtomicInteger Step 05 – Need for ConcurrentMap Step 06 – Implementing an example with ConcurrentHashMap Step 07 – ConcurrentHashMap uses different locks for diferrent regions Step 08 – CopyOnWrite Concurrent Collections – When reads are more than writes Step 09 – Conclusion
Java Tips
Java Tip 01 – Imports and Static Imports Java Tip 02 – Blocks Java Tip 03 – equals method Java Tip 04 – hashcode method Java Tip 05 – Class Access Modifiers – public and default Java Tip 06 – Method Access Modifiers – public, protected, private and default Java Tip 07 – Final classes and Final methods Java Tip 08 – Final Variables and Final Arguments Java Tip 09 – Why do we need static variables? Java Tip 09 – Why do we need static methods? Java Tip 10 – Static methods cannot use instance methods or variables Java Tip 11 – public static final – Constants Java Tip 12 – Nested Classes – Inner Class vs Static Nested Class Java Tip 13 – Anonymous Classes Java Tip 14 – Why Enum and Enum Basics – ordinal and values Java Tip 15 – Enum – Constructor, variables and methods Java Tip 16 – Quick look at inbuild Enums – Month, DayOfWeek
Zero risk. 30 day money-back guarantee with every purchase of the course. You have nothing to lose!
Start Learning Now. Hit the Enroll Button!
Who this course is for:
You have ZERO programming experience and want to learn Java Programming
You are a Beginner at Java Programming and want to Learn to write Great Java Programs
You want to learn the Basics of Object Oriented Programming with Java
You want to learn the Basics of Functional Programming with Java
Created by in28Minutes Official Last updated 1/2019 English English [Auto-generated]
Size: 2.80 GB
   Download Now
https://ift.tt/2A4bRbM.
The post Java Programming for Complete Beginners – Learn in 250 Steps appeared first on Free Course Lab.
0 notes
openwebsolutions · 5 years
Text
How to use Lambda expression in Java 8
New Post has been published on http://blog.openwebsolutions.in/use-lambda-expression-java-8/
How to use Lambda expression in Java 8
Lambda Expression in Java 8- Lambda expression basically expresses instances of functional interfaces. Lambda expression is a new feature of Java 8. It adds more functionalities like treat functionality as a method with arguments, a function can be created without belonging to any class. The lambda expression is containing two parts the one on the left of the arrow symbol (->) having its parameters and the one on the right containing its body of this function. Syntax: lambda operator -> body Zero parameter: () -> System.out.println(“Zero parameter lambda”); One parameter:– (p) -> System.out.println(“One parameter: ” + p); Multiple parameters : (parameter1, parameter2) -> System.out.println(” parameters : ” + parameter1 + “, ” + parameter2); // A Java program to demonstrate lambda expressions import java.util.ArrayList; class Test public static void main(String args[]) // Creating an ArrayList with integer elements // 1, 2, 3, 4 ArrayList<Integer> integerArr = new ArrayList<Integer>(); integerArr.add(1); integerArr.add(2); integerArr.add(3); integerArr.add(4);
// Using lambda expression to print all elements // of integerArr integerArr.forEach(num -> System.out.println(num));
// Using lambda expression to print even elements // of integerArr integerArr.forEach(n -> if (num%2 == 0) System.out.println(num); );
// Java program to demonstrate working of lambda expressions using interface and argument public class Example // operation is implemented using lambda expressions interface InterfaceFirst int result(int a, int b);
// welcomeMessage() is implemented using lambda expressions // above interface InterfaceSecond void welcomeMessage(String message);
// Performs InterfaceFirst’s operation on ‘a’ and ‘b’ private int operate(int a, int b, InterfaceFirst fobj) return fobj.result(a, b);
public static void main(String args[]) // lambda expression for addition for two parameters // This expression implements ‘InterfaceFirst’ interface InterfaceFirst add = (int x, int y) -> x + y;
// lambda expression multiplication for two parameters // This expression also implements ‘InterfaceFirst’ interface InterfaceFirst mul = (int x, int y) -> x * y;
// Creating an object of Example to call operate using // different implementations using lambda Expressions Example testObj = new Example();
// Add two numbers using lambda expression System.out.println(“Addition is ” + testObj.result(6, 3, add));
// Multiply two numbers using lambda expression System.out.println(“Multiplication is ” + testObj.result(6, 3, mul));
// lambda expression for single parameter // This expression implements ‘FuncInter2’ interface InterfaceSecond sobj = message ->System.out.println(“Welcome ” + message); sobj.welcomeMessage(“Java”);
0 notes