Study Guide v2.0 - Classes and Objects PDF

Summary

This document provides an overview of classes and objects in Java, focusing on introductory concepts. It defines objects as entities with state and behavior, and classes as templates for creating objects. It also discusses advantages of object-oriented programming (OOP) over procedural programming.

Full Transcript

11/28/24, 2:20 PM Study Guide v2.0 - Classes and Objects Classes and Objects Object Any entity that has state and behavior is known as an object. For example a chair, pen, table, keyboa...

11/28/24, 2:20 PM Study Guide v2.0 - Classes and Objects Classes and Objects Object Any entity that has state and behavior is known as an object. For example a chair, pen, table, keyboard, bike, etc. It can be physical or logical. An Object can be defined as an instance of a class. An object contains an address and takes up some space in memory. Objects can communicate without knowing the details of each other's data or code. The only necessary thing is the type of message accepted and the type of response returned by the objects. Example: A dog is an object because it has states like color, name, breed, etc. as well as behaviors like wagging the tail, barking, eating, etc. Class A class, in the context of Java, are templates that are used to create objects, and to define object data types and methods. Core properties include the data types and methods that may be used by the object A class can also be defined as a blueprint from which you can create an individual object. Class doesn't consume any space. Advantages of OOPs over Procedure Oriented Programming OOPs makes development and maintenance easier whereas in a procedure-oriented programming language it is not easy to manage if code grows as project size increases. OOPs provides data hiding whereas in a procedure-oriented programming language a global data can be accessed from anywhere. public class Dog { String breed; int age; String color; void barking() { } void hungry() { } void sleeping() { } } A class is a blueprint from which individual objects are created. The code above is a sample of a class Dog with attributes and behavior. @Revature 11730 Plaza America Drive, Reston, VA 20190 https://sites.google.com/revature.com/studyguide/oop/classes-and-objects?authuser=0 1/1 11/28/24, 2:20 PM Study Guide v2.0 - Constructors Constructors Constructor In Java, a constructor is a block of codes similar to the method. It is called when an instance of the object is created, and memory is allocated for the object. It is a special type of method which is used to initialize the object. When is a constructor called? When an object is created, compiler makes sure that constructors for all of its subobjects (its member and inherited objects) are called. If members have default constructors or constructor without parameter then these constructors are called automatically, otherwise parameterized constructors can be called using initializer list. Note: It is called constructor because it constructs the values at the time of object creation. It is not necessary to write a constructor for a class. It is because java compiler creates a default constructor if your class doesn't have any. Rules to remember while creating a constructor There are three rules defined for the constructor. Constructor name must be the same as its class name A Constructor must have no explicit return type A Java constructor cannot be abstract, static, final, and synchronized Types of constructors Default Constructor Parameterized Constructor https://sites.google.com/revature.com/studyguide/oop/constructors?authuser=0 1/3 11/28/24, 2:20 PM Study Guide v2.0 - Constructors Default Constructor The default constructor is a no-args constructor that the Java compiler inserts on your behalf; it contains a default call to super(); which is the default behavior. If you implement any constructor then you no longer receive a default constructor. Note : If there is no constructor in the class, the compiler adds a default constructor No-Argument Constructor public Bicycle() { gear = 1; cadence = 10; speed = 0; } Bicycle yourBike = new Bicycle(); invokes the no-argument constructor to create a new Bicycle object called yourBike. Note : The diagram below describes that a default constructor is added by the compiler when there is no constructor declared in the class. Parameterized Constructor A constructor which has a specific number of parameters is called a parameterized constructor. The parameterized constructor is used to provide different values to the distinct objects. However, you can provide the same values also. class Student4{ int id; String name; Student4(int i,String n){ id = i; name = n; } void display(){System.out.println(id+" "+name);} public static void main(String args[]){ Student4 s1 = new Student4(111,"Karan"); Student4 s2 = new Student4(222,"Aryan"); s1.display(); s2.display(); } } In the above example, we have created the constructor of Student class that have two parameters. We can have any number of parameters in the constructor. https://sites.google.com/revature.com/studyguide/oop/constructors?authuser=0 2/3 11/28/24, 2:20 PM Study Guide v2.0 - Constructors Constructor Overloading In Java, a constructor is just like a method but without return type. It can also be overloaded like Java methods. Constructor overloading in Java is a technique of having more than one constructor with different parameter lists. They are arranged in a way that each constructor performs a different task. They are differentiated by the compiler by the number of parameters in the list and their types. class Student5{ int id; String name; int age; //creating two argument constructor Student5(int i,String n){ id = i; name = n; } //creating three argument constructor Student5(int i,String n,int a){ id = i; name = n; age=a; } void display(){System.out.println(id+" "+name+" "+age);} public static void main(String args[]){ Student5 s1 = new Student5(111,"Karan"); Student5 s2 = new Student5(222,"Aryan",25); s1.display(); s2.display(); } } Constructor vs Method Constructor : A constructor is used to initialize the state of an object. A constructor must not have a return type. The constructor is invoked implicitly. The Java compiler provides a default constructor if you don't have any constructor in a class. The constructor name must be same as the class name. Method : A method is used to expose the behavior of an object. A method must have a return type. The method is invoked explicitly. The method is not provided by the compiler in any case. The method name may or may not be same as class name. https://sites.google.com/revature.com/studyguide/oop/constructors?authuser=0 3/3 11/28/24, 2:21 PM Study Guide v2.0 - Inheritance Inheritance Inheritance Inheritance in Java is a mechanism in which one object acquires all the properties and behaviors of a parent object. It is an important part of OOPs (Object Oriented programming system). The idea behind inheritance in Java is that you can create new classes that are built upon existing classes. When you inherit from an existing class, you can reuse methods and fields of the parent class. Moreover, you can add new methods and fields in your current class also. Inheritance represents the IS-A relationship which is also known as a parent-child relationship. Advantages of Inheritance For Method Overriding (so runtime polymorphism can be achieved). For Code Reusability. Terms used in Inheritance Class: A class is a group of objects which have common properties. It is a template or blueprint from which objects are created. Sub Class/Child Class: Subclass is a class which inherits the other class. It is also called a derived class, extended class, or child class. Super Class/Parent Class: Superclass is the class from where a subclass inherits the features. It is also called a base class or a parent class. Reusability: As the name specifies, reusability is a mechanism which facilitates you to reuse the fields and methods of the existing class when you create a new class. You can use the same fields and methods already defined in the previous class. Syntax class Subclass-name extends Superclass-name { //methods and fields added here } The extends keyword indicates that you are making a new class that derives from an existing class. The meaning of "extends" is to increase the functionality. https://sites.google.com/revature.com/studyguide/oop/oop-pillars/inheritance?authuser=0 1/4 11/28/24, 2:21 PM Study Guide v2.0 - Inheritance Example of Inheritance As displayed in the above figure, Programmer is the subclass and Employee is the superclass. The relationship between the two classes is Programmer IS-A Employee. It means that Programmer is a type of Employee. class Employee{ float salary=40000; } class Programmer extends Employee{ int bonus=10000; public static void main(String args[]){ Programmer p=new Programmer(); System.out.println("Programmer salary is:"+p.salary); System.out.println("Bonus of Programmer is:"+p.bonus); } } Types Of Inheritance In Java On the basis of class, there can be three types of inheritance in java: single, multilevel and hierarchical. In java programming, multiple and hybrid inheritance is supported through interface only. We will learn about interfaces later. Single Inheritance class Animal{ void eat(){System.out.println("eating...");} } class Dog extends Animal{ //Single Inheritance void bark(){System.out.println("barking...");} } class TestInheritance{ public static void main(String args[]){ Dog d=new Dog(); d.bark(); d.eat(); }} https://sites.google.com/revature.com/studyguide/oop/oop-pillars/inheritance?authuser=0 2/4 11/28/24, 2:21 PM Study Guide v2.0 - Inheritance Multilevel Inheritance class Animal{ void eat(){System.out.println("eating...");} } class Dog extends Animal{ //Level 1 - Inheritance void bark(){System.out.println("barking...");} } class BabyDog extends Dog{ //Level 2 - Inheritance void weep(){System.out.println("weeping...");} } class TestInheritance2{ public static void main(String args[]){ BabyDog d=new BabyDog(); d.weep(); d.bark(); d.eat(); }} Hierarchical Inheritance class Animal{ void eat(){System.out.println("eating...");} } class Dog extends Animal{ // Hierarchical Inheritance void bark(){System.out.println("barking...");} } class Cat extends Animal{ // Hierarchical Inheritance void meow(){System.out.println("meowing...");} } class TestInheritance3{ public static void main(String args[]){ Cat c=new Cat(); c.meow(); c.eat(); //c.bark(); //Error }} https://sites.google.com/revature.com/studyguide/oop/oop-pillars/inheritance?authuser=0 3/4 11/28/24, 2:21 PM Study Guide v2.0 - Inheritance Why multiple inheritance is not supported in Java? To reduce the complexity and simplify the language, multiple inheritance is not supported in java. Consider a scenario where A, B, and C are three classes. The C class inherits A and B classes. If A and B classes have the same method and you call it from child class object, there will be ambiguity to call the method of A or B class. Since compile-time errors are better than runtime errors, Java renders compile-time error if you inherit 2 classes. So whether you have same method or different, there will be compile time error. class A{ void msg(){System.out.println("Hello");} } class B{ void msg(){System.out.println("Welcome");} } class C extends A,B{ //suppose if it were public static void main(String args[]){ C obj=new C(); obj.msg(); //Now which msg() method would be invoked? } } https://sites.google.com/revature.com/studyguide/oop/oop-pillars/inheritance?authuser=0 4/4 11/28/24, 2:21 PM Study Guide v2.0 - Polymorphism Polymorphism Polymorphism Polymorphism is the ability of an object to take on many forms. The most common use of polymorphism in OOP occurs when a parent class reference is used to refer to a child class object. Any Java object that can pass more than one IS-A test is considered to be polymorphic. In Java, all Java objects are polymorphic since any object will pass the IS-A test for their own type and for the class Object. Method Overloading If a class has multiple methods having same name but different in parameters, it is known as Method Overloading. If we have to perform only one operation, having same name of the methods increases the readability of the program. Suppose you have to perform addition of the given numbers but there can be any number of arguments, if you write the method such as a(int,int) for two parameters, and b(int,int,int) for three parameters then it may be difficult for you as well as other programmers to understand the behavior of the method because its name differs. Different ways to overload a method? There are two ways to overload the method in java By changing number of arguments By changing the data type Method Overloading - Changing the number of arguments class Adder{ static int add(int a,int b){return a+b;} // 2 arguments static int add(int a,int b,int c){return a+b+c;} //3 arguments } class TestOverloading1{ public static void main(String[] args){ System.out.println(Adder.add(11,11)); System.out.println(Adder.add(11,11,11)); }} In the above example, we have created two methods, first add() method performs addition of two numbers and second add method performs addition of three numbers. In the above example, we are creating static methods so that we don't need to create instance for calling methods. https://sites.google.com/revature.com/studyguide/oop/oop-pillars/polymorphism?authuser=0 1/4 11/28/24, 2:21 PM Study Guide v2.0 - Polymorphism Method Overloading - Changing data type of arguments class Adder{ static int add(int a, int b){return a+b;} // 2 arguments of int data type static double add(double a, double b){return a+b;} // 2 arguments of double data type } class TestOverloading2{ public static void main(String[] args){ System.out.println(Adder.add(11,11)); System.out.println(Adder.add(12.3,12.6)); }} In the above example, we have created two methods that differs in data type. The first add method receives two integer arguments and second add method receives two double arguments. Note : Method overloading is not possible by changing the return type of the method. Overloading the main() method in Java class TestOverloading4{ public static void main(String[] args){System.out.println("main with String[]");} public static void main(String args){System.out.println("main with String");} public static void main(){System.out.println("main without args");} } Yes, by method overloading. You can have any number of main methods in a class by method overloading. But JVM calls main() method which receives string array as arguments only. Method Overriding If subclass (child class) has the same method as declared in the parent class, it is known as method overriding in Java. In other words, If a subclass provides the specific implementation of the method that has been declared by one of its parent class, it is known as method overriding. Usage and Rules for Method Overriding Usage : Method overriding is used to provide the specific implementation of a method which is already provided by its superclass. Method overriding is used for runtime polymorphism Rules : The method must have the same name as in the parent class The method must have the same parameter as in the parent class. There must be an IS-A relationship (inheritance). https://sites.google.com/revature.com/studyguide/oop/oop-pillars/polymorphism?authuser=0 2/4 11/28/24, 2:21 PM Study Guide v2.0 - Polymorphism Example for Method Overriding class ABC{ //Overridden method public void disp() { System.out.println("disp() method of parent class"); } } class Demo extends ABC{ //Overriding method public void disp(){ System.out.println("disp() method of Child class"); } public void newMethod(){ System.out.println("new method of child class"); } public static void main( String args[]) { ABC obj = new ABC(); obj.disp(); ABC obj2 = new Demo(); // Covariance with reference types obj2.disp(); } } In the above example, we have defined the disp() method in the subclass as defined in the parent class but it has some specific implementation. The name and parameter list of the methods are the same, and there is IS-A relationship between the classes. Can a static method be overridden? No, a static method cannot be overridden. It can be proved by runtime polymorphism, so we will learn it later. It is because the static method is bound with class whereas instance method is bound with an object. Static belongs to the class area, and an instance belongs to the heap area. Method Overloading vs Method Overriding Method Overloading : Method overloading is used to increase the readability of the program. Method overloading is performed within class. In case of method overloading, parameter must be different. Method overloading is the example of compile time polymorphism. In java, method overloading can't be performed by changing return type of the method only. Return type can be same or different in method overloading. But you must have to change the parameter. Method Overriding : Method overriding is used to provide the specific implementation of the method that is already provided by its super class. Method overriding occurs in two classes that have IS-A (inheritance) relationship. In case of method overriding, parameter must be same. Method overriding is the example of run time polymorphism. Return type must be same or covariant in method overriding. https://sites.google.com/revature.com/studyguide/oop/oop-pillars/polymorphism?authuser=0 3/4 11/28/24, 2:21 PM Study Guide v2.0 - Polymorphism Sample Exercise Consider a scenario where Bank is a class that provides functionality to get the rate of interest. However, the rate of interest varies according to banks. For example, SBI, ICICI and AXIS banks could provide 8%, 7%, and 9% rate of interest. Go ahead and code the above scenario. https://sites.google.com/revature.com/studyguide/oop/oop-pillars/polymorphism?authuser=0 4/4 11/28/24, 2:21 PM Study Guide v2.0 - Encapsulation Encapsulation Encapsulation Encapsulation in Java is a process of wrapping code and data together into a single unit, for example, a capsule which is mixed of several medicines. We can create a fully encapsulated class in Java by making all the data members of the class private. Now we can use setter and getter methods to set and get the data in it. The Java Bean class is the example of a fully encapsulated class. Advantages of Encapsulation By providing only a setter or getter method, you can make the class read-only or write-only. In other words, you can skip the getter or setter methods. It provides you the control over the data. Suppose you want to set the value of id which should be greater than 100 only, you can write the logic inside the setter method. You can write the logic not to store the negative numbers in the setter methods. It is a way to achieve data hiding in Java because other class will not be able to access the data through the private data members. The encapsulate class is easy to test. So, it is better for unit testing. https://sites.google.com/revature.com/studyguide/oop/oop-pillars/encapsulation?authuser=0 1/4 11/28/24, 2:21 PM Study Guide v2.0 - Encapsulation Example for Encapsulation package com.revature; public class Student{ //private data member private String name; //getter method for name public String getName(){ return name; } //setter method for name public void setName(String name){ this.name=name } } //A Java class to test the encapsulated class. package com.revature; class Test{ public static void main(String[] args){ //creating instance of the encapsulated class Student s=new Student(); //setting value in the name member s.setName("vijay"); //getting value of the name member System.out.println(s.getName()); } } The above is an example of encapsulation of a class called Student that has only one field with its setter and getter methods. Read-Only Class //A Java class which has only getter methods. public class Student{ //private data member private String college="AKG"; //getter method for college public String getCollege(){ return college; } } The above class is an example of a Read-Only class because it has only a getter to access the college name. If the user tries to change the value of the college name, a compile-time error is rendered. https://sites.google.com/revature.com/studyguide/oop/oop-pillars/encapsulation?authuser=0 2/4 11/28/24, 2:21 PM Study Guide v2.0 - Encapsulation Write-Only Class //A Java class which has only setter methods. public class Student{ //private data member private String college; //getter method for college public void setCollege(String college){ this.college=college; } } The above class is an example of a Write-Only class because it has only setters to change the value of the college name and cannot read the college name. Even if tried to access outside of this class a compile-time error is displayed only because the variable is declared as private. Access Modifiers There are two types of modifiers in java: access modifiers and non-access modifiers. The access modifiers in java specifies accessibility (scope) of a data member, method, constructor or class. There are 4 types of java access modifiers: private default protected public There are many non-access modifiers such as static, abstract, synchronized, native, volatile, transient etc. Here, we will learn access modifiers. Access Modifiers with Method Overriding class A{ protected void msg(){System.out.println("Hello java");} } public class Simple extends A{ void msg(){System.out.println("Hello java");} // Error because Class Simple method msg() is more restrictive that Class A method msg() public static void main(String args[]){ Simple obj=new Simple(); obj.msg(); } } If you are overriding any method, overridden method (i.e. declared in subclass) must not be more restrictive. https://sites.google.com/revature.com/studyguide/oop/oop-pillars/encapsulation?authuser=0 3/4 11/28/24, 2:21 PM Study Guide v2.0 - Encapsulation Sample Exercise Create an encapsulated class with 4 fields and the respective methods to access and edit those fields. Then go ahead and create a test class to verify. Class Name : Student Field Names : studentId, studentName, collegeName, address Test Class Name : TestStudent https://sites.google.com/revature.com/studyguide/oop/oop-pillars/encapsulation?authuser=0 4/4 11/28/24, 2:22 PM Study Guide v2.0 - Abstraction Abstraction Abstraction Abstraction is a process of hiding the implementation details and showing only functionality to the user. Another way, it shows only essential things to the user and hides the internal details, for example, sending SMS where you type the text and send the message. You don't know the internal processing about the message delivery. Abstraction lets you focus on what the object does instead of how it does it. Generalization Generalization is the process of extracting shared characteristics from two or more classes, and combining them into a generalized superclass. Shared characteristics can be attributes, associations, or methods. Eg : The classes Piece of Luggage and Piece of Cargo partially share the same attributes. From a domain perspective, the two classes are also very similar. During generalization, the shared characteristics are combined and used to create a new superclass Freight. Piece of Luggage and Piece of Cargo become subclasses of the class Freight. Therefore the properties that are common to the classes Piece of Luggage and Piece of Cargo are placed in the superclass Freight - Identification, Weight and ID-Number are those properties. Specialization Specialization means creating new subclasses from an existing class. If it turns out that certain attributes, associations, or methods only apply to some of the objects of the class, a subclass can be created. In the previous example for Generalization, we saw that the classes Piece of Luggage and Piece of Cargo shared similar properties that were placed in a superclass called Freight. When it comes to Specialization, if there is a property that is only applicable to a specific subclass, such as Degree of Hazardousness, that property is placed in the class Piece of Cargo where-in this class also has all the properties of the Freight class with the concept of Generalization. Ways to achieve abstraction? There are two ways to achieve abstraction in java Abstract class (0 to 100%) Interface (100%) https://sites.google.com/revature.com/studyguide/oop/oop-pillars/abstraction?authuser=0 1/2 11/28/24, 2:22 PM Study Guide v2.0 - Abstraction Abstract Class A class which is declared as abstract is known as an abstract class. It can have abstract and non-abstract methods. It needs to be extended and its method implemented. It cannot be instantiated. Some points to remember : An abstract class must be declared with an abstract keyword. It can have abstract and non-abstract methods. It cannot be instantiated. It can have constructors and static methods also. It can have final methods which will force the subclass not to change the body of the method. Abstract Method A method which is declared as abstract and does not have implementation is known as an abstract method. abstract void printStatus(); //no method body and abstract Example of Abstract Class with an Abstract Method abstract class Bike{ // Abstract class abstract void run(); // Abstract method } class Honda4 extends Bike{ void run(){System.out.println("running safely");} public static void main(String args[]){ Bike obj = new Honda4(); obj.run(); } } Sample Exercise : To create an abstract class called Bank. To create an abstract method called getRateOfInterest(); To create two subclasses called SBI - 7% and PNB - 5% as two banks that extend the abstract class Bank. To implement different functionalities for the getRateOfInterest() method in the SBI and PNB classes through the concept of method overriding and print out the interest rate inside the main() method created separately in a test class called TestBank https://sites.google.com/revature.com/studyguide/oop/oop-pillars/abstraction?authuser=0 2/2 11/28/24, 2:22 PM Study Guide v2.0 - Conditional Statements Conditional Statements Decision Making Structures Decision making structures have one or more conditions to be evaluated or tested by the program, along with a statement or statements that are to be executed if the condition is determined to be true, and optionally, other statements to be executed if the condition is determined to be false. Java programming language provides following types of decision making statements. if statement if..else statement nested if statement switch statement IF Statement An if statement consists of a Boolean expression followed by one or more statements. Syntax : if(Boolean_expression) { // Statements will execute if the Boolean expression is true } If the Boolean expression evaluates to true then the block of code inside the if statement will be executed. If not, the first set of code after the end of the if statement (after the closing curly brace) will be executed. Example public class Test { public static void main(String args[]) { int x = 10; if( x < 20 ) { System.out.print("This is if statement"); } } } https://sites.google.com/revature.com/studyguide/java/conditional-statements?authuser=0 1/5 11/28/24, 2:22 PM Study Guide v2.0 - Conditional Statements IF..ELSE Statement An if statement can be followed by an optional else statement, which executes when the Boolean expression is false. Syntax : if(Boolean_expression) { // Executes when the Boolean expression is true }else { // Executes when the Boolean expression is false } Example public class Test { public static void main(String args[]) { int x = 30; if( x < 20 ) { System.out.print("This is if statement"); }else { System.out.print("This is else statement"); } } } IF..ELSE IF Statement An if statement can be followed by an optional else if...else statement, which is very useful to test various conditions using single if...else if statement. When using if, else if, else statements there are a few points to keep in mind. An if can have zero or one else's and it must come after any else if's. An if can have zero to many else if's and they must come before the else. Once an else if succeeds, none of the remaining else if's or else's will be tested. Syntax : if(Boolean_expression 1) { // Executes when the Boolean expression 1 is true }else if(Boolean_expression 2) { // Executes when the Boolean expression 2 is true }else if(Boolean_expression 3) { // Executes when the Boolean expression 3 is true }else { // Executes when the none of the above condition is true. } https://sites.google.com/revature.com/studyguide/java/conditional-statements?authuser=0 2/5 11/28/24, 2:22 PM Study Guide v2.0 - Conditional Statements Example public class Test { public static void main(String args[]) { int x = 30; if( x == 10 ) { System.out.print("Value of X is 10"); }else if( x == 20 ) { System.out.print("Value of X is 20"); }else if( x == 30 ) { System.out.print("Value of X is 30"); }else { System.out.print("This is else statement"); } } } Nested IF Statement It is always legal to nest if-else statements which means you can use one if or else if statement inside another if or else if statement. Syntax : if(Boolean_expression 1) { // Executes when the Boolean expression 1 is true if(Boolean_expression 2) { // Executes when the Boolean expression 2 is true } } Example public class Test { public static void main(String args[]) { int x = 30; int y = 10; if( x == 30 ) { if( y == 10 ) { System.out.print("X = 30 and Y = 10"); } } } } https://sites.google.com/revature.com/studyguide/java/conditional-statements?authuser=0 3/5 11/28/24, 2:22 PM Study Guide v2.0 - Conditional Statements SWITCH Statement A switch statement allows a variable to be tested for equality against a list of values. Each value is called a case, and the variable being switched on is checked for each case. Syntax : switch(expression) { case value : // Statements break; // optional case value : // Statements break; // optional // You can have any number of case statements. default : // Optional // Statements } Rules for SWITCH Statement The variable used in a switch statement can only be integers, convertable integers (byte, short, char), strings and enums. You can have any number of case statements within a switch. Each case is followed by the value to be compared to and a colon. The value for a case must be the same data type as the variable in the switch and it must be a constant or a literal. When the variable being switched on is equal to a case, the statements following that case will execute until a break statement is reached. When a break statement is reached, the switch terminates, and the flow of control jumps to the next line following the switch statement. Not every case needs to contain a break. If no break appears, the flow of control will fall through to subsequent cases until a break is reached. A switch statement can have an optional default case, which must appear at the end of the switch. The default case can be used for performing a task when none of the cases is true. No break is needed in the default case. https://sites.google.com/revature.com/studyguide/java/conditional-statements?authuser=0 4/5 11/28/24, 2:22 PM Study Guide v2.0 - Conditional Statements Example public class Test { public static void main(String args[]) { // char grade = args.charAt(0); char grade = 'C'; switch(grade) { case 'A' : System.out.println("Excellent!"); break; case 'B' : case 'C' : System.out.println("Well done"); break; case 'D' : System.out.println("You passed"); case 'F' : System.out.println("Better try again"); break; default : System.out.println("Invalid grade"); } System.out.println("Your grade is " + grade); } } https://sites.google.com/revature.com/studyguide/java/conditional-statements?authuser=0 5/5 11/28/24, 2:23 PM Study Guide v2.0 - Looping Constructs Looping Constructs Loops In Java There may be a situation when you need to execute a block of code several number of times. In general, statements are executed sequentially: The first statement in a function is executed first, followed by the second, and so on. Programming languages provide various control structures that allow for more complicated execution paths. A loop statement allows us to execute a statement or group of statements multiple times and following is the general form of a loop statement in most of the programming languages. Types Of Loops : Java programming language provides the following types of loop to handle looping requirements : While loop For loop Do..While loop While Loop A while loop statement in Java programming language repeatedly executes a target statement as long as a given condition is true. Syntax : while(Boolean_expression) { // Statements } Here, statement(s) may be a single statement or a block of statements. The condition may be any expression, and true is any non zero value. When executing, if the boolean_expression result is true, then the actions inside the loop will be executed. This will continue as long as the expression result is true. When the condition becomes false, program control passes to the line immediately following the loop. https://sites.google.com/revature.com/studyguide/java/looping-constructs?authuser=0 1/4 11/28/24, 2:23 PM Study Guide v2.0 - Looping Constructs Example public class Test { public static void main(String args[]) { int x = 10; while( x < 20 ) { System.out.print("value of x : " + x ); x++; System.out.print("\n"); } } } For Loop A for loop is a repetition control structure that allows you to efficiently write a loop that needs to be executed a specific number of times. A for loop is useful when you know how many times a task is to be repeated. Syntax : for(initialization; Boolean_expression; update) { // Statements } This is how it works : The initialization step is executed first, and only once. This step allows you to declare and initialize any loop control variables and this step ends with a semi colon (;). Next, the Boolean expression is evaluated. If it is true, the body of the loop is executed. If it is false, the body of the loop will not be executed and control jumps to the next statement past the for loop. After the body of the for loop gets executed, the control jumps back up to the update statement. This statement allows you to update any loop control variables. This statement can be left blank with a semicolon at the end. The Boolean expression is now evaluated again. If it is true, the loop executes and the process repeats (body of loop, then update step, then Boolean expression). After the Boolean expression is false, the for loop terminates. Example public class Test { public static void main(String args[]) { for(int x = 10; x < 20; x = x + 1) { System.out.print("value of x : " + x ); System.out.print("\n"); } } } https://sites.google.com/revature.com/studyguide/java/looping-constructs?authuser=0 2/4 11/28/24, 2:23 PM Study Guide v2.0 - Looping Constructs Do..While Loop A do...while loop is similar to a while loop, except that a do...while loop is guaranteed to execute at least one time. Syntax : do { // Statements }while(Boolean_expression); Notice that the Boolean expression appears at the end of the loop, so the statements in the loop execute once before the Boolean is tested. If the Boolean expression is true, the control jumps back up to do statement, and the statements in the loop execute again. This process repeats until the Boolean expression is false. Example public class Test { public static void main(String args[]) { int x = 10; do { System.out.print("value of x : " + x ); x++; System.out.print("\n"); }while( x < 20 ); } } Enhanced For Loop As of Java 5, the enhanced for loop was introduced. This is mainly used to traverse collection of elements including arrays. Syntax : for(declaration : expression) { // Statements } Declaration − The newly declared block variable, is of a type compatible with the elements of the array you are accessing. The variable will be available within the for block and its value would be the same as the current array element. Expression − This evaluates to the array you need to loop through. The expression can be an array variable or method call that returns an array. https://sites.google.com/revature.com/studyguide/java/looping-constructs?authuser=0 3/4 11/28/24, 2:23 PM Study Guide v2.0 - Looping Constructs Example public class Test { public static void main(String args[]) { int [] numbers = {10, 20, 30, 40, 50}; for(int x : numbers ) { System.out.print( x ); System.out.print(","); } System.out.print("\n"); String [] names = {"James", "Larry", "Tom", "Lacy"}; for( String name : names ) { System.out.print( name ); System.out.print(","); } } } https://sites.google.com/revature.com/studyguide/java/looping-constructs?authuser=0 4/4 11/28/24, 2:23 PM Study Guide v2.0 - Usage of Keywords Usage of Keywords Usage of "this" keyword There can be a lot of usage of java this keyword. In java, this is a reference variable that refers to the current object. Here is given the 6 usage of java this keyword. this can be used to refer current class instance variable. this can be used to invoke current class method (implicitly) this() can be used to invoke current class constructor. this can be passed as an argument in the method call. this can be passed as argument in the constructor call. this can be used to return the current class instance from the method. "this" : to refer current class instance variable The this keyword can be used to refer current class instance variable. If there is ambiguity between the instance variables and parameters, this keyword resolves the problem of ambiguity. class Student{ int rollno; String name; float fee; Student(int rollno,String name,float fee){ this.rollno=rollno; // Refers class instance variable rollno this.name=name; // Refers class instance variable name this.fee=fee; // Refers class instance variable fee } void display(){System.out.println(rollno+" "+name+" "+fee);} } class TestThis2{ public static void main(String args[]){ Student s1=new Student(111,"ankit",5000f); Student s2=new Student(112,"sumit",6000f); s1.display(); s2.display(); }} "this" : to invoke current class method You may invoke the method of the current class by using the this keyword. If you don't use the this keyword, compiler automatically adds this keyword while invoking the method. https://sites.google.com/revature.com/studyguide/java/usage-of-keywords?authuser=0 1/6 11/28/24, 2:23 PM Study Guide v2.0 - Usage of Keywords Example class A{ void m(){System.out.println("hello m");} void n(){ System.out.println("hello n"); //m();//same as this.m() this.m(); // By default added by the compiler } } class TestThis4{ public static void main(String args[]){ A a=new A(); a.n(); }} "this" : to invoke current class constructor The this() constructor call can be used to invoke the current class constructor. It is used to reuse the constructor. In other words, it is used for constructor chaining. Example class A{ A(){System.out.println("hello a");} A(int x){ this(); // Current class constructor is called. System.out.println(x); } } class TestThis5{ public static void main(String args[]){ A a=new A(10); }} Usage of the "new" keyword When you are declaring a class in java, you are just creating a new data type. A class provides the blueprint for objects. You can create an object from a class. Declaration : First, you must declare a variable of the class type. This variable does not define an object. Instantiation and Initialization : Second, you must acquire an actual, physical copy of the object and assign it to that variable. You can do this using the new operator. The new operator instantiates a class by dynamically allocating(i.e, allocation at run time) memory for a new object and returning a reference to that memory. This reference is then stored in the variable. Thus, in Java, all class objects must be dynamically allocated. The new operator is also followed by a call to a class constructor, which initializes the new object. A constructor defines what occurs when an object of a class is created. Constructors are an important part of all classes and have many significant attributes. Example Let us say that we have a class called Student and we need to instantiate this class. The following syntax does that : Student anil = new Student(); https://sites.google.com/revature.com/studyguide/java/usage-of-keywords?authuser=0 2/6 11/28/24, 2:23 PM Study Guide v2.0 - Usage of Keywords Usage of "super" keyword The super keyword in Java is a reference variable which is used to refer immediate parent class object. Whenever you create the instance of subclass, an instance of parent class is created implicitly which is referred by super reference variable. super can be used to refer immediate parent class instance variable. super can be used to invoke immediate parent class method. super() can be used to invoke immediate parent class constructor. Using "super" to refer parent class instance variable We can use super keyword to access the data member or field of parent class. It is used if parent class and child class have same fields. class Animal{ String color="white"; } class Dog extends Animal{ String color="black"; void printColor(){ System.out.println(color); //prints color of Dog class System.out.println(super.color); //prints color of Animal class } } class TestSuper1{ public static void main(String args[]){ Dog d=new Dog(); d.printColor(); }} Using "super" to invoke parent class method The super keyword can also be used to invoke parent class method. It should be used if subclass contains the same method as parent class. In other words, it is used if method is overridden. class Animal{ void eat(){System.out.println("eating...");} } class Dog extends Animal{ void eat(){System.out.println("eating bread...");} void bark(){System.out.println("barking...");} void work(){ super.eat(); // Calling the parent class eat() method using super keyword bark(); } } class TestSuper2{ public static void main(String args[]){ Dog d=new Dog(); d.work(); }} https://sites.google.com/revature.com/studyguide/java/usage-of-keywords?authuser=0 3/6 11/28/24, 2:23 PM Study Guide v2.0 - Usage of Keywords Using "super" to invoke parent class constructor The super keyword can also be used to invoke the parent class constructor. class Animal{ Animal(){System.out.println("animal is created");} } class Dog extends Animal{ Dog(){ super(); // using super keyword to access the parent class constructor. System.out.println("dog is created"); } } class TestSuper3{ public static void main(String args[]){ Dog d=new Dog(); }} Note : While using "super" keyword to access the parent class constructor, remember that it has to be in the first line within the subclass constructor. Static Keyword The static keyword in Java is used for memory management mainly. We can apply java static keyword with variables, methods, blocks and nested class. The static keyword belongs to the class than an instance of the class. The static can be: Variable (also known as a class variable) Method (also known as a class method) Block Nested class https://sites.google.com/revature.com/studyguide/java/usage-of-keywords?authuser=0 4/6 11/28/24, 2:23 PM Study Guide v2.0 - Usage of Keywords Static variable If you declare any variable as static, it is known as a static variable. The static variable can be used to refer to the common property of all objects (which is not unique for each object), for example, the company name of employees, college name of students, etc. The static variable gets memory only once in the class area at the time of class loading. Advantages It makes your program memory efficient (i.e., it saves memory). Example //Java Program to demonstrate the use of static variable class Student{ int rollno;//instance variable String name; static String college ="ITS"; //static variable //constructor Student(int r, String n){ rollno = r; name = n; } //method to display the values void display (){System.out.println(rollno+" "+name+" "+college);} } //Test class to show the values of objects public class TestStaticVariable1{ public static void main(String args[]){ Student s1 = new Student(111,"Karan"); Student s2 = new Student(222,"Aryan"); //we can change the college of all objects by the single line of code //Student.college="BBDIT"; s1.display(); s2.display(); } } Static Explanation Notice the stack, heap and class area in the diagram. https://sites.google.com/revature.com/studyguide/java/usage-of-keywords?authuser=0 5/6 11/28/24, 2:23 PM Study Guide v2.0 - Usage of Keywords Final Keyword The final keyword in java is used to restrict the user. The java final keyword can be used in many context. Final can be: variable method class The final keyword can be applied with the variables, a final variable that have no value it is called blank final variable or uninitialized final variable. It can be initialized in the constructor only. The blank final variable can be static also which will be initialized in the static block only. Example Final Variable : class Bike9{ final int speedlimit=90;//final variable void run(){ speedlimit=400; // Compile Time Error (Cant change final variable value) } public static void main(String args[]){ Bike9 obj=new Bike9(); obj.run(); } }//end of class Final Method : class Bike{ final void run(){System.out.println("running");} } class Honda extends Bike{ void run(){System.out.println("running safely with 100kmph");} // Compile Time Error (Cant override final method) public static void main(String args[]){ Honda honda= new Honda(); honda.run(); } } Final Class : final class Bike{} class Honda1 extends Bike{ // Compile Time Error (Cant extend final class) void run(){System.out.println("running safely with 100kmph");} public static void main(String args[]){ Honda1 honda= new Honda1(); honda.run(); } } https://sites.google.com/revature.com/studyguide/java/usage-of-keywords?authuser=0 6/6 11/28/24, 2:23 PM Study Guide v2.0 - String Manipulation String Manipulation What is a String? Strings, which are widely used in Java programming, are a sequence of characters. In Java programming language, strings are treated as objects. The Java platform provides the String class to create and manipulate strings. Creating Strings The most direct way to create a string is to write : String greeting = "hello world"; Whenever it encounters a string literal in your code, the compiler creates a String object with its value in this case, "Hello world!'. As with any other object, you can create String objects by using the new keyword and a constructor. The String class has 11 constructors that allow you to provide the initial value of the string using different sources, such as an array of characters. Example public class StringDemo { public static void main(String args[]) { char[] helloArray = { 'h', 'e', 'l', 'l', 'o', '.' }; String helloString = new String(helloArray); System.out.println( helloString ); } } Note : The String class is immutable, so that once it is created a String object cannot be changed. If there is a necessity to make a lot of modifications to Strings of characters, then you should use String Buffer & String Builder Classes. String Length Methods used to obtain information about an object are known as accessor methods. One accessor method that you can use with strings is the length() method, which returns the number of characters contained in the string object. Example public class StringDemo { public static void main(String args[]) { String palindrome = "Dot saw I was Tod"; int len = palindrome.length(); // Using the length method System.out.println( "String Length is : " + len ); } } https://sites.google.com/revature.com/studyguide/java/string-manipulation?authuser=0 1/2 11/28/24, 2:23 PM Study Guide v2.0 - String Manipulation Concatenating Strings The String class includes a method for concatenating two strings : string1.concat(string2); This returns a new string that is string1 with string2 added to it at the end. You can also use the concat() method with string literals "My Name is".concat("Zara"); Strings are most commonly concatenated with the "+" operator "Hello," + " world" + "!" Example public class StringDemo { public static void main(String args[]) { String string1 = "saw I was "; System.out.println("Dot " + string1 + "Tod"); } } Some String Handling Methods char charAt(int index) - Returns the character at the specified index. int compareTo(Object o) - Compares this String to another Object. String concat(String str) - Concatenates the specified string to the end of this string. boolean equals(Object anObject) - Compares this string to the specified object. boolean equalsIgnoreCase(String anotherString) - Compares this String to another String, ignoring case considerations. https://sites.google.com/revature.com/studyguide/java/string-manipulation?authuser=0 2/2 11/28/24, 2:24 PM Study Guide v2.0 - Packages Packages Package? A java package is a group of similar types of classes, interfaces and sub-packages. Package in java can be categorized in two form, built-in package and user-defined package. There are many built-in packages such as java, lang, awt, javax, swing, net, io, util, sql etc. Advantages Of Packages Java package is used to categorize the classes and interfaces so that they can be easily maintained. Java package provides access protection. Java package removes naming collision. Example //save as Simple.java package com.revature; public class Simple{ public static void main(String args[]){ System.out.println("Welcome to package"); } } Accessing a package from other packages There are three ways to access the package from outside the package. import package.*; import package.classname; fully qualified name. Using packagename.* If you use package.* then all the classes and interfaces of this package will be accessible but not subpackages. The import keyword is used to make the classes and interface of another package accessible to the current package. //save by A.java package pack; public class A{ public void msg(){System.out.println("Hello");} } //save as B.java package mypack; import pack.*; //Importing the package named pack which contains class A. class B{ public static void main(String args[]){ A obj = new A(); obj.msg(); } } https://sites.google.com/revature.com/studyguide/java/packages?authuser=0 1/2 11/28/24, 2:24 PM Study Guide v2.0 - Packages Using packagename.classname If you import package.classname then only declared class of this package will be accessible. //save by A.java package pack; public class A{ public void msg(){System.out.println("Hello");} } //save by B.java package mypack; import pack.A; //Importing class A from packagename pack which gives us access to only A. class B{ public static void main(String args[]){ A obj = new A(); obj.msg(); } } Using fully qualified name If you use fully qualified name then only declared class of this package will be accessible. Now there is no need to import. But you need to use fully qualified name every time when you are accessing the class or interface. It is generally used when two packages have same class name e.g. java.util and java.sql packages contain Date class. //save by A.java package pack; public class A{ public void msg(){System.out.println("Hello");} } //save by B.java package mypack; class B{ public static void main(String args[]){ pack.A obj = new pack.A(); // using fully qualified name obj.msg(); } } Sequence of program Sequence of the program must be package then import then class. https://sites.google.com/revature.com/studyguide/java/packages?authuser=0 2/2 11/28/24, 2:24 PM Study Guide v2.0 - Interface Interface Interface? An interface is a reference type in Java. It is similar to class. It is a collection of abstract methods. A class implements an interface, thereby inheriting the abstract methods of the interface. Along with abstract methods, an interface may also contain constants, default methods, static methods, and nested types. Method bodies exist only for default methods and static methods. Writing an interface is similar to writing a class. But a class describes the attributes and behaviors of an object. And an interface contains behaviors that a class implements. Unless the class that implements the interface is abstract, all the methods of the interface need to be defined in the class. Similarities between an interface and a class An interface can contain any number of methods. An interface is written in a file with a.java extension, with the name of the interface matching the name of the file. The byte code of an interface appears in a.class file. Interfaces appear in packages, and their corresponding bytecode file must be in a directory structure that matches the package name. Differences between an interface and a class You cannot instantiate an interface. An interface does not contain any constructors. All of the methods in an interface are abstract. An interface cannot contain instance fields. The only fields that can appear in an interface must be declared both static and final. An interface is not extended by a class, it is implemented by a class. An interface can extend multiple interfaces. https://sites.google.com/revature.com/studyguide/java/interface?authuser=0 1/4 11/28/24, 2:24 PM Study Guide v2.0 - Interface Declaring Interfaces The interface keyword is used to declare an interface. import java.lang.*; // Any number of import statements public interface NameOfInterface { // Any number of final, static fields // Any number of abstract method declarations\ } An interface is implicitly abstract. You do not need to use the abstract keyword while declaring an interface. Each method in an interface is also implicitly abstract, so the abstract keyword is not needed. Methods in an interface are implicitly public. Example interface Animal { public void eat(); public void travel(); } https://sites.google.com/revature.com/studyguide/java/interface?authuser=0 2/4 11/28/24, 2:24 PM Study Guide v2.0 - Interface Implementing Interfaces When a class implements an interface, you can think of the class as signing a contract, agreeing to perform the specific behaviors of the interface. If a class does not perform all the behaviors of the interface, the class must declare itself as abstract. A class uses the implements keyword to implement an interface. The implements keyword appears in the class declaration following the extends portion of the declaration. Example public class MammalInt implements Animal { public void eat() { System.out.println("Mammal eats"); } public void travel() { System.out.println("Mammal travels"); } public int noOfLegs() { return 0; } public static void main(String args[]) { MammalInt m = new MammalInt(); m.eat(); m.travel(); } } Rules to Remember : A class can implement more than one interface at a time. A class can extend only one class, but implement many interfaces. An interface can extend another interface, in a similar way as a class can extend another class. https://sites.google.com/revature.com/studyguide/java/interface?authuser=0 3/4 11/28/24, 2:24 PM Study Guide v2.0 - Interface Extending Interfaces An interface can extend another interface in the same way that a class can extend another class. The extends keyword is used to extend an interface, and the child interface inherits the methods of the parent interface. Example // Filename: Sports.java public interface Sports { public void setHomeTeam(String name); public void setVisitingTeam(String name); } // Filename: Football.java public interface Football extends Sports { public void homeTeamScored(int points); public void visitingTeamScored(int points); public void endOfQuarter(int quarter); } // Filename: Hockey.java public interface Hockey extends Sports { public void homeGoalScored(); public void visitingGoalScored(); public void endOfPeriod(int period); public void overtimePeriod(int ot); } The Hockey interface has four methods, but it inherits two from Sports. Thus, a class that implements Hockey needs to implement all six methods. Similarly, a class that implements Football needs to define the three methods from Football and the two methods from Sports. Extending Multiple Interfaces A Java class can only extend one parent class. Multiple inheritance is not allowed. Interfaces are not classes, however, and an interface can extend more than one parent interface. The extends keyword is used once, and the parent interfaces are declared in a comma-separated list. Example public interface Hockey extends Sports, Event https://sites.google.com/revature.com/studyguide/java/interface?authuser=0 4/4 11/28/24, 2:24 PM Study Guide v2.0 - Exceptions Exceptions Exceptions? Exceptions are events that occur during the execution of programs that disrupt the normal flow of instructions (e.g. divide by zero, array access out of bound, etc.). In Java, an exception is an object that wraps an error event that occurred within a method and contains: Information about the error including its type The state of the program when the error occurred Optionally, other custom information Categories of Exceptions : Checked Exceptions Unchecked Exceptions Errors Checked Exceptions Checked exceptions are those that : The compiler enforces that you handle them explicitly. Methods that generate checked exceptions must declare that they throw them. Methods that invoke other methods that throw checked exceptions must either handle them (they can be reasonably expected to recover) or let them propagate by declaring that they throw them. Example If you use FileReader class in your program to read data from a file, if the file specified in its constructor doesn't exist, then a FileNotFoundException occurs, and the compiler prompts the programmer to handle the exception. import java.io.File; import java.io.FileReader; public class FilenotFoundDemo { public static void main(String args[]) { File file = new File("E://file.txt"); //If the file does not exist an exception is thrown. That exception is called as FileNotFoundException FileReader fr = new FileReader(file); } } https://sites.google.com/revature.com/studyguide/java/exceptions?authuser=0 1/4 11/28/24, 2:24 PM Study Guide v2.0 - Exceptions Unchecked Exceptions Errors and RuntimeExceptions are unchecked — that is, the compiler does not enforce (check) that you handle them explicitly. Methods do not have to declare that they throw them (in the method signatures). It is assumed that the application cannot do anything to recover from these exceptions (at runtime). Example If you have declared an array of size 5 in your program, and trying to call the 6th element of the array then an ArrayIndexOutOfBoundsException occurs. public class Unchecked_Demo { public static void main(String args[]) { int num[] = {1, 2, 3, 4}; System.out.println(num); } } Errors These are not exceptions at all, but problems that arise beyond the control of the user or the programmer. Errors are typically ignored in your code because you can rarely do anything about an error. For example, if a stack overflow occurs, an error will arise. They are also ignored at the time of compilation. Exception Hierarchy All exception classes are subtypes of the java.lang.Exception class. The exception class is a subclass of the Throwable class. Other than the exception class there is another subclass called Error which is derived from the Throwable class. https://sites.google.com/revature.com/studyguide/java/exceptions?authuser=0 2/4 11/28/24, 2:24 PM Study Guide v2.0 - Exceptions Catching Exceptions A method catches an exception using a combination of the try and catch keywords. A try/catch block is placed around the code that might generate an exception. Code within a try/catch block is referred to as protected code, and the syntax for using try/catch looks like the following try { // Protected code } catch (ExceptionName e1) { // Catch block } The code which is prone to exceptions is placed in the try block. When an exception occurs, that exception occurred is handled by catch block associated with it. Every try block should be immediately followed either by a catch block or finally block. A catch statement involves declaring the type of exception you are trying to catch. If an exception occurs in protected code, the catch block (or blocks) that follows the try is checked. If the type of exception that occurred is listed in a catch block, the exception is passed to the catch block much as an argument is passed into a method parameter. Example The following is an array declared with 2 elements. Then the code tries to access the 3rd element of the array which throws an exception. // File Name : ExcepTest.java import java.io.*; public class ExcepTest { public static void main(String args[]) { try { int a[] = new int; // Size 2 System.out.println("Access element three :" + a); // Accessing 3rd element } catch (ArrayIndexOutOfBoundsException e) { System.out.println("Exception thrown :" + e); } System.out.println("Out of the block"); } } The Throw/Throws Keyword If a method does not handle a checked exception, the method must declare it using the throws keyword. The throws keyword appears at the end of a method's signature. One can throw an exception, either a newly instantiated one or an exception that you just caught, by using the throw keyword. Understand the difference between throws and throw keywords, throws is used to postpone the handling of a checked exception and throw is used to invoke an exception explicitly. Example import java.io.*; public class className { public void deposit(double amount) throws RemoteException { // Method implementation throw new RemoteException(); } // Remainder of class definition } https://sites.google.com/revature.com/studyguide/java/exceptions?authuser=0 3/4 11/28/24, 2:24 PM Study Guide v2.0 - Exceptions Finally Block The finally block follows a try block or a catch block. A finally block of code always executes, irrespective of occurrence of an Exception. Using a finally block allows you to run any cleanup-type statements that you want to execute, no matter what happens in the protected code. A finally block appears at the end of the catch blocks and has the following syntax try { // Protected code } catch (ExceptionType1 e1) { // Catch block } catch (ExceptionType2 e2) { // Catch block } catch (ExceptionType3 e3) { // Catch block }finally { // The finally block always executes. } Example public class ExcepTest { public static void main(String args[]) { int a[] = new int; // Size 2 try { System.out.println("Access element three :" + a); // Accessing 3rd element } catch (ArrayIndexOutOfBoundsException e) { System.out.println("Exception thrown :" + e); }finally { // Always executed no matter what! a = 6; System.out.println("First element value: " + a); System.out.println("The finally statement is executed"); } } } Output : Exception thrown :java.lang.ArrayIndexOutOfBoundsException: 3 First element value: 6 The finally statement is executed https://sites.google.com/revature.com/studyguide/java/exceptions?authuser=0 4/4 11/28/24, 2:24 PM Study Guide v2.0 - Data Structures Data Structures Array Normally, an array is a collection of similar type of elements that have a contiguous memory location. Java array is an object which contains elements of a similar data type. It is a data structure where we store similar elements. We can store only a fixed set of elements in a Java array. Array in java is index-based, the first element of the array is stored at the 0 index. Advantages Code Optimization: It makes the code optimized, we can retrieve or sort the data efficiently. Random access: We can get any data located at an index position Disadvantages Size Limit: We can store only the fixed size of elements in the array. It doesn't grow its size at runtime. To solve this problem, collection framework is used in Java which grows automatically. Types of Array There are two types of array. Single Dimensional Array Multidimensional Array https://sites.google.com/revature.com/studyguide/java/data-structures?authuser=0 1/4 11/28/24, 2:24 PM Study Guide v2.0 - Data Structures Example //Java Program to illustrate how to declare, instantiate, initialize //and traverse the Java array. class Testarray{ public static void main(String args[]){ int a[]=new int; //declaration and instantiation a=10; //initialization a=20; a=70; a=40; a=50; //traversing array for(int i=0;i

Use Quizgecko on...
Browser
Browser