0% found this document useful (0 votes)
21 views4 pages

Java Access Modifiers and OOP Concepts

The document provides an overview of various Java concepts, including access modifiers, ArrayList, classes, constructors, and OOP principles such as inheritance, encapsulation, and polymorphism. It also explains keywords like 'static', 'final', 'this', and 'super', along with exception handling, collections, and data structures like HashMap and HashSet. Additionally, it includes Java programming examples for sorting arrays, reversing strings, and finding duplicates.

Uploaded by

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

Java Access Modifiers and OOP Concepts

The document provides an overview of various Java concepts, including access modifiers, ArrayList, classes, constructors, and OOP principles such as inheritance, encapsulation, and polymorphism. It also explains keywords like 'static', 'final', 'this', and 'super', along with exception handling, collections, and data structures like HashMap and HashSet. Additionally, it includes Java programming examples for sorting arrays, reversing strings, and finding duplicates.

Uploaded by

suresh
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

What are the Access Modifiers in Java? What is Java Arraylist?

1. Access modifiers in Java help to restrict the scope of a 1. The ArrayList class is a resizable array, which can be
class, constructor, variable, method, or data member. found in the [Link] package.
2. Types of Access Modifiers: Default, Private, Protected 2. ArrayList<String> cars = new ArrayList<String>();
and Public. 3. Sort an arraylist: [Link](arraylist name);

What are the various types of Classes in Java? What is a Java Constructor?

1. Static, Final, Abstract, Concrete and Singleton Class. 1. A constructor in Java is a special method that is used to
initialize objects.
What is Singleton Class in Java? 2. The constructor’s name must match the class name and
1. In object-oriented programming, a singleton class is a class cannot have a return type (like void).
that can have only one object (an instance of the class) at a 3. The constructor is called when the object is created.
time. 4. Types of Constructors: Default and Parameterized.

Java OOPs Concepts: What is Java Super Keyword?

1. Inheritance: it is a mechanism in java by which one class 1. The super keyword refers to superclass (parent) objects.
is allowed to inherit the features (fields and methods) of 2. It is used to call superclass methods, and to access the
another class. superclass constructor.
2. Encapsulation: it is a process of wrapping code and data What is Java this Keyword?
together into a single unit, for example, a capsule which is
mixed of several medicines. The public setXXX() and 1. This keyword refers to the current object in a method or
getXXX() methods are the access points of the instance constructor.
variables of the EncapTest class. 2. The most common use of this keyword is to eliminate the
3. Abstraction: it is the process of hiding certain details and confusion between class attributes and parameters with the
showing only essential information to the users. In java, same name (because a class attribute is shadowed by a
abstraction is achieved by interfaces and abstract method or constructor parameter).
classes.
4. Polymorphism: it means having many forms. Using What is the Final Keyword in Java?
polymorphism, we can perform a single action in different 1. The final keyword in java is used to restrict the user. The
ways. It could be achieved by method overloading and java final keyword can be used in many contexts. The
overriding (Runtime Polymorphism). Final can be:
What is a static keyword in Java? a. Variable: If you make any variable as final, you
cannot change the value of final variable (It will
1. In Java, if we want to access class members, we must first be constant).
create an instance of the class. But there will be situations b. Method: If you make any method as final, you
where we want to access class members without creating cannot override it.
any object. c. Class: If you make any class as final, you cannot
2. In those situations, we can use the static keyword in Java. extend it.
3. The static can be:
a. Variable (also known as a class variable): if we What is Exception Handling in Java?
declare a variable static, all objects of the class 1. The Exception Handling in Java is one of the powerful
share the same static variable. mechanism to handle the runtime errors so that the normal
b. Method (also known as a class method): we can flow of the application can be maintained.
invoke static methods directly using the class 2. Java Exception Keywords:
name. a. Try: The "try" keyword is used to specify a block
c. Block: static blocks are used to initialize the static where we should place an exception code.
variables. b. Catch: The "catch" block is used to handle the
i. // static variable: static int age; exception.
ii. // static block: static {age = 23; } c. finally: The "finally" block is used to execute the
d. Nested class necessary code of the program. It is executed
What is an Array in Java? whether an exception is handled or not.

