Output of Java Program | Set 7 - GeeksforGeeks
Description: A Computer Science portal for geeks. It contains well written, well thought and well explained computer science and programming articles, quizzes and practice/competitive programming/company interview Questions.
Keywords: Data Structures, Algorithms, Python, Java, C, C++, JavaScript, Android Development, SQL, Data Science, Machine Learning, PHP, Web Development, System Design, Tutorial, Technical Blogs, Interview Experience, Interview Preparation, Programming, Competitive Programming, Jobs, Coding Contests, GATE CSE, HTML, CSS, React, NodeJS, Placement, Aptitude, Quiz, Computer Science, Programming Examples, GeeksforGeeks Courses, Puzzles, SSC, Banking, UPSC, Commerce, Finance, CBSE, School, k12, General Knowledge, News, Mathematics, Exams
Date: 2016-11-07 18:29:48+00:00

- Java Arrays
- Java Strings
- Java OOPs
- Java Collection
- Java 8 Tutorial
- Java Multithreading
- Java Exception Handling
- Java Programs
- Java Project
- Java Collections Interview
- Java Interview Questions
- Java MCQs
- Spring
- Spring MVC
- Spring Boot
- Hibernate

Open In App

# Output of Java Program | Set 7

Last Updated : 28 Jun, 2021
Summarize
Comments
Improve

Suggest changes
Like Article
Like
Save
Share
Report
Follow

Difficulty level : Intermediate

Predict the output of following Java Programs.

Program 1 :

`public` `class` `Calculator` `{` `` `int` `num =` `100``;` `` `public` `void` `calc(``int` `num) {` `this``.num = num *` `10``; }` `` `public` `void` `printNum() { System.out.println(num); }` `` `` `public` `static` `void` `main(String[] args)` `` `{` `` `Calculator obj =` `new` `Calculator();` `` `obj.calc(``2``);` `` `obj.printNum();` `` `}` `}`

Options :
A) 20
B) 100
C) 1000
D) 2
Answer : A) 20
Explanation : Here the class instance variable name(num) is same as calc() method local variable name(num). So for referencing class instance variable from calc() method, this keyword is used. So in statement this.num = num * 10, num represents local variable of the method whose value is 2 and this.num represents class instance variable whose initial value is 100. Now in printNum() method, as it has no local variable whose name is same as class instance variable, so we can directly use num to reference instance variable, although this.num can be used.

Program 2 :

`public` `class` `MyStuff` `{` `` `String name;` `` `` `MyStuff(String n) { name = n; }` `` `` `public` `static` `void` `main(String[] args)` `` `{` `` `MyStuff m1 =` `new` `MyStuff(``"guitar"``);` `` `MyStuff m2 =` `new` `MyStuff(``"tv"``);` `` `System.out.println(m2.equals(m1));` `` `}` `` `` `@Override` `` `public` `boolean` `equals(Object obj)` `` `{` `` `MyStuff m = (MyStuff) obj;` `` `if` `(m.name !=` `null``) {` `return` `true``; }` `` `return` `false``;` `` `}` `}`

Options :
A) The output is true and MyStuff fulfills the Object.equals() contract.
B) The output is false and MyStuff fulfills the Object.equals() contract.
C) The output is true and MyStuff does NOT fulfill the Object.equals() contract.
D) The output is false and MyStuff does NOT fulfill the Object.equals() contract.

Answer : C) The output is true and MyStuff does NOT fulfill the Object.equals() contract.
Explanation : As equals(Object obj) method in Object class, compares two objects on the basis of equivalence relation. But here we are just confirming that the object is null or not, So it doesn’t fulfill Object.equals() contract. As m1 is not null, true will be printed.

Program 3 :

`class` `Alpha` `{` `` `public` `String type =` `"a "``;` `` `public` `Alpha() { System.out.print(``"alpha "``); }` `}` `` `public` `class` `Beta` `extends` `Alpha` `{` `` `public` `Beta() { System.out.print(``"beta "``); }` `` `` `void` `go()` `` `{` `` `type =` `"b "``;` `` `System.out.print(``this``.type +` `super``.type);` `` `}` `` `` `public` `static` `void` `main(String[] args)` `` `{` `` `new` `Beta().go();` `` `}` `}`

