0% found this document useful (0 votes)
5 views

Java 1

The document provides a comprehensive overview of Java concepts, including JVM, JRE, JDK, and comparisons with other programming languages like C and C++. It covers Java features, exception handling, multithreading, functional programming, and the Java Collections Framework, along with Spring Framework concepts such as Dependency Injection and Aspect-Oriented Programming. Additionally, it discusses various Java keywords, data types, operators, and the usage of lambda expressions and method references.

Uploaded by

vg0687734
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
5 views

Java 1

The document provides a comprehensive overview of Java concepts, including JVM, JRE, JDK, and comparisons with other programming languages like C and C++. It covers Java features, exception handling, multithreading, functional programming, and the Java Collections Framework, along with Spring Framework concepts such as Dependency Injection and Aspect-Oriented Programming. Additionally, it discusses various Java keywords, data types, operators, and the usage of lambda expressions and method references.

Uploaded by

vg0687734
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 23
Unit 1 1A. Discuss JVM. JVM (Java Virtual Machine) is an engine that provides a runtime environment to execute Java bytecode. It is part of the JRE and converts compiled Java bytecode into machine code depending on the underlying operating system. 1B. Discuss JRE and JDK. JRE (Java Runtime Environment): Contains JVM and Java class libraries. It is used to run Java programs. JDK (Java Development Kit): Contains JRE plus development tools like compiler (javac), debugger, etc. It is used to develop Java programs. 1C. Compare C and Java. Feature C Java Programming Paradigm Procedural Object-Oriented Platform Dependency Platform-dependent Platform- independent Memory Management Manual Automatic (Garbage Collector) Pointers Supported Not supported directly 1D. Compare C++ and Java. Feature C++ Java Inheritance Multiple inheritance supported Only through interfaces Memory Management Manual Automatic Platform Platform-dependent Platform-independent Templates Supported Uses Generics instead 1E. Discuss Bytecode. Also need of Byte code. Bytecode is an intermediate code generated after compilation of Java source code (.java) into .class files. It is platform-independent and executed by the JVM. Need: Bytecode enables Java programs to be "write once, run anywhere." 1F. What do you mean by platform independent and architecture neutral? Platform Independent: Java code can run on any platform with JVM. Architecture Neutral: Java bytecode is not tied to any processor architecture, making it portable across systems. 1G. State feature of Java. Simple Object-Oriented Platform Independent Secure Robust Multithreaded High Performance Distributed Dynamic 1H. State history of Java programming language. Developed by James Gosling at Sun Microsystems in 1991. Originally called Oak, later renamed Java. Released publicly in 1995. Now owned by Oracle Corporation. 1|. State the applications of Java programming language. Desktop Applications Web Applications Enterprise Applications (Banking, ERP) Mobile Applications (Android) Scientific Applications Embedded Systems Games Development 1J. Compare J2SE, J2EE and J2ME. Version Use J2SE Java Standard Edition — Core functionality (desktop apps, utilities) J2EE Java Enterprise Edition - Enterprise-level applications (web, servers) J2ME Java Micro Edition - Embedded and mobile devices 1K. Differentiate between “path” and “classpath”. Term Description Path Tells the OS where to find Java binaries (e.g., javac, java) Classpath Tells JVM where to find user-defined classes and packages 1L. Differentiate between “javac” and “java” commands. Command Function javac Compiles .java files to .class bytecode java Runs the .class file using JVM 1M. Discuss datatype. Enlist all 8 primitive datatypes available in Java. Datatypes define the type of data a variable can hold. Primitive Datatypes: 1. byte 2. short 3. int 4. long 5. float 6. double 7. char 8. boolean 1N. Write a short note on following keywords: i) static: Belongs to the class, not instances. Shared across all objects. ii) abstract: Used to declare a method or class without implementation. iii) final: Used to declare constants or prevent inheritance/ method overriding. 10. Differentiate between “this” and “super” keyword. Give example of both. this: Refers to current class object. super: Refers to parent class object. Example: class A { int a = 10; } class B extends A { int a = 20; void show() { System.out.printIn(this.a); // 20 System.out.printIn(super.a); // 10 } } 1P. Describe the role of an operator in performing an operation. Enlist all types of operators available in Java. Operators perform operations on variables and values. Types of Operators: 1. Arithmetic (+, -, *, /, %) 2. Relational (==, !=, <, >, <=, >=) 3. Logical (&8&, |I, !) 4. Bitwise (8 |, *, ~, <<, >>) 5. Assignment (=, +=, -=, etc.) 6. Unary (+, -, ++, —) 7. Ternary (?:) 8. instanceof 1Q. Differentiate between “extends” and “implements” keyword. Give example of both. extends: Used for class inheritance. implements: Used to implement interfaces. Example: class A {} class B extends A {} interface C class D implements C 1R. Discuss package? How to use a package in a java program? Demonstrate the process of creating a package. A package is a namespace that organizes classes and interfaces. Steps to create a package: 1. Declare package: package mypack; 2. Save class in a directory with package name. 3. Compile: javac -d . MyClass.java 4. Use: import mypack.MyClass; 1S. Discuss array? Give syntax to define an array. Create an array of type char of size 100. An array is a collection of similar data types stored in contiguous memory. Syntax: char[] arr = new char[100]; 1T. What do you mean by static import? Static import allows access to static members of a class without using the class name. Example: import static java.lang.Math.*; System.out.printIn(sqrt(16)); // instead of Math.sqrt(16) Unit. 2 A. Discuss Exception? An exception is an event that disrupts the normal flow of a program's execution. It is an object which is thrown at runtime and can be handled using try-catch blocks. B. Discuss Exception handling? Exception handling is the process of responding to the occurrence of exceptions during program execution using try, catch, finally, and throw/throws. C. Discuss multithreading in Java? Multithreading is a feature that allows concurrent execution of two or more parts of a program to maximize CPU usage. Each part is called a thread. D. Discuss various ways to achieve multithreading achieved in Java? Multithreading can be achieved by: 1. Extending the Thread class 2. Implementing the Runnable interface E. Discuss the advantages of multithreading? Efficient CPU utilization Simultaneous task execution Better resource sharing Reduced response time F. Discuss Thread in Java? A thread is a lightweight process and smallest unit of CPU execution. Java provides the Thread class and Runnable interface to implement threads. G. Write down the steps to create a thread in Java? 1. Extend Thread or implement Runnable 2. Override run() method 3. Create object of class 4. Call start() method H. Explain the life cycle of a thread in Java. 1. New 2. Runnable 3. Running 4. Blocked/Waiting 5. Terminated |. Explain synchronization in Java multithreading? Synchronization ensures that only one thread accesses a shared resource at a time to prevent data inconsistency. J. Explain the difference between checked and unchecked exceptions in Java. Checked: Checked at compile-time (e.g., |OException) Unchecked: Checked at runtime (e.g., NullPointerException) K. Discuss the purpose of the try-catch block in Java exception handling? It is used to catch exceptions and handle them gracefully to avoid program termination. L. Discuss the purpose of the finally block in Java exception handling? The finally block contains code that is always executed after try-catch, whether an exception is thrown or not. M. Explain the difference between the throw and throws keywords in Java. throw: Used to explicitly throw an exception throws: Declares exceptions that a method might throw N. Write down the steps to define custom exceptions in Java? 1. Create a class extending Exception or RuntimeException 2. Define constructors 3. Throw it using throw new CustomException() O. What is the default priority of a thread in Java? The default priority is 5 (NORM_PRIORITY). P. Discuss the procedure to set the priority of a thread in Java? Use setPriority(int priority) method on a thread object. Value ranges from 1 (MIN) to 10 (MAX). Q. State the primary classes used for handling input and output operations in Java? InputStream, OutputStream Reader, Writer Scanner FileReader, FileWriter R. Explain the purpose of System.out.println() and System.out.print() methods. printIn() prints data and moves to the next line print() prints data without moving to the next line S. Explain the significance of the java.util.Scanner class in input operations. It is used to parse primitive types and strings using regular expressions from keyboard input or file. T. Enlist various methods of Scanner class to accept runtime input values in Java. next(), nextLine() nextint(), nextDouble(), nextBoolean() nextFloat(), nextLong() Unit 3 A. Explain what a functional interface is in Java. Give an example. A functional interface has only one abstract method. It can have multiple default or static methods. Example: @Functionalinterface interface MyFunctionalinterface { void show(); } B. Define a lambda expression in Java. Provide an example of its usage. Lambda expressions provide a clear and concise way to implement a method of a functional interface. Example: MyFunctionallnterface f = () -> System.out.printIn("Hello Lambda!’); f.show(); C. Discuss the benefits of using lambda expressions over anonymous classes. Less code Better readability Functional programming support Enables use with Stream API D. Discuss method references in Java? Give examples of different types of method references. Method references are shortcuts to call methods using :: operator. Types: 1. Static: ClassName::staticMethod 2. Instance: object::instanceMethod 3. Constructor: ClassName::new E. Explain the syntax and usage of method references in Java. Syntax: List list = Arrays.asList("a’, "b", "c"); list.forEach(System.out::printIn); F. Discuss Stream API in Java? How does it differ from collections? Stream API processes data in a functional style. Unlike collections, streams don't store data but operate on data. Key difference: Collections are for storing data, Streams are for processing data. G. Describe common operations that can be performed using the Stream API. map(), filter(), reduce() collect(), forEach() sorted(), distinct() H. Give an example of using Stream API to filter a collection. List names = List.of("John", "Jane", "Jack"); names.stream().filter(n -> n.startsWith("J")).forEach(System.out::println); |. Discuss default methods in Java interfaces? When are they used? Default methods allow interfaces to have method implementations. Used for backward compatibility in interfaces. interface Test { default void show() { System.out.printIn("Default Method"); } } J. Discuss the role of static methods in interfaces. Static methods in interfaces provide utility functions. They are not inherited by implementing classes. K. Explain the purpose of Base64 encoding and decoding. Base64 is used to encode binary data (like images) into ASCII string format, especially for email and URL data transmission. L. Provide examples of encoding and decoding a string using Base64 in Java. String original = "Hello’; String encoded = Base64.getEncoder().encodeToString(original.getBytes()); String decoded = new String(Base64.getDecoder().decode(encoded)); M. Discuss the forEach method introduced in Java 8? How is it used? It is used to iterate elements of a collection. Example: list.forEach(System.out::printin); N. Compare the forEach method with traditional loops. forEach is more concise and readable Cannot use break/continue Better for functional programming O. Explain the purpose of the try-with-resources statement in Java? Introduced in Java 7, it ensures automatic closing of resources like FileReader, Scanner etc. P. Give an example of using try-with-resources to automatically close resources like files. try (BufferedReader br = new BufferedReader(new FileReader‘(‘file.txt"))) { System.out.printIn(br.readLine());} Q. Explain the concept of type annotations in Java. Type annotations provide metadata for types (e.g., @NonNull String name). Useful for static analysis and validation. R. Discuss the use of repeating annotations and when they are helpful. Repeating annotations allow applying the same annotation multiple times on a declaration. Example:@Schedule(day="Monday") @Schedule(day="Tuesday") Unit 4 A. Define the Java Collections Framework. The Java Collections Framework is a unified architecture for storing and manipulating collections. It includes interfaces (like List, Set, Queue), implementations (like ArrayList, HashSet), and algorithms (like sorting and searching). B. Explain the purpose of the Collections Framework in Java. Reduces programming effort Increases performance Provides ready-to-use data structures Promotes reusability and consistency C. Discuss the advantages of using collections in Java programming. Dynamic memory allocation Predefined classes and interfaces Algorithms like sort, shuffle, reverse Easy iteration and manipulation D. Describe the hierarchy of the Collection Framework in Java. Root: java.util.Collection Subinterfaces: List, Set, Queue Implementations: ArrayList, LinkedList, HashSet, PriorityQueue, etc. E. Explain the relationships between different interfaces and classes in the hierarchy. Interfaces (e.g., List, Set) are implemented by classes (e.g., ArrayList, HashSet). Some classes extend abstract classes (e.g., AbstractList), which implement interfaces partially. F. Describe the difference between Collection and Collections in Java. Collection: An interface representing a group of objects. Collections: A utility class with static methods (e.g., sort(), reverse()). G. Design a Java method that takes a Collection of strings and returns a list of those strings in uppercase. public List toUpperCaseList(Collection input) { return input.stream().map(String::toUpperCase).collect(Collectors.t oList()); } H. Design a Java program that uses removelf to remove all even numbers from a collection. Collection nums = new ArrayList<>(List.of(1, 2, 3, 4, 5)); nums.removelf(n -> n % 2 == 0); |. Implement a method that uses the Collection interface to find the intersection of two collections. public Collection findintersection(Collection c1, Collection c2) { return c1.stream().filter(c2::contains).collect(Collectors.toSet()); } J. Which interface is part of the collection framework but does not extend the Collection interface? Why? Map does not extend Collection because it stores key-value pairs, not a collection of individual elements. K. Give a difference between LinkedList and ArrayList in Java. ArrayList: Faster for random access, slower for insert/delete LinkedList: Slower for access, faster for insert/delete L. Discuss the critical difference between a list and a set. List: Allows duplicates, maintains order Set: No duplicates, no guaranteed order (unless using LinkedHashSet) M. Discuss the various interfaces used in Java Collections Framework. Collection, List, Set, Queue, Deque, Map, SortedSet, SortedMap, etc. Unit 5 A. Discuss Spring Framework in Java. State the features of Spring Framework. Spring is a powerful, lightweight framework used for enterprise Java development. Features: Dependency Injection (Dl) Aspect-Oriented Programming (AOP) Transaction management MVC framework Security Integration with JDBC and ORM tools B. Discuss IoC (Inversion of Control) Container in Spring Framework. loC Container is the core of the Spring Framework that manages the creation and injection of beans. It uses Dependency Injection to manage objects and their dependencies. C. Explain Dependency Injection. It is a design pattern where the object dependencies are provided externally rather than creating them within the class. Types: Constructor Injection Setter Injection D. Give the difference between constructor and setter injection. Constructor Injection: Dependencies are provided through constructor parameters. Setter Injection: Dependencies are set using public setter methods. E. Explain Aspect-Oriented Programming (AOP)? Explain Spring AOP Features. AOP is a programming paradigm that separates cross- cutting concerns like logging, security, etc. Spring AOP Features: Declarative support Based on proxies Integration with Spring DI F. Give the default scope in Spring, and how does it work? Default scope is singleton — a single instance per Spring container. G. Discuss how does Spring manage singleton beans? Spring creates and caches a single instance of the bean and returns the same instance on every request. H. Discuss how you can explicitly define a bean as a singleton in Spring XML configuration? |. Give the difference between the singleton scope and the prototype scope in Spring. Singleton: One shared bean instance. Prototype: A new bean instance on each request. J. Explain, how can you define a bean as a prototype in Spring XML configuration? K. Explain, what will happen when you request a prototype bean multiple times? Each request returns a new instance of the bean. L. Explain the request scope in Spring, and when is it used? A new bean instance is created per HTTP request. Used in web applications (Spring MVC). M. Explain, how can you define a bean as having request scope in Spring? @Component @Scope(value = WebApplicationContext.SCOPE_REQUEST) N. Discuss the session scope in Spring, and when is it used? A new bean instance is created for each user session. Used for session-related data storage in web apps. O. State the steps to define a bean as having session scope in Spring. @Component @Scope(value = WebApplicationContext.SCOPE_SESSION)

You might also like