1. Java array is an object which contains elements of a similar What is the difference between Throw and Throws keywords in
data type. Java?
2. int Array = new int[20];
3. int[][] intArray = new int[10][20];
1. Throw: Java throw keyword is used throw an exception 2. Here, keys are unique identifiers used to associate each
explicitly in the code, inside the function or the block of value on a map.
code. Throw is used within the method. 3. It allows one null for key and multiple nulls for values.
4. It uses put method to insert a new element.
2. Throws: Java throws keyword is used in the method
signature to declare an exception which might be thrown What is Hash Table?
by the function while the execution of the code. Throws is 5. It stores elements in key/value pairs, and it uses put
used with the method signature. method to insert a new element.
1. It does not allow null for key as well as for value.
What is finalize() method in Java?
What is Hash Set?
1. The finalize() method is used just before object is
destroyed and can be called just prior to object creation. 1. It does not allow duplicates.
2. It can have a single null value. It uses add method.
What are Java Wrapper Classes? What is the difference between [Link]() and
1. Wrapper classes provide a way to use primitive data types [Link]()?
(int, boolean, etc..) as objects. 1. parseInt(): will be returning the primitive type int.
2. ArrayList<Integer> myNumbers = new 2. valueOf(): will be returning the Integer wrapper Object.
ArrayList<Integer>();
Java Program to “Sort an Array”:
Can We Override Static Method in Java? If not, Why?
1. public class Main {
1. No, we cannot override static methods because methods 2. public static void main(String[] args) {
overriding is based on dynamic binding at runtime and the 3. //define original array
static methods are bonded using static binding at compile 4. int [] intArray = new int []
time. So, we cannot override static methods. {52,45,32,64,12,87,78,98,23,7};
What are collections in Java? 5. int temp = 0;
6. //print original array
1. The Collection in Java is a framework that provides an 7. [Link]("Original array: ");
architecture to store and manipulate the group of objects. 8. for (int i = 0; i <[Link]; i++) {
2. Java Collection means a single unit of objects. Java 9. [Link](intArray[i] + " ");
Collection framework provides many interfaces (Set, List, 10. }
Queue, Deque) and classes (ArrayList, Vector, LinkedList, 11. //Sort the array in ascending order using two for loops
PriorityQueue, HashSet, LinkedHashSet, TreeSet). 12. for (int i = 0; i <[Link]; i++) {
13. for (int j = i+1; j <[Link]; j++) {
What is the difference between Collection and Collections?
14. if(intArray[i] >intArray[j]) { //swap elements if
1. Collection: It is an interface. not in order
2. Collections: It is a utility class. 15. temp = intArray[i];
16. intArray[i] = intArray[j];
What is the difference between Set and List in Java? 17. intArray[j] = temp;
18. }
1. The list implementation allows us to add the same or
19. }
duplicate elements.
20. }
2. The set implementation does not allow us to add the same
21. //print sorted array
or duplicate elements.
22. [Link]("\nArray sorted in ascending
What is Hashing in Java? order: ");
23. for (int i = 0; i <[Link]; i++) {
1. Hashing is the process of mapping the data to some 24. [Link](intArray[i] + " ");
representative integer value using the concept of hashing 25. }
algorithms. 26. }
2. In Java, a hash code is an integer value that is linked with
each object. Java Program to “Split a String”:
3. Hashing finds its data structure implementation in
1. public class SplitExample{
HashTables and HashMaps.
2. public static void main(String args[]){
What is Hash Map? 3. String s1="java string split method by javatpoint";
4. String[] words=[Link]("\\s");//splits the string based on
1. It stores elements in key/value pairs. whitespace
5. //using java foreach loop to print elements of string array
6. for(String w:words){ 8. for(int i=0;i<size;i++) //Use to hold an element
7. [Link](w); 9. {
8. }}} 10. for(int j=i+1;j<size;j++) //Use to check for rest of
the elements
Java Program to “Reverse a String”: 11. {
1. import [Link].*; 12. if(arr[i]<arr[j]) //Compare and swap
2. import [Link]; 13. {
3. class GFG { 14. int temp=arr[i];
4. public static void main (String[] args) { 15. arr[i]=arr[j];
5. String str= "Geeks", nstr=""; 16. arr[j]=temp;
6. char ch; 17. }}}
7. [Link]("Original word: "); 18. [Link]("Largest element is
8. [Link]("Geeks"); //Example word "+arrayname[size-1]); //Display Largest
9. for (int i=0; i<[Link](); i++) 19. }}
10. { Java program to “Extract a word from a string”:
11. ch= [Link](i); //extracts each character
12. nstr= ch+nstr; //adds each character in front of the 1. import [Link];
existing string 2. public class string {
13. } 3. public static void main(String args[]){
14. [Link]("Reversed word: "+ nstr); 4. Scanner sc = new Scanner([Link]);
15. }} 5. String sentence = "This is a bird";
6. [Link]("Enter a word to extract from the
Java Program to “Reverse any String”: string: ");
1. class ReverseString { 7. String wordToextract = [Link]();
2. public static void main(String[] args) 8. if([Link](wordToextract)){
3. { 9. int y = [Link](wordToextract);
4. String input = "Geeks for Geeks"; 10. [Link](y);
5. StringBuilder input1 = new StringBuilder(); 11. String u = [Link](y ,
6. [Link](input); y+([Link]()));
7. [Link](); 12. [Link](u);
8. [Link](input1); }} 13. } }}

What is StringBuilder? Java Program to illustrate a Set and Iterator:

1. StringBuilder in Java is a class used to create a mutable, or 1. import [Link].*;


in other words, a modifiable succession of characters. 2. public class SetDemo {
3. public static void main(String args[])
What is StringBuffer? 4. {
5. Set<String> set = new HashSet<String>();
1. The StringBuffer class is used to create mutable string. It is
6. [Link]("Welcome");
same as String class except it is mutable and thread safe.
7. [Link]("To");
What is the difference between String, StringBuilder and 8. [Link]("Geeks");
StringBuffer? 9. [Link]("4");
10. [Link]("Geeks");
1. If a string can change and will be accessed from multiple 11. [Link]("Set: " + set);
threads, use a StringBuffer because StringBuffer is 12. Iterator value = [Link]();
synchronous, so you have thread-safety. 13. [Link]("The iterator values are: ");
2. If you don’t want thread-safety than you can also go with 14. while ([Link]()) {
StringBuilder class as it is not synchronized. 15. [Link]([Link]());
16. }}}
Java Program to “Find the Largest and Second Largest
Number in a given Array”: Java program to “Find Duplicate elements in an Array”:
1. public class findElement 1. public class DuplicateElement {
2. { 2. public static void main(String[] args) {
3. public static void main(String []args) 3. //Initialize array
4. { 4. int [] arr = new int [] {1, 2, 3, 4, 2, 7, 8, 8, 3};
5. int [] arrayname = new int [] {1, 2, 3, 4, 2, 7, 8, 8, 3}; 5. [Link]("Duplicate elements in given
6. int temp, size; array: ");
7. size = [Link];

Common questions

Powered by AI

Access modifiers in Java—namely, default, private, protected, and public—support encapsulation by controlling the visibility and access levels of classes, constructors, variables, and methods . By restricting access, they allow for a clear separation between a class’s public interface and its implementation details, fostering module independence and security. This encapsulation enhances code maintainability and modularity by allowing internal changes without affecting external dependencies, thus preventing unintended interference and improving reliability and design clarity in software development.

The primary differences between a Set and a List in Java collections are related to element uniqueness and order. A List allows duplicate elements and maintains the order of insertion, meaning elements are accessed by an index . In contrast, a Set does not allow duplicate elements, making it ideal for storing unique items, and it does not maintain any specific order . These distinctions influence how each is used depending on the requirements for data handling and retrieval efficiency.

The 'throw' keyword is used to explicitly throw an exception from a method or code block, while 'throws' is used in a method signature to declare that a method might throw exceptions during its execution . 'Throw' is used within the method to generate an exception on demand, providing precise control over exception generation. On the other hand, 'throws' is part of the method's contract, alerting users or callables of the method to handle specified exceptions, thus supporting exception propagation and checked exception handling.

The static keyword alters the default behavior of variables and methods by associating them with the class rather than any particular instance, meaning there is a single copy shared among all instances . For static variables, this means all instances access the same data point, promoting memory savings and synchronized data points. Static methods do not require instantiation of the class to be called, enabling utility or factory method implementations. Practically, this leads to consistent states for data commonly used by instances, enables easy access to utility methods, and fosters design patterns such as Singleton where state consistency is crucial.

Java achieves immutability primarily through the use of final classes and fields, and by avoiding setters that alter state after construction. By making a class final, it cannot be subclassed, and by making its fields final and private, their values cannot be altered, ensuring that instances remain constant once constructed . Immutability is desirable because it offers thread-safety, as immutable objects do not require synchronization and can be freely shared across threads. This increases predictability, stability, and simplifies debugging since immutable objects are always in a consistent state.

Static methods cannot be overridden in Java because they are bound to the class instead of an instance of the class. Overriding is fundamentally based on dynamic binding at runtime, whereas static methods use static binding at compile time . The implication for object-oriented design is that static methods cannot exhibit polymorphic behavior, which limits their utility in scenarios where runtime method resolution is desired. This encourages the use of static methods for behaviors common to all instances or unrelated to specific instance details.

The 'final' keyword has distinct impacts on variables, methods, and classes in software design and performance. When applied to variables, it makes them constants, optimizing performance by allowing certain compiler optimizations and preventing accidental changes . For methods, 'final' prevents overriding, ensuring that the implementation is preserved and may lead to performance gains through inline expansion by the JVM. When classes are marked as 'final', they become non-extendable, which is a design decision to maintain a fixed behavior and enhance security by preventing further subclass modulations. These uses of 'final' thus facilitate robust, predictable, and secure code.

Polymorphism in Java enhances flexibility and reusability by allowing objects to be treated as instances of their parent class, providing a single interface to perform different functions. It enables method overriding and overloading, which allows the same method to behave differently based on the object it is acting upon . By using polymorphism, developers can write more generic and extensible code, making it possible to integrate new features with minimal changes to existing code bases, thereby promoting code reusability.

Encapsulation relates to method and data protection by bundling the data (fields) and methods that operate on the data into a single unit, or class, and controlling access using access modifiers (private, protected, public). This approach prevents unauthorized interference and modification of data from outside the class, as the data fields are usually kept private and accessed through public methods (getters and setters). Therefore, encapsulation ensures that the internal representation of an object is shielded from the outside world, allowing controlled, secure access and modification.

The 'super' keyword in Java plays a critical role in inheritance by referring to the immediate parent class of a subclass . It is used to call superclass methods and constructors, enabling subclasses to inherit and extend the behavior of parent classes while maintaining their unique behavior. This facilitates the reuse of code because common functionality can be defined in a superclass, preventing code duplication and fostering a hierarchical class structure. Additionally, 'super' helps in accessing overridden methods, supporting polymorphic design and promoting modularity.

You might also like