Options :
A) alpha beta b b
B) alpha beta a b
C) beta alpha b b
D) beta alpha a b

Answer : A) alpha beta b b
Explanation : The statement new Beta().go() executes in two phases. In first phase Beta class constructor is called. There is no instance member present in Beta class. So now Beta class constructor is executed. As Beta class extends Alpha class, so call goes to Alpha class constructor as first statement by default(Put by the compiler) is super() in the Beta class constructor. Now as one instance variable(type) is present in Alpha class, so it will get memory and now Alpha class constructor is executed, then call return to Beta class constructor next statement. So alpha beta is printed.
In second phase go() method is called on this object. As there is only one variable(type) in the object whose value is a. So it will be changed to b and printed two times. The super keyword here is of no use.

Program 4 :

`public` `class` `Test` `{` `` `public` `static` `void` `main(String[] args)` `` `{` `` `StringBuilder s1 =` `new` `StringBuilder(``"Java"``);` `` `String s2 =` `"Love"``;` `` `s1.append(s2);` `` `s1.substring(``4``);` `` `int` `foundAt = s1.indexOf(s2);` `` `System.out.println(foundAt);` `` `}` `}`

Options :
A) -1
B) 3
C) 4
D) A StringIndexOutOfBoundsException is thrown at runtime.
Answer : C) 4
Explanation : append(String str) method,concatenate the str to s1. The substring(int index) method return the String from the given index to the end. But as there is no any String variable to store the returned string,so it will be destroyed.Now indexOf(String s2) method return the index of first occurrence of s2. So 4 is printed as s1=”JavaLove”.

Program 5 :

`class` `Writer` `{` `` `public` `static` `void` `write()` `` `{` `` `System.out.println(``"Writing..."``);` `` `}` `}` `class` `Author` `extends` `Writer` `{` `` `public` `static` `void` `write()` `` `{` `` `System.out.println(``"Writing book"``);` `` `}` `}` `` `public` `class` `Programmer` `extends` `Author` `{` `` `public` `static` `void` `write()` `` `{` `` `System.out.println(``"Writing code"``);` `` `}` `` `` `public` `static` `void` `main(String[] args)` `` `{` `` `Author a =` `new` `Programmer();` `` `a.write();` `` `}` `}`

Options :
A) Writing…
B) Writing book
C) Writing code
D) Compilation fails

Answer : B) Writing book
Explanation : Since static methods can’t be overridden, it doesn’t matter which class object is created. As a is a Author referenced type, so always Author class method is called. If we remove write() method from Author class then Writer class method is called, as Author class extends Writer class.

Next Article
Java Data Types

G

Gaurav Miglani
Improve

### Similar Reads

- Output of Java program | Set 17
  1) What is the output of following program? public class Test { private static float temp() { public static float sum = 21; return(--(sum)); } public static void main(String[] args) { Test test = new Test(); System.out.println(test.temp()); } } a) 21 b) 20 c) Compilation error d) Runtime error Ans.
  2 min read
- Output of Java Program | Set 1
  Difficulty Level: Rookie Predict the output of the following Java Programs.Program 1: Java Code // filename Main.java class Test { protected int x, y; } class Main { public static void main(String args[]) { Test t = new Test(); System.out.println(t.x + &quot; &quot; + t.y); } } Output: 0 0 I
  3 min read
- Output of Java Program | Set 3
  Predict the output of the following Java Programs: Example1: Java Code // filename: Test.java class Test { // Declaring and initializing integer variable int x = 10; // Main driver method public static void main(String[] args) { // Creating an object of class inside main() Test t = new Test(); // Pr
  3 min read
- Output of Java Program | Set 6
  Difficulty level : Intermediate Predict the output of following Java Programs. Program 1: class First { public First() { System.out.println("a"); } } class Second extends First { public Second() { System.out.println("b"); } } class Third extends Second { public Third() { System.o
  2 min read
- Output of Java Program | Set 19
  Predict the output of following Java Programs. Program 1 : public class RuntimePolymorphism { public static void main(String[] args) { A a = new B(); B b = new B(); System.out.println(a.c + " " + a.getValue() + " " + b.getValue() + " " + b.getSuperValue()); } } class A
  3 min read
- Output of Java program | Set 23 (Inheritance)
  Prerequisite: Inheritance in Java 1) What is the output of the following program? Java Code public class A extends B { public static String sing() { return "fa"; } public static void main(String[] args) { A a = new A(); B b = new A(); System.out.println(a.sing() + " " + b.sing())
  3 min read
- Output of Java programs | Set 13 (Collections)
  Prerequisite - Collections in Java 1) What is the output of the following program? Java Code import java.util.*; public class priorityQueue { public static void main(String[] args) { PriorityQueue<Integer> queue = new PriorityQueue<>(); queue.add(11); queue.add(10); queue.add(22); queue.
  3 min read
- Output of Java Programs | Set 14 (Constructors)
  Prerequisite - Java Constructors 1) What is the output of the following program? [GFGTABS] Java class Helper { private int data; private Helper() { data = 5; } } public class Test { public static void main(String[] args) { Helper help = new Helper(); System.out.println(help.data); } } [/GFGTABS]a) C
  3 min read
- Output of Java programs | Set 24 (Final Modifier)
  Difficulty level : Easy Prerequisite : final keyword in java Predict the output of following Java Programs: What will be output of following program? class Test { final int MAXIMUM; final double PI; public Test(int max) { MAXIMUM = max; } public Test(double pi) { PI = pi; } public static void main(S
  3 min read
- Output of Java program | Set 12(Exception Handling)
  Prerequisites : Exception handling , control flow in try-catch-finally 1) What is the output of the following program? public class Test { public static void main(String[] args) { try { System.out.printf("1"); int sum = 9 / 0; System.out.printf("2"); } catch(ArithmeticException e
  3 min read
- How to Run Java Program?
  Java is a popular, high-level, object-oriented programming language that was developed by James Gosling and his team at Sun Microsystems (now owned by Oracle Corporation) in the mid-1990s. It is widely used for developing various kinds of software, including web applications, desktop applications, m
  2 min read
- Shift Operator in Java
  Operators in Java are used to performing operations on variables and values. Examples of operators: +, -, *, /, >>, <<. Types of operators: Arithmetic Operator,Shift Operator,Relational Operator,Bitwise Operator,Logical Operator,Ternary Operator andAssignment Operator. In this article, w
  4 min read
- System.out.println in Java
  Java System.out.println() is used to print an argument that is passed to it. Parts of System.out.println()The statement can be broken into 3 parts which can be understood separately: System: It is a final class defined in the java.lang package.out: This is an instance of PrintStream type, which is a
  5 min read
- Few Tricky Programs in Java
  Comments that execute : Till now, we were always taught "Comments do not Execute". Let us see today "The comments that execute" Following is the code snippet: public class Testing { public static void main(String[] args) { // the line below this gives an output // \u000d System.out.println("com
  2 min read
- Java Program to Update the List Items
  In Java, Lists are dynamic collections that allow modifications, such as updating elements. We can use the set method to update the elements in the List. This method replaces the element at the given index with a new value, allowing modification of list contents. In this article, we will learn to up
  2 min read
- Java Tricky Output Questions
  Question 1: What will be the Output of the below code: public class A { public static void main(String[] args) { if (true) break; } } Choices: a) Nothing b) Error Answer: b) Error Reason: Break statement can only be used with loop or switch. So, using break with if statement causes "break outside sw
  3 min read
- Java Hello World Program
  Java is one of the most popular and widely used programming languages and platforms. Java is fast, reliable, and secure. Java is used in every nook and corner from desktop to web applications, scientific supercomputers to gaming consoles, cell phones to the Internet. In this article, we will learn h
  5 min read
- Redirecting System.out.println() Output to a File in Java
  System.out.println() is used mostly to print messages to the console. However very few of us are actually aware of its working mechanism. We can use System.out.println() to print messages to other sources too, not just restricting it to the console. However, before doing so, we must reassign the sta
  2 min read
- Formatted Output in Java using printf()
  Sometimes in programming, it is essential to print the output in a given specified format. Most users are familiar with the printf function in C. Let us discuss how we can Formatting Output with printf() in Java in this article. Formatting Using Java Printf()printf() uses format specifiers for forma
  5 min read

Article Tags :

- Java

Practice Tags :

- Java

Explore More

We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
Suggest Changes
min 4 words, max CharLimit:2000

## What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences